Repository: vietj/reactive-pg-client Branch: master Commit: 5250ef2a67f3 Files: 507 Total size: 7.6 MB Directory structure: gitextract_38znhpqz/ ├── .editorconfig ├── .gitignore ├── .travis.deploy.artifacts.sh ├── .travis.maven.settings.xml ├── .travis.yml ├── BENCHMARK.md ├── Dockerfile ├── LICENSE.txt ├── README.adoc ├── RELEASES.adoc ├── docker/ │ ├── postgres/ │ │ ├── README.md │ │ ├── docker-compose.yml │ │ ├── resources/ │ │ │ ├── create-postgres.sql │ │ │ ├── server.crt │ │ │ └── server.key │ │ └── ssl.sh │ └── postgres_tc/ │ ├── Dockerfile │ ├── README.md │ └── create-postgres.sql ├── docs/ │ ├── README.md │ ├── _config.yml │ ├── apidocs/ │ │ ├── allclasses-frame.html │ │ ├── allclasses-noframe.html │ │ ├── constant-values.html │ │ ├── deprecated-list.html │ │ ├── help-doc.html │ │ ├── index-all.html │ │ ├── index.html │ │ ├── io/ │ │ │ └── reactiverse/ │ │ │ ├── pgclient/ │ │ │ │ ├── Json.html │ │ │ │ ├── JsonImpl.html │ │ │ │ ├── Numeric.html │ │ │ │ ├── PgClient.html │ │ │ │ ├── PgConnectOptions.html │ │ │ │ ├── PgConnectOptionsConverter.html │ │ │ │ ├── PgConnection.html │ │ │ │ ├── PgCursor.html │ │ │ │ ├── PgException.html │ │ │ │ ├── PgIterator.html │ │ │ │ ├── PgNotification.html │ │ │ │ ├── PgNotificationConverter.html │ │ │ │ ├── PgPool.html │ │ │ │ ├── PgPoolOptions.html │ │ │ │ ├── PgPoolOptionsConverter.html │ │ │ │ ├── PgPreparedQuery.html │ │ │ │ ├── PgResult.html │ │ │ │ ├── PgRowSet.html │ │ │ │ ├── PgStream.html │ │ │ │ ├── PgTransaction.html │ │ │ │ ├── Row.html │ │ │ │ ├── SslMode.html │ │ │ │ ├── Tuple.html │ │ │ │ ├── class-use/ │ │ │ │ │ ├── Json.html │ │ │ │ │ ├── JsonImpl.html │ │ │ │ │ ├── Numeric.html │ │ │ │ │ ├── PgClient.html │ │ │ │ │ ├── PgConnectOptions.html │ │ │ │ │ ├── PgConnectOptionsConverter.html │ │ │ │ │ ├── PgConnection.html │ │ │ │ │ ├── PgCursor.html │ │ │ │ │ ├── PgException.html │ │ │ │ │ ├── PgIterator.html │ │ │ │ │ ├── PgNotification.html │ │ │ │ │ ├── PgNotificationConverter.html │ │ │ │ │ ├── PgPool.html │ │ │ │ │ ├── PgPoolOptions.html │ │ │ │ │ ├── PgPoolOptionsConverter.html │ │ │ │ │ ├── PgPreparedQuery.html │ │ │ │ │ ├── PgResult.html │ │ │ │ │ ├── PgRowSet.html │ │ │ │ │ ├── PgStream.html │ │ │ │ │ ├── PgTransaction.html │ │ │ │ │ ├── Row.html │ │ │ │ │ ├── SslMode.html │ │ │ │ │ └── Tuple.html │ │ │ │ ├── data/ │ │ │ │ │ ├── Box.html │ │ │ │ │ ├── BoxConverter.html │ │ │ │ │ ├── Circle.html │ │ │ │ │ ├── CircleConverter.html │ │ │ │ │ ├── Interval.html │ │ │ │ │ ├── IntervalConverter.html │ │ │ │ │ ├── Json.html │ │ │ │ │ ├── Line.html │ │ │ │ │ ├── LineConverter.html │ │ │ │ │ ├── LineSegment.html │ │ │ │ │ ├── LineSegmentConverter.html │ │ │ │ │ ├── Numeric.html │ │ │ │ │ ├── Path.html │ │ │ │ │ ├── PathConverter.html │ │ │ │ │ ├── Point.html │ │ │ │ │ ├── PointConverter.html │ │ │ │ │ ├── Polygon.html │ │ │ │ │ ├── PolygonConverter.html │ │ │ │ │ ├── class-use/ │ │ │ │ │ │ ├── Box.html │ │ │ │ │ │ ├── BoxConverter.html │ │ │ │ │ │ ├── Circle.html │ │ │ │ │ │ ├── CircleConverter.html │ │ │ │ │ │ ├── Interval.html │ │ │ │ │ │ ├── IntervalConverter.html │ │ │ │ │ │ ├── Json.html │ │ │ │ │ │ ├── Line.html │ │ │ │ │ │ ├── LineConverter.html │ │ │ │ │ │ ├── LineSegment.html │ │ │ │ │ │ ├── LineSegmentConverter.html │ │ │ │ │ │ ├── Numeric.html │ │ │ │ │ │ ├── Path.html │ │ │ │ │ │ ├── PathConverter.html │ │ │ │ │ │ ├── Point.html │ │ │ │ │ │ ├── PointConverter.html │ │ │ │ │ │ ├── Polygon.html │ │ │ │ │ │ └── PolygonConverter.html │ │ │ │ │ ├── package-frame.html │ │ │ │ │ ├── package-summary.html │ │ │ │ │ ├── package-tree.html │ │ │ │ │ └── package-use.html │ │ │ │ ├── package-frame.html │ │ │ │ ├── package-summary.html │ │ │ │ ├── package-tree.html │ │ │ │ ├── package-use.html │ │ │ │ └── pubsub/ │ │ │ │ ├── PgChannel.html │ │ │ │ ├── PgSubscriber.html │ │ │ │ ├── class-use/ │ │ │ │ │ ├── PgChannel.html │ │ │ │ │ └── PgSubscriber.html │ │ │ │ ├── package-frame.html │ │ │ │ ├── package-summary.html │ │ │ │ ├── package-tree.html │ │ │ │ └── package-use.html │ │ │ ├── reactivex/ │ │ │ │ └── pgclient/ │ │ │ │ ├── Json.html │ │ │ │ ├── PgClient.html │ │ │ │ ├── PgConnection.html │ │ │ │ ├── PgCursor.html │ │ │ │ ├── PgIterator.html │ │ │ │ ├── PgPool.html │ │ │ │ ├── PgPreparedQuery.html │ │ │ │ ├── PgResult.html │ │ │ │ ├── PgRowSet.html │ │ │ │ ├── PgStream.html │ │ │ │ ├── PgTransaction.html │ │ │ │ ├── Row.html │ │ │ │ ├── Tuple.html │ │ │ │ ├── class-use/ │ │ │ │ │ ├── Json.html │ │ │ │ │ ├── PgClient.html │ │ │ │ │ ├── PgConnection.html │ │ │ │ │ ├── PgCursor.html │ │ │ │ │ ├── PgIterator.html │ │ │ │ │ ├── PgPool.html │ │ │ │ │ ├── PgPreparedQuery.html │ │ │ │ │ ├── PgResult.html │ │ │ │ │ ├── PgRowSet.html │ │ │ │ │ ├── PgStream.html │ │ │ │ │ ├── PgTransaction.html │ │ │ │ │ ├── Row.html │ │ │ │ │ └── Tuple.html │ │ │ │ ├── data/ │ │ │ │ │ ├── Json.html │ │ │ │ │ ├── class-use/ │ │ │ │ │ │ └── Json.html │ │ │ │ │ ├── package-frame.html │ │ │ │ │ ├── package-summary.html │ │ │ │ │ ├── package-tree.html │ │ │ │ │ └── package-use.html │ │ │ │ ├── package-frame.html │ │ │ │ ├── package-summary.html │ │ │ │ ├── package-tree.html │ │ │ │ ├── package-use.html │ │ │ │ └── pubsub/ │ │ │ │ ├── PgChannel.html │ │ │ │ ├── PgSubscriber.html │ │ │ │ ├── class-use/ │ │ │ │ │ ├── PgChannel.html │ │ │ │ │ └── PgSubscriber.html │ │ │ │ ├── package-frame.html │ │ │ │ ├── package-summary.html │ │ │ │ ├── package-tree.html │ │ │ │ └── package-use.html │ │ │ └── rxjava/ │ │ │ └── pgclient/ │ │ │ ├── Json.html │ │ │ ├── PgClient.html │ │ │ ├── PgConnection.html │ │ │ ├── PgCursor.html │ │ │ ├── PgIterator.html │ │ │ ├── PgPool.html │ │ │ ├── PgPreparedQuery.html │ │ │ ├── PgResult.html │ │ │ ├── PgRowSet.html │ │ │ ├── PgStream.html │ │ │ ├── PgTransaction.html │ │ │ ├── Row.html │ │ │ ├── Tuple.html │ │ │ ├── class-use/ │ │ │ │ ├── Json.html │ │ │ │ ├── PgClient.html │ │ │ │ ├── PgConnection.html │ │ │ │ ├── PgCursor.html │ │ │ │ ├── PgIterator.html │ │ │ │ ├── PgPool.html │ │ │ │ ├── PgPreparedQuery.html │ │ │ │ ├── PgResult.html │ │ │ │ ├── PgRowSet.html │ │ │ │ ├── PgStream.html │ │ │ │ ├── PgTransaction.html │ │ │ │ ├── Row.html │ │ │ │ └── Tuple.html │ │ │ ├── data/ │ │ │ │ ├── Json.html │ │ │ │ ├── class-use/ │ │ │ │ │ └── Json.html │ │ │ │ ├── package-frame.html │ │ │ │ ├── package-summary.html │ │ │ │ ├── package-tree.html │ │ │ │ └── package-use.html │ │ │ ├── package-frame.html │ │ │ ├── package-summary.html │ │ │ ├── package-tree.html │ │ │ ├── package-use.html │ │ │ └── pubsub/ │ │ │ ├── PgChannel.html │ │ │ ├── PgSubscriber.html │ │ │ ├── class-use/ │ │ │ │ ├── PgChannel.html │ │ │ │ └── PgSubscriber.html │ │ │ ├── package-frame.html │ │ │ ├── package-summary.html │ │ │ ├── package-tree.html │ │ │ └── package-use.html │ │ ├── overview-frame.html │ │ ├── overview-summary.html │ │ ├── overview-tree.html │ │ ├── package-list │ │ ├── script.js │ │ ├── serialized-form.html │ │ └── stylesheet.css │ ├── guide/ │ │ ├── groovy/ │ │ │ └── index.md │ │ ├── java/ │ │ │ └── index.md │ │ ├── js/ │ │ │ └── index.md │ │ ├── kotlin/ │ │ │ └── index.md │ │ └── ruby/ │ │ └── index.md │ ├── jsdoc/ │ │ ├── index.html │ │ ├── json.js.html │ │ ├── module-reactive-pg-client-js_json-Json.html │ │ ├── module-reactive-pg-client-js_json.html │ │ ├── module-reactive-pg-client-js_pg_channel-PgChannel.html │ │ ├── module-reactive-pg-client-js_pg_channel.html │ │ ├── module-reactive-pg-client-js_pg_client-PgClient.html │ │ ├── module-reactive-pg-client-js_pg_client.html │ │ ├── module-reactive-pg-client-js_pg_connection-PgConnection.html │ │ ├── module-reactive-pg-client-js_pg_connection.html │ │ ├── module-reactive-pg-client-js_pg_cursor-PgCursor.html │ │ ├── module-reactive-pg-client-js_pg_cursor.html │ │ ├── module-reactive-pg-client-js_pg_iterator-PgIterator.html │ │ ├── module-reactive-pg-client-js_pg_iterator.html │ │ ├── module-reactive-pg-client-js_pg_pool-PgPool.html │ │ ├── module-reactive-pg-client-js_pg_pool.html │ │ ├── module-reactive-pg-client-js_pg_prepared_query-PgPreparedQuery.html │ │ ├── module-reactive-pg-client-js_pg_prepared_query.html │ │ ├── module-reactive-pg-client-js_pg_result-PgResult.html │ │ ├── module-reactive-pg-client-js_pg_result.html │ │ ├── module-reactive-pg-client-js_pg_row_set-PgRowSet.html │ │ ├── module-reactive-pg-client-js_pg_row_set.html │ │ ├── module-reactive-pg-client-js_pg_stream-PgStream.html │ │ ├── module-reactive-pg-client-js_pg_stream.html │ │ ├── module-reactive-pg-client-js_pg_subscriber-PgSubscriber.html │ │ ├── module-reactive-pg-client-js_pg_subscriber.html │ │ ├── module-reactive-pg-client-js_pg_transaction-PgTransaction.html │ │ ├── module-reactive-pg-client-js_pg_transaction.html │ │ ├── module-reactive-pg-client-js_row-Row.html │ │ ├── module-reactive-pg-client-js_row.html │ │ ├── module-reactive-pg-client-js_tuple-Tuple.html │ │ ├── module-reactive-pg-client-js_tuple.html │ │ ├── pg_channel.js.html │ │ ├── pg_client.js.html │ │ ├── pg_connection.js.html │ │ ├── pg_cursor.js.html │ │ ├── pg_iterator.js.html │ │ ├── pg_pool.js.html │ │ ├── pg_prepared_query.js.html │ │ ├── pg_result.js.html │ │ ├── pg_row_set.js.html │ │ ├── pg_stream.js.html │ │ ├── pg_subscriber.js.html │ │ ├── pg_transaction.js.html │ │ ├── row.js.html │ │ ├── scripts/ │ │ │ ├── linenumber.js │ │ │ └── prettify/ │ │ │ ├── Apache-License-2.0.txt │ │ │ ├── lang-css.js │ │ │ └── prettify.js │ │ ├── styles/ │ │ │ ├── jsdoc-default.css │ │ │ ├── prettify-jsdoc.css │ │ │ └── prettify-tomorrow.css │ │ └── tuple.js.html │ └── yardoc/ │ ├── ReactivePgClient/ │ │ ├── Json.html │ │ ├── PgChannel.html │ │ ├── PgClient.html │ │ ├── PgConnection.html │ │ ├── PgCursor.html │ │ ├── PgIterator.html │ │ ├── PgPool.html │ │ ├── PgPreparedQuery.html │ │ ├── PgResult.html │ │ ├── PgRowSet.html │ │ ├── PgStream.html │ │ ├── PgSubscriber.html │ │ ├── PgTransaction.html │ │ ├── Row.html │ │ └── Tuple.html │ ├── ReactivePgClient.html │ ├── _index.html │ ├── class_list.html │ ├── css/ │ │ ├── common.css │ │ ├── full_list.css │ │ └── style.css │ ├── file.README.html │ ├── file_list.html │ ├── frames.html │ ├── index.html │ ├── js/ │ │ ├── app.js │ │ ├── full_list.js │ │ └── jquery.js │ ├── method_list.html │ └── top-level-namespace.html ├── jekyll/ │ ├── README.md │ ├── _config.yml │ └── docker-compose.yml ├── jitwatch.properties ├── jitwatch.sh ├── pom.xml └── src/ ├── assembly/ │ ├── benchmark.xml │ └── sources.xml ├── benchmark/ │ └── java/ │ └── io/ │ └── reactiverse/ │ └── pgclient/ │ ├── BenchmarkBase.java │ ├── LargeSelectBenchmark.java │ ├── Main.java │ ├── PgBenchmarkBase.java │ ├── PipelineBenchmark.java │ ├── RawBenchmark.java │ ├── SingleSelectBenchmark.java │ └── UpdateBenchmark.java ├── main/ │ ├── asciidoc/ │ │ └── dataobjects.adoc │ ├── docs/ │ │ └── index.md │ ├── java/ │ │ ├── examples/ │ │ │ ├── Examples.java │ │ │ └── RxExamples.java │ │ └── io/ │ │ └── reactiverse/ │ │ └── pgclient/ │ │ ├── PgClient.java │ │ ├── PgConnectOptions.java │ │ ├── PgConnection.java │ │ ├── PgCursor.java │ │ ├── PgException.java │ │ ├── PgIterator.java │ │ ├── PgNotification.java │ │ ├── PgPool.java │ │ ├── PgPoolOptions.java │ │ ├── PgPreparedQuery.java │ │ ├── PgResult.java │ │ ├── PgRowSet.java │ │ ├── PgStream.java │ │ ├── PgTransaction.java │ │ ├── Row.java │ │ ├── SslMode.java │ │ ├── Tuple.java │ │ ├── data/ │ │ │ ├── Box.java │ │ │ ├── Circle.java │ │ │ ├── Interval.java │ │ │ ├── Json.java │ │ │ ├── Line.java │ │ │ ├── LineSegment.java │ │ │ ├── Numeric.java │ │ │ ├── Path.java │ │ │ ├── Point.java │ │ │ └── Polygon.java │ │ ├── impl/ │ │ │ ├── ArrayTuple.java │ │ │ ├── CloseConnectionCommand.java │ │ │ ├── ClosePortalCommand.java │ │ │ ├── CloseStatementCommand.java │ │ │ ├── CommandBase.java │ │ │ ├── CommandResponse.java │ │ │ ├── CommandScheduler.java │ │ │ ├── Connection.java │ │ │ ├── ConnectionPool.java │ │ │ ├── ExtendedBatchQueryCommand.java │ │ │ ├── ExtendedQueryCommand.java │ │ │ ├── ExtendedQueryCommandBase.java │ │ │ ├── InitCommand.java │ │ │ ├── PgClientBase.java │ │ │ ├── PgConnectionBase.java │ │ │ ├── PgConnectionFactory.java │ │ │ ├── PgConnectionImpl.java │ │ │ ├── PgConnectionUriParser.java │ │ │ ├── PgCursorImpl.java │ │ │ ├── PgPoolImpl.java │ │ │ ├── PgPreparedQueryImpl.java │ │ │ ├── PgResultBase.java │ │ │ ├── PgResultBuilder.java │ │ │ ├── PgResultImpl.java │ │ │ ├── PgRowSetImpl.java │ │ │ ├── PgStreamImpl.java │ │ │ ├── PrepareStatementCommand.java │ │ │ ├── PreparedStatement.java │ │ │ ├── QueryCommandBase.java │ │ │ ├── QueryResultHandler.java │ │ │ ├── RowImpl.java │ │ │ ├── RowResultDecoder.java │ │ │ ├── SimpleQueryCommand.java │ │ │ ├── SocketConnection.java │ │ │ ├── StringLongSequence.java │ │ │ ├── Transaction.java │ │ │ ├── codec/ │ │ │ │ ├── ColumnDesc.java │ │ │ │ ├── DataFormat.java │ │ │ │ ├── DataType.java │ │ │ │ ├── DataTypeCodec.java │ │ │ │ ├── TxStatus.java │ │ │ │ ├── decoder/ │ │ │ │ │ ├── ErrorResponse.java │ │ │ │ │ ├── InboundMessage.java │ │ │ │ │ ├── InitiateSslHandler.java │ │ │ │ │ ├── MessageDecoder.java │ │ │ │ │ ├── NoticeResponse.java │ │ │ │ │ ├── NotificationResponse.java │ │ │ │ │ ├── ParameterDescription.java │ │ │ │ │ ├── Response.java │ │ │ │ │ ├── RowDecoder.java │ │ │ │ │ ├── RowDescription.java │ │ │ │ │ └── type/ │ │ │ │ │ ├── AuthenticationType.java │ │ │ │ │ ├── CommandCompleteType.java │ │ │ │ │ ├── ErrorOrNoticeType.java │ │ │ │ │ └── MessageType.java │ │ │ │ ├── encoder/ │ │ │ │ │ ├── Bind.java │ │ │ │ │ ├── Describe.java │ │ │ │ │ ├── MessageEncoder.java │ │ │ │ │ ├── Parse.java │ │ │ │ │ ├── PasswordMessage.java │ │ │ │ │ ├── Query.java │ │ │ │ │ └── StartupMessage.java │ │ │ │ ├── formatter/ │ │ │ │ │ ├── DateTimeFormatter.java │ │ │ │ │ └── TimeFormatter.java │ │ │ │ └── util/ │ │ │ │ ├── MD5Authentication.java │ │ │ │ ├── UTF8StringEndDetector.java │ │ │ │ └── Util.java │ │ │ ├── data/ │ │ │ │ └── JsonImpl.java │ │ │ └── pubsub/ │ │ │ └── PgSubscriberImpl.java │ │ ├── package-info.java │ │ └── pubsub/ │ │ ├── PgChannel.java │ │ └── PgSubscriber.java │ └── kotlin/ │ └── io/ │ └── reactiverse/ │ └── kotlin/ │ └── pgclient/ │ ├── PgClient.kt │ ├── PgConnectOptions.kt │ ├── PgConnection.kt │ ├── PgCursor.kt │ ├── PgNotification.kt │ ├── PgPool.kt │ ├── PgPoolOptions.kt │ ├── PgPreparedQuery.kt │ ├── PgStream.kt │ ├── PgTransaction.kt │ ├── data/ │ │ ├── Box.kt │ │ ├── Circle.kt │ │ ├── Interval.kt │ │ ├── Line.kt │ │ ├── LineSegment.kt │ │ ├── Path.kt │ │ ├── Point.kt │ │ └── Polygon.kt │ └── pubsub/ │ ├── PgChannel.kt │ └── PgSubscriber.kt └── test/ └── java/ └── io/ └── reactiverse/ └── pgclient/ ├── ErrorCodes.java ├── JdbcTest.java ├── JdbcTestBase.java ├── NumericTest.java ├── PgClientTestBase.java ├── PgConnectOptionsProviderTest.java ├── PgConnectionTest.java ├── PgConnectionTestBase.java ├── PgConnectionUriParserTest.java ├── PgPoolTest.java ├── PgPoolTestBase.java ├── PgPooledConnectionTest.java ├── PgTestBase.java ├── PgTransactionTest.java ├── PreparedBatchTest.java ├── PreparedStatementCachedTest.java ├── PreparedStatementTest.java ├── PreparedStatementTestBase.java ├── ProxyServer.java ├── PubSubTest.java ├── RowTest.java ├── RxTest.java ├── StringLongSequenceTest.java ├── TLSTest.java ├── TupleTest.java ├── UnixDomainSocketTest.java ├── UtilTest.java ├── data/ │ ├── BinaryDataTypesExtendedCodecTest.java │ ├── BinaryDataTypesSimpleCodecTest.java │ ├── BooleanTypeExtendedCodecTest.java │ ├── BooleanTypeSimpleCodecTest.java │ ├── CharacterTypesExtendedCodecTest.java │ ├── CharacterTypesSimpleCodecTest.java │ ├── ColumnChecker.java │ ├── CustomTypesExtendedCodecTest.java │ ├── CustomTypesSimpleCodecTest.java │ ├── DataTypeTestBase.java │ ├── DateTimeTypesExtendedCodecTest.java │ ├── DateTimeTypesSimpleCodecTest.java │ ├── EnumeratedTypesExtendedCodecTest.java │ ├── EnumeratedTypesSimpleCodecTest.java │ ├── ExtendedQueryDataTypeCodecTestBase.java │ ├── GeometricTypesExtendedCodecTest.java │ ├── GeometricTypesSimpleCodecTest.java │ ├── JsonTypesExtendedCodecTest.java │ ├── JsonTypesSimpleCodecTest.java │ ├── NullSimpleCodecTest.java │ ├── NumericTypesExtendedCodecTest.java │ ├── NumericTypesSimpleCodecTest.java │ ├── PreparedStatementParamCoercionTest.java │ ├── SimpleQueryDataTypeCodecTestBase.java │ ├── UUIDTypeExtendedCodecTest.java │ └── UUIDTypeSimpleCodecTest.java ├── impl/ │ └── codec/ │ └── util/ │ └── MD5AuthenticationTest.java ├── it/ │ └── EnvTest.java └── pool/ ├── ConnectionPoolTest.java ├── ConnectionQueue.java ├── SimpleConnection.java └── SimpleHolder.java ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ root = true [*] charset = utf-8 indent_style = space indent_size = 2 trim_trailing_whitespace = true end_of_line = lf insert_final_newline = true ================================================ FILE: .gitignore ================================================ jitwatch.out jekyll/apidocs jekyll/yardoc jekyll/guide jekyll/.* jekyll/_site jekyll/jsdoc *.log .vertx .DS_Store .gradle .idea .classpath .project .settings .yardoc .yardopts build target out *.iml *.ipr *.iws *.jfr test-output Scratch.java ScratchTest.java test-results test-tmp *.class ScratchPad.java src/main/resources/ext-js/*.js src/main/java/io/vertx/java/**/*.java *.swp ================================================ FILE: .travis.deploy.artifacts.sh ================================================ PROJECT_VERSION=$(mvn org.apache.maven.plugins:maven-help-plugin:evaluate -Dexpression=project.version -B | grep -v '\[') if [[ "$PROJECT_VERSION" =~ .*SNAPSHOT ]] && [[ "${TRAVIS_BRANCH}" =~ ^master$|^[0-9]+\.[0-9]+$ ]] && [[ "${TRAVIS_PULL_REQUEST}" = "false" ]]; then mvn deploy -s .travis.maven.settings.xml -DskipTests -B; fi ================================================ FILE: .travis.maven.settings.xml ================================================ false sonatype-nexus-snapshots ${env.SONATYPE_NEXUS_USERNAME} ${env.SONATYPE_NEXUS_PASSWORD} ================================================ FILE: .travis.yml ================================================ language: java branches: only: - master - /^\d+\.\d+$/ jobs: include: - stage: test name: "Postgres 9" jdk: oraclejdk8 script: mvn -q clean verify -B -Dembedded.postgres.version=9.6 - stage: test name: "Postgres 10" jdk: oraclejdk8 script: mvn -q clean verify -B -Dembedded.postgres.version=10.6 - stage: deploy name: "Deploy to Sonatype's snapshots repository" if: type != pull_request AND env(SONATYPE_NEXUS_USERNAME) IS present script: bash .travis.deploy.artifacts.sh notifications: email: recipients: - secure: "Auz9no9ZKVvY7rtA+CI6fNxXoTHR8xQZRWPWkx3GgBTFOiPlt6NWVmdUnGVdYaBQAV8M5kQ8ldv6Zo1gKWBRIZ9mdrElHPaImP15RqlUhqGdu6EByAHUCx0An3qla2Chsrs9QQAARQHjheWv6mRmRQFeNWVU/X0qSciiK0r40EzRAKuY3zwuNiNIDza12QrCrlQnGvdBf6qnfNrV03Rkxk+AzZHeNP0vjGB57zQCwClZQNIDWwyCdHJDHiMwKC16qQxRJ09RY4EJi0qDTzTFgQ3tL28G7zR8M563ELTVU7ojrAq8AvlZcpiLivjP/RR99owyzm+r9ZHMiPHqJ3cbbisBqtRQSWP8yCKJ9h2GKGlzX9JDZJ+/3smvoPLgUg7yiwjDeX+yFDFL7F5pfzHh0DXxRqRCAGPs4dOho023C6kqiWk94SzzUX8FCKuIm+N5Y9M2KAWvA0s6/KtpIhdi+rpdIImaDwf7LoAFzwvaZnFMS5wB6/wVz/AEiSKOiu05uzaDymRWnupugN6XZd4KY95vB9JCvaLOmjJHvSF8fFGqMVSLopU2ZAZTjWSceOn4/lU/qDThnTuhY9qHCqEcbYWSJ1Jl6cD5ddX++qk+lmhTbvcbIAZ8L+ZKxvanfFl5TtTdYc9vpOFrfMTeOWBo9Oq5/TgZTeDaXCSH1gaM4sQ=" - secure: "KdmtQ62Cge7jmyj40XVJ/rW6sXuWdwtHIMsaGEg4pc17tMIl2bGI/pnpVt5UVbjq7xYHFwA9DaIh5oyq9hizdDEAx46pGmuDIsATn9TTaWJK35dht6Ri/So2B2mAhDJrz3s7HDFb4IYI72Cgp2ukw/q6R6pHDt/xHyT4h+/YmTzXPUhyrduO0nQHvTCyUqUsyOTL4uC/HyBnAID9UtCgEJBCWAnATQc3sMRw9VqgQmLQeEPmIaor9UNxrS4sNpnHCPrsjNfGN4sSfAbRcNENsh7iyM6b+aPKm6hh/KPlYQ59FHqXXAxeYrdXAoObN8heg5TFH6v20g3n2mLeVvJFgCF8Dq6dJCPAqgMsENcB2OdunRop1bUEzLRQicKscZ7vd+9FOXX8cYP7zKLiEWJs/bU1sTQ3vbHqtReC8yWlQTKYeNMlw9cFJvSZLZ+GqetNgcoH4DiCrOiDpqWCgHGZ+98E1U5CEwpBcqRo9hfwtS8vSQjy08t/LvEIZqGTuD+nmsgN7tPhh9qrfLGk76pzF4QzYVManXd1WDIInWuOKbDjUdRuGHDc1TSwqBVjGoe9w0VI25fT1H/osTWgXon/I/vSTnFrJOYmZvthL+OUR3ptuYXUcGZQZtiVSQs71dAoTChBlf9dNJhLqLk7VK304XQL7peYn4PuofEYW+SFAB8=" on_success: always on_failure: always ================================================ FILE: BENCHMARK.md ================================================ ## Client Benchmarking ### Running the query benchmark Runs query operations with 8 threads ``` > mvn clean package -Pbenchmark > java -jar target/vertx-pg-client-0.3.1-SNAPSHOT-benchmark.jar ``` You can profile the benchmark ``` > java -jar target/vertx-pg-client-0.3.1-SNAPSHOT-benchmark.jar SingleSelectBenchmark.poolPreparedQuery -jvmArgsAppend "-XX:+UnlockCommercialFeatures -XX:+FlightRecorder -XX:StartFlightRecording=duration=60s,filename=./profiling-data.jfr,name=profile,settings=profile" ``` just make sure to run one benchmark at a time. ## Client performance ### Outbound message size estimation Some messages are really small, and it would be good allocate the right size instead of 256 by default. ### Row decoding Investigate plugability of row decoder that can operate on `@DataObject` directly. ================================================ FILE: Dockerfile ================================================ # We're using the official Maven 3 image from the Docker Hub (https://hub.docker.com/_/maven/). # Take a look at the available versions so you can specify the Java version you want to use. FROM maven:3 # INSTALL any further tools you need here so they are cached in the docker build WORKDIR /app # Copy the whole repository into the image COPY . ./ # Run install task so all necessary dependencies are downloaded and cached in # the Docker image. We're running through the whole process but disable # testing and make sure the command doesn't fail. RUN mvn install clean --fail-never -B -DfailIfNoTests=false ================================================ FILE: LICENSE.txt ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed 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. ================================================ FILE: README.adoc ================================================ = Reactive Postgres Client image:https://travis-ci.org/vietj/reactive-pg-client.svg?branch=master["Build Status",link="https://travis-ci.org/vietj/reactive-pg-client"] IMPORTANT: The Reactive PostgreSQL Client has a new https://github.com/eclipse-vertx/vertx-sql-client/tree/3.8/vertx-pg-client[home], this project remains active for security fixes * Simple API focusing on scalability and low overhead. * Reactive and non blocking which able to handle many database connections with a single thread. * Ranked *#1* in the https://www.techempower.com/benchmarks/#section=data-r15&hw=ph&test=db[TechEmpower Benchmark Round 15] _Single query_ benchmark. This project has evolved to become the https://github.com/eclipse-vertx/vertx-sql-client[Reactive SQL Client] that provides support for PostgreSQL and MySQL. This project will remain maintained for bug fixes. == Features - Event driven - Lightweight - Built-in connection pooling - Prepared queries caching - Publish / subscribe using Postgres `LISTEN/NOTIFY` - Batch and cursor support - Row streaming - `java.util.stream.Collector` row set transformation - Command pipeling - RxJava 1 and RxJava 2 - Direct memory to object without unnecessary copies - Java 8 Date and Time - SSL/TLS - Unix domain socket - HTTP/1.x CONNECT, SOCKS4a or SOCKS5 proxy - Request cancellation == Usage Latest release is https://github.com/reactiverse/reactive-pg-client/blob/master/RELEASES.adoc[0.11.4]. To use the client, add the following dependency to the _dependencies_ section of your build descriptor: * Maven (in your `pom.xml`) for Vert.x 3.7.x: [source,xml] ---- io.reactiverse reactive-pg-client 0.11.4 ---- * Gradle (in your `build.gradle` file) for Vert.x 3.7.x: [source,groovy] ---- dependencies { compile 'io.reactiverse:reactive-pg-client:0.11.4' } ---- If you are using Vertx 3.5.x you should use instead `0.10.9` Then the code is quite straightforward: [source,java] ---- // Pool options PgPoolOptions options = new PgPoolOptions() .setPort(5432) .setHost("the-host") .setDatabase("the-db") .setUser("user") .setPassword("secret") .setMaxSize(5); // Create the client pool PgPool client = PgClient.pool(options); // A simple query client.query("SELECT * FROM users WHERE id='julien'", ar -> { if (ar.succeeded()) { PgResult result = ar.result(); System.out.println("Got " + result.size() + " results "); } else { System.out.println("Failure: " + ar.cause().getMessage()); } // Now close the pool client.close(); }); ---- == Integration / Usages * https://github.com/jklingsporn/vertx-jooq[vertx-jooq]: writing type safe queries and let them run at high speed using jOOQ, vertx and the reactive-pg-client. * https://docs.micronaut.io/latest/guide/index.html#postgresSupport[Micronaut]: supports reactive and non-blocking client to connect to Postgres using reactive-pg-client, allowing to handle many database connections with a single thread. == Documentations * https://reactiverse.io/reactive-pg-client/guide/java/index.html[Java docs] * https://reactiverse.io/reactive-pg-client/guide/kotlin/[Kotlin docs] * https://reactiverse.io/reactive-pg-client/guide/groovy/index.html[Groovy docs] * https://reactiverse.io/reactive-pg-client/guide/ruby/index.html[Ruby docs] * https://reactiverse.io/reactive-pg-client/guide/js/index.html[JavaScript docs] == Javadoc * https://reactiverse.io/reactive-pg-client/apidocs/index.html[Javadoc] == Pipelining This client supports pipelining requests to the database which can give a significant performance improvement depending on the latency to the database and the type of queries your application is doing. .100µs latency image::100µs-latency.png[] .1ms latency image::1ms-latency.png[] Such results have been produced using this https://github.com/vietj/pg-client-concurrency-benchmark[benchmark]. WARNING: The two results are not normalized, the 100µs latency executes the 5000 queries in about 300ms, the 1ms latency executes the 5000 queries in about 13 seconds. == Supported Data Types The *Reactive Postgres Client* currently supports the following data types [cols="^,^,^,^,^", options="header"] |==== | _ 2+| Value 2+| Array | Postgres | Java | Supported | JAVA | Supported |`BOOLEAN` |`j.l.Boolean` |✔ |`j.l.Boolean[]` |✔ |`INT2` |`j.l.Short` |✔ |`j.l.Short[]` |✔ |`INT4` |`j.l.Integer` |✔ |`j.l.Integer[]` |✔ |`INT8` |`j.l.Long` |✔ |`j.l.Long[]` |✔ |`FLOAT4` |`j.l.Float` |✔ |`j.l.Float[]` |✔ |`FLOAT8` |`j.l.Double` |✔ |`j.l.Double[]` |✔ |`CHAR` |`j.l.Character` |✔ |`j.l.Character[]` |✔ |`VARCHAR` |`j.l.String` |✔ |`j.l.String[]` |✔ |`TEXT` |`j.l.String` |✔ |`j.l.String[]` |✔ |`ENUM` |`j.l.String` |✔ |`j.l.String[]` |✔ |`NAME` |`j.l.String` |✔ |`j.l.String[]` |✔ |`SERIAL2` |`j.l.Short` |✔ |`invalid type` |✕ |`SERIAL4` |`j.l.Integer` |✔ |`invalid type` |✕ |`SERIAL8` |`j.l.Long` |✔ |`invalid type` |✕ |`NUMERIC` |`i.r.p.data.Numeric` |✔ |`i.r.p.data.Numeric[]` |✔ |`UUID` |`j.u.UUID` |✔ |`j.u.UUID[]` |✔ |`DATE` |`j.t.LocalDate` |✔ |`j.t.LocalDate[]` |✔ |`TIME` |`j.t.LocalTime` |✔ |`j.t.LocalTime[]` |✔ |`TIMETZ` |`j.t.OffsetTime` |✔ |`j.t.OffsetTime[]` |✔ |`TIMESTAMP` |`j.t.LocalDateTime` |✔ |`j.t.LocalDateTime[]` |✔ |`TIMESTAMPTZ` |`j.t.OffsetDateTime` |✔ |`j.t.OffsetDateTime[]` |✔ |`INTERVAL` |`i.r.p.data.Interval` |✔ |`i.r.p.data.Interval[]` |✔ |`BYTEA` |`i.v.c.b.Buffer` |✔ |`i.v.c.b.Buffer[]` |✔ |`JSON` |`i.r.p.data.Json` |✔ |`i.r.p.data.Json[]` |✔ |`JSONB` |`i.r.p.data.Json` |✔ |`i.r.p.data.Json[]` |✔ |`POINT` |`i.r.p.data.Point` |✔ |`i.r.p.data.Point[]` |✔ |`LINE` |`i.r.p.data.Line` |✔ |`i.r.p.data.Line[]` |✔ |`LSEG` |`i.r.p.data.LineSegment` |✔ |`i.r.p.data.LineSegment[]` |✔ |`BOX` |`i.r.p.data.Box` |✔ |`i.r.p.data.Box[]` |✔ |`PATH` |`i.r.p.data.Path` |✔ |`i.r.p.data.Path[]` |✔ |`POLYGON` |`i.r.p.data.Polygon` |✔ |`i.r.p.data.Polygon[]` |✔ |`CIRCLE` |`i.r.p.data.Circle` |✔ |`i.r.p.data.Circle[]` |✔ |`UNKNOWN` |`j.l.String` |✔ |`j.l.String[]` |✔ |==== The following types _MONEY_, _BIT_, _VARBIT_, _MACADDR_, _INET_, _CIDR_, _MACADDR8_, _XML_, _HSTORE_, _OID_, _VOID_, _TSQUERY_, _TSVECTOR_ are not implemented yet (PR are welcome). == Snapshots Snapshots are deploy in Sonatype OSS repository: https://oss.sonatype.org/content/repositories/snapshots/io/reactiverse/reactive-pg-client/ == License Apache License - Version 2.0 == Developers === Testing Out of the box, the test suite runs an embedded Postgres by default. You can change the version of the embedded Postgres by passing a property `embedded.postgres.version` like this: ``` > mvn test -Dembedded.postgres.version=9.6 ``` The following versions of embedded Postgres are supported: - `9.6` - `10.6` (default) - `11.1` (not supported on Linux) === Testing with an external database You can run tests with an external database: - the script `docker/postgres/resources/create-postgres.sql` creates the test data - the `TLSTest` expects the database to be configured with SSL with `docker/postgres/resources/server.key` / `docker/postgres/resources/server.cert`` You need to add some properties for testing: ``` > mvn test -Dconnection.uri=postgres://$username:$password@$host:$port/$database -Dtls.connection.uri=postgres://$username:$password@$host:$port/$database -Dunix.socket.directory=$path ``` - connection.uri(mandatory): configure the client to connect the specified database - tls.connection.uri(mandatory): configure the client to run `TLSTest` with the specified Postgres with SSL enabled - unix.socket.directory(optional): the single unix socket directory(multiple socket directories are not supported) to test Unix domain socket with a specified database, domain socket tests will be skipped if this property is not specified (Note: Make sure you can access the unix domain socket with this directory under your host machine) - unix.socket.port(optional): unix socket file is named `.s.PGSQL.nnnn` and `nnnn` is the server's port number, this property is mostly used when you test with Docker, when you publish your Postgres container port other than 5432 in your host but Postgres may actually listen on a different port in the container, you will then need this property to help you connect the Postgres with Unix domain socket === Testing with Docker Run the Postgres containers with `docker-compose`: ``` > cd docker/postgres > docker-compose up --build -V ``` Run tests: ``` > mvn test -Dconnection.uri=postgres://$username:$password@$host:$port/$database -Dtls.connection.uri=postgres://$username:$password@$host:$port/$database -Dunix.socket.directory=$path -Dunix.socket.port=$port ``` === Documentation The online and published documentation is in `/docs` and is served by GitHub pages with Jekyll. You can find the actual guide source in [src/main/docs/index.md](src/main/docs/index.md). At compilation time, this source generates the `jekyll/guide/java/index.md`. The current documentation is in `/jekyll` and can be preview using Docker and your browser * generate the documentation ** `mvn compile` to generate `jekyll/guide/java/index.md` ** `mvn site` to generate the javadoc in `jekyll/apidocs` * run Jekyll ** `cd jekyll` ** `docker-compose up` * open your browser at http://localhost:4000 ================================================ FILE: RELEASES.adoc ================================================ == 0.11.4 Fixed issues: https://github.com/vietj/reactive-pg-client/milestone/1?closed=1 - Vert.x 3.7.1 upgrade - Add support for Postgres BYTEA escape format == 0.11.3 Fixed issues: https://github.com/reactiverse/reactive-pg-client/issues?q=is%3Aclosed+milestone%3A0.11.4 - Vert.x 3.7.0 upgrade == 0.11.2 Fixed issues: https://github.com/reactiverse/reactive-pg-client/issues?q=is%3Aclosed+milestone%3A0.11.2 - Request cancellation support - Remove @GenIgnore or use permitted-type in Tuple/Row methods - Add documentation and an example for fetching generated keys - Add support for sslmode == 0.11.1 Fixed issues: https://github.com/reactiverse/reactive-pg-client/issues?q=is%3Aclosed+milestone%3A0.11.1 - Upgrade to Vert.x 3.6.2 - Generate kotlin coroutine methods - Get details from PgException - SSL upgradefuture failure is not properly handled == 0.11.0 Fixed issues: https://github.com/reactiverse/reactive-pg-client/issues?q=is%3Aclosed+milestone%3A0.11.0 - Upgrade to Vert.x 3.6.0 - Example for Kotlin throws compilation errors == 0.10.9 Fixed issues: https://github.com/reactiverse/reactive-pg-client/issues?q=is%3Aclosed+milestone%3A0.10.9 - Geometric types supports - Accept null value for json parameter == 0.10.8 Fixed issues: https://github.com/reactiverse/reactive-pg-client/issues?q=is%3Aclosed+milestone%3A0.10.8 - Connection pool opens more connections than necessary - Negative numeric values are not simple queries are not properly decoded == 0.10.7 Fixed issues: https://github.com/reactiverse/reactive-pg-client/milestone/14?closed=1 - Batch execution incorrectly handles batch result when the batch list is empty - Pool connection acquisition failure is not propagated to the scheduled command - Upgrade to Vertx 3.5.4 - Source code for rxjava and reactivex API variants missing from -sources.jar - Allow to prepare query from a transaction object - Rework cursor/stream documentation == 0.10.6 Fixed issues: https://github.com/reactiverse/reactive-pg-client/milestone/13?closed=1 - PgPool#preparedQuery operation should always use the same connection - Numeric type prepared statement parameters needs to be coerced == 0.10.5 Fixed issues: https://github.com/reactiverse/reactive-pg-client/milestone/12?closed=1 - Connection pool queue boundary - Pool does not handle connection failure correctly - Rx Stream API documentation unclear == 0.10.4 Fixed issues: https://github.com/reactiverse/reactive-pg-client/milestone/11?closed=1 - RowResultDecoder does not correctly decode empty text arrays - Move to Vertx logger for warnings instead of Sysout === Bug fixes - Treat unknown datatypes as text instead of binary - Null values should always be valid in prepared statement parameters == 0.10.3 Fixed issues: https://github.com/reactiverse/reactive-pg-client/milestone/10?closed=1 === Bug fixes - Treat unknown datatypes as text instead of binary - Null values should always be valid in prepared statement parameters == 0.10.2 Fixed issues: https://github.com/reactiverse/reactive-pg-client/milestone/9?closed=1 === Bug fixes - When a pooled connection is closed, the actual connection should not be made available after it has been closed internally - Missing prepared statement tuple validation - JSONB array treated as non array - PreparedQuery should schedule commands from the event loop thread - Calling Transaction rollback() leads to an NPE == 0.10.1 Fixed issues: https://github.com/reactiverse/reactive-pg-client/milestone/8?closed=1 === Bug fixes - Connection client encoding parsing should be case insensitive for supporting Greenplum - Use quoted identifiers in LISTEN / UNLISTEN == 0.10.0 Fixed issues: https://github.com/reactiverse/reactive-pg-client/milestone/7?closed=1[Issues] === Features - simplified transaction API - interval data type support - enum data type support - cached prepared statement option - RxJava documentation enhancements - upgrade to Vert.x 3.5.3 - `Row` provides access to column names === Breaking changes - data types in `io.reactiverse.pgclient` have been moved to `io.reactiverse.pgclient.data` - `PgResult#updatedCount()` has been renamed to `PgResult#rowCount()` ================================================ FILE: docker/postgres/README.md ================================================ ## Postgres containers for testing There will be 2 Postgres containers for testing, one with SSL enabled is for `TLSTest` and the other one with SSL disabled is for all other tests. ### Configure the containers modify the content in the `docker-compose.yml` ### Run the containers ``` > docker-compose up --build -V ``` ### Run tests ``` > mvn test -Dconnection.uri=postgres://postgres:postgres@localhost:5432/postgres -Dtls.connection.uri=postgres://postgres:postgres@localhost:5433/postgres -Dunix.socket.directory=/var/run/postgresql -Dunix.socket.port=5432 ``` ================================================ FILE: docker/postgres/docker-compose.yml ================================================ version: "3" services: test-postgres: image: healthcheck/postgres:alpine ports: - "5432:5432" environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: postgres volumes: - /var/run/postgresql:/var/run/postgresql - ./resources/create-postgres.sql:/docker-entrypoint-initdb.d/create-postgres.sql tls-test-postgres: image: healthcheck/postgres:alpine ports: - "5433:5432" environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: postgres volumes: - ./resources/create-postgres.sql:/docker-entrypoint-initdb.d/create-postgres.sql - ./resources/server.crt:/server.crt - ./resources/server.key:/server.key - ./ssl.sh:/docker-entrypoint-initdb.d/ssl.sh ================================================ FILE: docker/postgres/resources/create-postgres.sql ================================================ DROP TYPE IF EXISTS weather CASCADE; DROP TYPE IF EXISTS mood CASCADE; DROP TYPE IF EXISTS full_address CASCADE; CREATE TYPE weather AS ENUM ('sunny', 'cloudy', 'rainy'); CREATE TYPE mood AS ENUM ('unhappy', 'ok', 'happy'); CREATE TYPE full_address AS (city TEXT, street TEXT, home BOOLEAN); -- World table DROP TABLE IF EXISTS World; CREATE TABLE World ( id integer NOT NULL, randomNumber integer NOT NULL default 0, PRIMARY KEY (id) ); INSERT INTO World (id, randomnumber) SELECT x.id, random() * 10000 + 1 FROM generate_series(1,10000) as x(id); -- Fortune table DROP TABLE IF EXISTS Fortune; CREATE TABLE Fortune ( id integer NOT NULL, message varchar(2048) NOT NULL, PRIMARY KEY (id) ); INSERT INTO Fortune (id, message) VALUES (1, 'fortune: No such file or directory'); INSERT INTO Fortune (id, message) VALUES (2, 'A computer scientist is someone who fixes things that aren''t broken.'); INSERT INTO Fortune (id, message) VALUES (3, 'After enough decimal places, nobody gives a damn.'); INSERT INTO Fortune (id, message) VALUES (4, 'A bad random number generator: 1, 1, 1, 1, 1, 4.33e+67, 1, 1, 1'); INSERT INTO Fortune (id, message) VALUES (5, 'A computer program does what you tell it to do, not what you want it to do.'); INSERT INTO Fortune (id, message) VALUES (6, 'Emacs is a nice operating system, but I prefer UNIX. — Tom Christaensen'); INSERT INTO Fortune (id, message) VALUES (7, 'Any program that runs right is obsolete.'); INSERT INTO Fortune (id, message) VALUES (8, 'A list is only as strong as its weakest link. — Donald Knuth'); INSERT INTO Fortune (id, message) VALUES (9, 'Feature: A bug with seniority.'); INSERT INTO Fortune (id, message) VALUES (10, 'Computers make very fast, very accurate mistakes.'); INSERT INTO Fortune (id, message) VALUES (11, ''); INSERT INTO Fortune (id, message) VALUES (12, 'フレームワークのベンチマーク'); -- All purpose testing table DROP TABLE IF EXISTS Test; CREATE TABLE Test ( id integer NOT NULL, val varchar(2048) NOT NULL, PRIMARY KEY (id) ); DROP TABLE IF EXISTS "NumericDataType"; CREATE TABLE "NumericDataType" ( "id" INTEGER NOT NULL PRIMARY KEY, "Short" INT2, "Integer" INT4, "Long" INT8, "Float" FLOAT4, "Double" FLOAT8, "BigDecimal" NUMERIC, "Boolean" BOOLEAN, "SmallSerial" SERIAL2, "Serial" SERIAL4, "BigSerial" SERIAL8 ); INSERT INTO "NumericDataType" ("id", "Short", "Integer", "Long", "Float", "Double", "BigDecimal", "Boolean") VALUES (1, 32767, 2147483647, 9223372036854775807, 3.4028235E38, 1.7976931348623157E308, '9.99999999999999999999999999999999999', true); INSERT INTO "NumericDataType" ("id", "Short", "Integer", "Long", "Float", "Double", "BigDecimal", "Boolean") VALUES (2, 32767, 2147483647, 9223372036854775807, 3.4028235E38, 1.7976931348623157E308, '9.99999999999999999999999999999999999', true); DROP TABLE IF EXISTS "TemporalDataType"; CREATE TABLE "TemporalDataType" ("id" INTEGER NOT NULL PRIMARY KEY, "Date" date, "Time" time without time zone, "TimeTz" time with time zone, "Timestamp" timestamp without time zone, "TimestampTz" timestamp with time zone, "Interval" interval); INSERT INTO "TemporalDataType" ("id" ,"Date", "Time", "TimeTz", "Timestamp", "TimestampTz", "Interval") VALUES (1 ,'1981-05-30', '17:55:04.90512', '17:55:04.90512+03:07', '2017-05-14 19:35:58.237666', '2017-05-14 23:59:59.237666-03', '10 years 3 months 332 days 20 hours 20 minutes 20.999999 seconds'); INSERT INTO "TemporalDataType" ("id" ,"Date", "Time", "TimeTz", "Timestamp", "TimestampTz", "Interval") VALUES (2 ,'2017-05-30', '12:55:04.90512', '02:55:04.90512+03:07', '1909-05-14 19:35:58.237666', '1909-05-14 22:35:58.237666-03', '02:01:33'); INSERT INTO "TemporalDataType" ("id" ,"Date", "Time", "TimeTz", "Timestamp", "TimestampTz", "Interval") VALUES (3 ,'1900-01-01', '23:59:04.90512', '08:08:03.90512+03:07', '1800-01-01 23:57:53.237666', '1800-01-01 23:59:59.237666-03', '04:33:59'); INSERT INTO "TemporalDataType" ("id" ,"Date", "Time", "TimeTz", "Timestamp", "TimestampTz", "Interval") VALUES (4 ,'1900-01-01', '23:59:04.90512', '08:08:03.90512+03:07', '1800-01-01 23:57:53.237666', '1800-01-01 23:59:59.237666-03', '04:33:59'); DROP TABLE IF EXISTS "CharacterDataType"; CREATE TABLE "CharacterDataType" ( "id" INTEGER NOT NULL PRIMARY KEY, "Name" NAME, "SingleChar" CHAR, "FixedChar" CHAR(3), "Text" TEXT, "VarCharacter" VARCHAR, "uuid" UUID ); INSERT INTO "CharacterDataType" ("id" ,"Name", "SingleChar", "FixedChar", "Text", "VarCharacter", "uuid") VALUES (1, 'What is my name ?', 'A', 'YES', 'Hello World', 'Great!', '6f790482-b5bd-438b-a8b7-4a0bed747011'); INSERT INTO "CharacterDataType" ("id" ,"Name", "SingleChar", "FixedChar", "Text", "VarCharacter", "uuid") VALUES (2, 'What is my name ?', 'A', 'YES', 'Hello World', 'Great!', '6f790482-b5bd-438b-a8b7-4a0bed747011'); DROP TABLE IF EXISTS "JsonDataType"; CREATE TABLE "JsonDataType" ( "id" INTEGER NOT NULL PRIMARY KEY, "JsonObject" JSON, "JsonArray" JSON, "Number" JSON, "String" JSON, "BooleanTrue" JSON, "BooleanFalse" JSON, "Null" JSON ); INSERT INTO "JsonDataType" ("id" ,"JsonObject", "JsonArray", "Number", "String", "BooleanTrue", "BooleanFalse", "Null") VALUES (1, ' {"str":"blah", "int" : 1, "float" : 3.5, "object": {}, "array" : [] }', '[1,true,null,9.5,"Hi"]', '4', '"Hello World"', 'true', 'false', 'null'); INSERT INTO "JsonDataType" ("id" ,"JsonObject", "JsonArray", "Number", "String", "BooleanTrue", "BooleanFalse", "Null") VALUES (2, ' {"str":"blah", "int" : 1, "float" : 3.5, "object": {}, "array" : [] }', '[1,true,null,9.5,"Hi"]', '4', '"Hello World"', 'true', 'false', 'null'); DROP TABLE IF EXISTS "JsonbDataType"; CREATE TABLE "JsonbDataType" ( "id" INTEGER NOT NULL PRIMARY KEY, "JsonObject" JSONB, "JsonArray" JSONB, "Number" JSONB, "String" JSONB, "BooleanTrue" JSONB, "BooleanFalse" JSONB, "Null" JSONB ); INSERT INTO "JsonbDataType" ("id" ,"JsonObject", "JsonArray", "Number", "String", "BooleanTrue", "BooleanFalse", "Null") VALUES (1, ' {"str":"blah", "int" : 1, "float" : 3.5, "object": {}, "array" : [] }', '[1,true,null,9.5,"Hi"]', '4', '"Hello World"', 'true', 'false', 'null'); INSERT INTO "JsonbDataType" ("id" ,"JsonObject", "JsonArray", "Number", "String", "BooleanTrue", "BooleanFalse", "Null") VALUES (2, ' {"str":"blah", "int" : 1, "float" : 3.5, "object": {}, "array" : [] }', '[1,true,null,9.5,"Hi"]', '4', '"Hello World"', 'true', 'false', 'null'); -- Geometric table DROP TABLE IF EXISTS "GeometricDataType"; CREATE TABLE "GeometricDataType" ( "id" INTEGER NOT NULL PRIMARY KEY, "Point" POINT, "Line" LINE, "Lseg" LSEG, "Box" BOX, "ClosedPath" PATH, "OpenPath" PATH, "Polygon" POLYGON, "Circle" CIRCLE ); INSERT INTO "GeometricDataType" ("id", "Point", "Line", "Lseg", "Box", "ClosedPath", "OpenPath", "Polygon", "Circle") VALUES (1, '(1.0,2.0)':: POINT, '{1.0,2.0,3.0}':: LINE, '((1.0,1.0),(2.0,2.0))':: LSEG, '((2.0,2.0),(1.0,1.0))':: BOX, '((1.0,1.0),(2.0,1.0),(2.0,2.0),(2.0,1.0))':: PATH,'[(1.0,1.0),(2.0,1.0),(2.0,2.0),(2.0,1.0)]':: PATH, '((1.0,1.0),(2.0,2.0),(3.0,1.0))':: POLYGON, '<(1.0,1.0),1.0>':: CIRCLE); INSERT INTO "GeometricDataType" ("id", "Point", "Line", "Lseg", "Box", "ClosedPath", "OpenPath", "Polygon", "Circle") VALUES (2, '(1.0,2.0)':: POINT, '{1.0,2.0,3.0}':: LINE, '((1.0,1.0),(2.0,2.0))':: LSEG, '((2.0,2.0),(1.0,1.0))':: BOX, '((1.0,1.0),(2.0,1.0),(2.0,2.0),(2.0,1.0))':: PATH,'[(1.0,1.0),(2.0,1.0),(2.0,2.0),(2.0,1.0)]':: PATH, '((1.0,1.0),(2.0,2.0),(3.0,1.0))':: POLYGON, '<(1.0,1.0),1.0>':: CIRCLE); DROP TABLE IF EXISTS "ArrayDataType"; CREATE TABLE "ArrayDataType" ( "id" INTEGER NOT NULL PRIMARY KEY, "Boolean" BOOLEAN [], "Short" INT2 [], "Integer" INT4 [], "Long" INT8 [], "Float" FLOAT4 [], "Double" FLOAT8 [], "Char" CHAR(8) [], "Varchar" VARCHAR [], "Text" TEXT [], "Name" NAME [], "LocalDate" DATE [], "LocalTime" TIME WITHOUT TIME ZONE [], "OffsetTime" TIME WITH TIME ZONE [], "LocalDateTime" TIMESTAMP WITHOUT TIME ZONE [], "OffsetDateTime" TIMESTAMP WITH TIME ZONE [], "UUID" UUID [], "Numeric" NUMERIC [], "Bytea" BYTEA[], "JSON" JSON[], "JSONB" JSONB[], "Point" POINT[], "Line" LINE[], "Lseg" LSEG[], "Box" BOX[], "ClosedPath" PATH[], "OpenPath" PATH[], "Polygon" POLYGON[], "Circle" CIRCLE[], "Enum" mood[], "Interval" INTERVAL [], "CustomType" full_address[] ); INSERT INTO "ArrayDataType" VALUES (1, ARRAY [TRUE], ARRAY [1], ARRAY [2], ARRAY [3], ARRAY [4.1], ARRAY [5.2], ARRAY ['01234567'], ARRAY ['Knock, knock.Who’s there?very long pause….Java.'], ARRAY ['Knock, knock.Who’s there?very long pause….Java.'], ARRAY ['Knock, knock.Who’s there?very long pause….Java.'], ARRAY ['1998-05-11' :: DATE, '1998-05-11' :: DATE], ARRAY ['17:55:04.90512' :: TIME WITHOUT TIME ZONE], ARRAY ['17:55:04.90512+03' :: TIME WITH TIME ZONE], ARRAY ['2017-05-14 19:35:58.237666' :: TIMESTAMP WITHOUT TIME ZONE], ARRAY ['2017-05-14 23:59:59.237666-03' :: TIMESTAMP WITH TIME ZONE], ARRAY ['6f790482-b5bd-438b-a8b7-4a0bed747011' :: UUID], ARRAY [0,1,2,3], ARRAY [decode('48454c4c4f', 'hex')], ARRAY [' {"str":"blah", "int" : 1, "float" : 3.5, "object": {}, "array" : [] }' :: JSON, '[1,true,null,9.5,"Hi"]' :: JSON, '4' :: JSON, '"Hello World"' :: JSON, 'true' :: JSON, 'false' :: JSON, 'null' :: JSON], ARRAY [' {"str":"blah", "int" : 1, "float" : 3.5, "object": {}, "array" : [] }' :: JSON, '[1,true,null,9.5,"Hi"]' :: JSON, '4' :: JSON, '"Hello World"' :: JSON, 'true' :: JSON, 'false' :: JSON, 'null' :: JSON], ARRAY ['(1.0,1.0)':: POINT, '(2.0,2.0)' :: POINT], ARRAY ['{1.0,2.0,3.0}':: LINE, '{2.0,3.0,4.0}':: LINE], ARRAY ['((1.0,1.0),(2.0,2.0))':: LSEG, '((2.0,2.0),(3.0,3.0))':: LSEG], ARRAY ['((2.0,2.0),(1.0,1.0))':: BOX, '((3.0,3.0),(2.0,2.0))':: BOX], ARRAY ['((1.0,1.0),(2.0,1.0),(2.0,2.0),(2.0,1.0))':: PATH, '((2.0,2.0),(3.0,2.0),(3.0,3.0),(3.0,2.0))':: PATH], ARRAY ['[(1.0,1.0),(2.0,1.0),(2.0,2.0),(2.0,1.0)]':: PATH, '[(2.0,2.0),(3.0,2.0),(3.0,3.0),(3.0,2.0)]':: PATH], ARRAY ['((1.0,1.0),(2.0,2.0),(3.0,1.0))':: POLYGON, '((0.0,0.0),(0.0,1.0),(1.0,2.0),(2.0,1.0),(2.0,0.0))':: POLYGON], ARRAY ['<(1.0,1.0),1.0>':: CIRCLE, '<(0.0,0.0),2.0>':: CIRCLE], ARRAY['ok'::mood,'unhappy'::mood, 'happy'::mood], ARRAY['10 years 3 months 332 days 20 hours 20 minutes 20.999991 seconds'::INTERVAL, '20 minutes 20.123456 seconds'::INTERVAL, '30 months ago'::INTERVAL], ARRAY [ROW('Anytown', 'Main St', true)::full_address, ('Anytown', 'First St', false)::full_address]); INSERT INTO "ArrayDataType" VALUES (2, ARRAY [TRUE], ARRAY [1], ARRAY [2], ARRAY [3], ARRAY [4.1], ARRAY [5.2], ARRAY ['01234567'], ARRAY ['Knock, knock.Who’s there?very long pause….Java.'], ARRAY ['Knock, knock.Who’s there?very long pause….Java.'], ARRAY ['Knock, knock.Who’s there?very long pause….Java.'], ARRAY ['1998-05-11' :: DATE], ARRAY ['17:55:04.90512' :: TIME WITHOUT TIME ZONE], ARRAY ['17:55:04.90512+03' :: TIME WITH TIME ZONE], ARRAY ['2017-05-14 19:35:58.237666' :: TIMESTAMP WITHOUT TIME ZONE], ARRAY ['2017-05-14 23:59:59.237666-03' :: TIMESTAMP WITH TIME ZONE], ARRAY ['6f790482-b5bd-438b-a8b7-4a0bed747011' :: UUID], ARRAY [0,1,2,3], ARRAY [decode('48454c4c4f', 'hex')], ARRAY [' {"str":"blah", "int" : 1, "float" : 3.5, "object": {}, "array" : [] }' :: JSON, '[1,true,null,9.5,"Hi"]' :: JSON, '4' :: JSON, '"Hello World"' :: JSON, 'true' :: JSON, 'false' :: JSON, 'null' :: JSON], ARRAY [' {"str":"blah", "int" : 1, "float" : 3.5, "object": {}, "array" : [] }' :: JSON, '[1,true,null,9.5,"Hi"]' :: JSON, '4' :: JSON, '"Hello World"' :: JSON, 'true' :: JSON, 'false' :: JSON, 'null' :: JSON], ARRAY ['(1.0,1.0)':: POINT, '(2.0,2.0)' :: POINT], ARRAY ['{1.0,2.0,3.0}':: LINE, '{2.0,3.0,4.0}':: LINE], ARRAY ['((1.0,1.0),(2.0,2.0))':: LSEG, '((2.0,2.0),(3.0,3.0))':: LSEG], ARRAY ['((2.0,2.0),(1.0,1.0))':: BOX, '((3.0,3.0),(2.0,2.0))':: BOX], ARRAY ['((1.0,1.0),(2.0,1.0),(2.0,2.0),(2.0,1.0))':: PATH, '((2.0,2.0),(3.0,2.0),(3.0,3.0),(3.0,2.0))':: PATH], ARRAY ['[(1.0,1.0),(2.0,1.0),(2.0,2.0),(2.0,1.0)]':: PATH, '[(2.0,2.0),(3.0,2.0),(3.0,3.0),(3.0,2.0)]':: PATH], ARRAY ['((1.0,1.0),(2.0,2.0),(3.0,1.0))':: POLYGON, '((0.0,0.0),(0.0,1.0),(1.0,2.0),(2.0,1.0),(2.0,0.0))':: POLYGON], ARRAY ['<(1.0,1.0),1.0>':: CIRCLE, '<(0.0,0.0),2.0>':: CIRCLE], ARRAY['unhappy'::mood, 'happy'::mood], ARRAY['0 years 0 months 0 days 0 hours 0 minutes 0 seconds'::INTERVAL], ARRAY [ROW('Anytown', 'Main St', true)::full_address, ('Anytown', 'First St', false)::full_address]); DROP TABLE IF EXISTS "EnumDataType"; CREATE TABLE "EnumDataType" ( "id" INTEGER NOT NULL PRIMARY KEY, "currentMood" mood, "currentWeather" weather ); INSERT INTO "EnumDataType" ("id", "currentMood", "currentWeather") VALUES (1, 'ok', 'sunny'); INSERT INTO "EnumDataType" ("id", "currentMood", "currentWeather") VALUES (2, 'unhappy', 'cloudy'); INSERT INTO "EnumDataType" ("id", "currentMood", "currentWeather") VALUES (3, 'happy', 'rainy'); INSERT INTO "EnumDataType" ("id", "currentMood", "currentWeather") VALUES (4, null, null); INSERT INTO "EnumDataType" ("id", "currentMood", "currentWeather") VALUES (5, 'ok', 'sunny'); DROP TABLE IF EXISTS "CustomDataType"; CREATE TABLE "CustomDataType" ( "id" INTEGER NOT NULL PRIMARY KEY, "address" full_address ); INSERT INTO "CustomDataType" ("id", "address") VALUES (1, ('Anytown', 'Main St', true)); INSERT INTO "CustomDataType" ("id", "address") VALUES (2, ('Anytown', 'First St', false)); CREATE TABLE "AllDataTypes" ( boolean BOOLEAN, int2 INT2, int4 INT4, int8 INT8, float4 FLOAT4, float8 FLOAT8, char CHAR, varchar VARCHAR, text TEXT, enum mood, name NAME, numeric NUMERIC, uuid UUID, date DATE, time TIME, timetz TIMETZ, timestamp TIMESTAMP, timestamptz TIMESTAMPTZ, interval INTERVAL, bytea BYTEA, json JSON, jsonb JSONB, point POINT, line LINE, lseg LSEG, box BOX, path PATH, polygon POLYGON, circle CIRCLE ); ================================================ FILE: docker/postgres/resources/server.crt ================================================ -----BEGIN CERTIFICATE----- MIIDeDCCAuGgAwIBAgIJAPsnSZ7KK38hMA0GCSqGSIb3DQEBBQUAMIGFMQswCQYD VQQGEwJDQTEZMBcGA1UECBMQQnJpdGlzaCBDb2x1bWJpYTEOMAwGA1UEBxMFQ29t b3gxFDASBgNVBAoTC1RoZUJyYWluLmNhMRQwEgYDVQQDEwt0aGVicmFpbi5jYTEf MB0GCSqGSIb3DQEJARYQaW5mb0B0aGVicmFpbi5jYTAeFw0xNzA5MTUyMTE3MzVa Fw0yNzA5MTMyMTE3MzVaMIGFMQswCQYDVQQGEwJDQTEZMBcGA1UECBMQQnJpdGlz aCBDb2x1bWJpYTEOMAwGA1UEBxMFQ29tb3gxFDASBgNVBAoTC1RoZUJyYWluLmNh MRQwEgYDVQQDEwt0aGVicmFpbi5jYTEfMB0GCSqGSIb3DQEJARYQaW5mb0B0aGVi cmFpbi5jYTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA3ZjwfKKfhp4bHX7l vdfov6SbGYu8nTz/DhcIt+dY8f1SfjLMtJhI0BCaBNUrC3F5K02val9EUF8HIQFo HmrUXVVnN54Suca+HuJiJGMBxIPOy8EJsHWybqNdwq3SIUTzODpYQNjTiTR/Dlw6 OLZNFR9d1YgDCdaYAmI/g+V4tbcCAwEAAaOB7TCB6jAdBgNVHQ4EFgQUNLQbcLVw R2EbXG/ecZkqWIiKgMswgboGA1UdIwSBsjCBr4AUNLQbcLVwR2EbXG/ecZkqWIiK gMuhgYukgYgwgYUxCzAJBgNVBAYTAkNBMRkwFwYDVQQIExBCcml0aXNoIENvbHVt YmlhMQ4wDAYDVQQHEwVDb21veDEUMBIGA1UEChMLVGhlQnJhaW4uY2ExFDASBgNV BAMTC3RoZWJyYWluLmNhMR8wHQYJKoZIhvcNAQkBFhBpbmZvQHRoZWJyYWluLmNh ggkA+ydJnsorfyEwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOBgQDcb+Tt 1ULpXaWbmwxqjCK9XY3v1k0yPvoArawsQ2LEiJdF7hILlHCzwBxSqkWL2SHqb0NA /w+8YKv/EGGyoE3LC9tkXt8oO5rnQGEclt74Jz3Q1yFIRpHn5iF4Jd763Z0/ohxe WLZHrlllNHEw9xIiYgJFlFgPaj1rD0dR8MwcTg== -----END CERTIFICATE----- ================================================ FILE: docker/postgres/resources/server.key ================================================ -----BEGIN RSA PRIVATE KEY----- MIICXgIBAAKBgQDdmPB8op+GnhsdfuW91+i/pJsZi7ydPP8OFwi351jx/VJ+Msy0 mEjQEJoE1SsLcXkrTa9qX0RQXwchAWgeatRdVWc3nhK5xr4e4mIkYwHEg87LwQmw dbJuo13CrdIhRPM4OlhA2NOJNH8OXDo4tk0VH13ViAMJ1pgCYj+D5Xi1twIDAQAB AoGBAJayIxkfHo1Vh+sPGP15jvaE4lUFCkeD64+RaoRl977ZHvhjY4KM7TdRkuwm axdlG5mvQtN75eEiPp7bbgsBa1ipeFAfIM0UZkhRdP0vw+BmTnPaymycR4CP3mRO 0Nsm0TIFnBpEVWJmVL9QHcw7TXqzsxyO+t1+i+s0cqVc8msBAkEA8Zp9vBBD/e2w 8nWZ+XzY5V3fuZ1TdAaD9g1dGQZ5DQLEV708bsdJuru77YAQP5yKpmvzU5cl3LFC /3ryja1OMQJBAOrNRLUza8htYA+lgZuloy+E2lSKguyxlkQuagI5YTligFhYkiyo WuNGNSIMqdAaVZ7eNu3ADKLEjI994f3SQGcCQCdE0QLsMeDn7Ua7Tpd6b1Z4d5CX vaSyGmi3q1YR80LmHDuWimgHBDjRoq3rjriIHREHorkHbCP+u8ECnsHgVUECQQCB VU3qTYeqH+0Q0UaB+IvZieFFPgJ95Bf0OGi2Dusp08MEZs0lghqGI87ykW0cLtVI q/gvn2CWa5NNGrbXu+8zAkEAuI/0x026m7cr1JCQUCAEHqNa9x1mTNmmqGwkArvy BU0Zt8XlJcrO6uPH/MJCW4OCE48GLFqeSV3dANKhUgsSqg== -----END RSA PRIVATE KEY----- ================================================ FILE: docker/postgres/ssl.sh ================================================ #!/bin/bash # Borrowed from https://github.com/muccg/docker-postgres-ssl/blob/master/9.6/docker-entrypoint-initdb.d/devssl.sh cp /server.crt "${PGDATA}"/server.crt cp /server.key "${PGDATA}"/server.key chmod og-rwx "${PGDATA}"/server.key chown -R postgres:postgres "${PGDATA}" # turn on ssl sed -ri "s/^#?(ssl\s*=\s*)\S+/\1'on'/" "$PGDATA/postgresql.conf" ================================================ FILE: docker/postgres_tc/Dockerfile ================================================ FROM postgres ENV POSTGRES_DB postgres ENV POSTGRES_USER postgres ENV POSTGRES_PASSWORD postgres RUN apt-get update && apt-get install -y iproute COPY create-postgres.sql /docker-entrypoint-initdb.d/ ================================================ FILE: docker/postgres_tc/README.md ================================================ ## Postgres docker file for testing with tc Build container with tc installed ``` > docker build -t test/postgres_tc postgres ``` Running the container ``` > docker run --rm --name test-postgres_tc -p 5432:5432 --cap-add=NET_ADMIN test/postgres_tc ``` Add one 1 ms latency to eth0 ``` > docker exec -it test-postgres_tc tc qdisc add dev eth0 root netem delay 1ms ``` ================================================ FILE: docker/postgres_tc/create-postgres.sql ================================================ DROP TYPE IF EXISTS weather CASCADE; DROP TYPE IF EXISTS mood CASCADE; DROP TYPE IF EXISTS full_address CASCADE; CREATE TYPE weather AS ENUM ('sunny', 'cloudy', 'rainy'); CREATE TYPE mood AS ENUM ('unhappy', 'ok', 'happy'); CREATE TYPE full_address AS (city TEXT, street TEXT, home BOOLEAN); DROP TABLE IF EXISTS World; CREATE TABLE World ( id integer NOT NULL, randomNumber integer NOT NULL default 0, PRIMARY KEY (id) ); INSERT INTO World (id, randomnumber) SELECT x.id, random() * 10000 + 1 FROM generate_series(1,10000) as x(id); DROP TABLE IF EXISTS Fortune; CREATE TABLE Fortune ( id integer NOT NULL, message varchar(2048) NOT NULL, PRIMARY KEY (id) ); INSERT INTO Fortune (id, message) VALUES (1, 'fortune: No such file or directory'); INSERT INTO Fortune (id, message) VALUES (2, 'A computer scientist is someone who fixes things that aren''t broken.'); INSERT INTO Fortune (id, message) VALUES (3, 'After enough decimal places, nobody gives a damn.'); INSERT INTO Fortune (id, message) VALUES (4, 'A bad random number generator: 1, 1, 1, 1, 1, 4.33e+67, 1, 1, 1'); INSERT INTO Fortune (id, message) VALUES (5, 'A computer program does what you tell it to do, not what you want it to do.'); INSERT INTO Fortune (id, message) VALUES (6, 'Emacs is a nice operating system, but I prefer UNIX. — Tom Christaensen'); INSERT INTO Fortune (id, message) VALUES (7, 'Any program that runs right is obsolete.'); INSERT INTO Fortune (id, message) VALUES (8, 'A list is only as strong as its weakest link. — Donald Knuth'); INSERT INTO Fortune (id, message) VALUES (9, 'Feature: A bug with seniority.'); INSERT INTO Fortune (id, message) VALUES (10, 'Computers make very fast, very accurate mistakes.'); INSERT INTO Fortune (id, message) VALUES (11, ''); INSERT INTO Fortune (id, message) VALUES (12, 'フレームワークのベンチマーク'); DROP TABLE IF EXISTS "World"; CREATE TABLE "World" ( id integer NOT NULL, randomNumber integer NOT NULL default 0, PRIMARY KEY (id) ); INSERT INTO "World" (id, randomnumber) SELECT x.id, random() * 10000 + 1 FROM generate_series(1,10000) as x(id); DROP TABLE IF EXISTS "Fortune"; CREATE TABLE "Fortune" ( id integer NOT NULL, message varchar(2048) NOT NULL, PRIMARY KEY (id) ); INSERT INTO "Fortune" (id, message) VALUES (1, 'fortune: No such file or directory'); INSERT INTO "Fortune" (id, message) VALUES (2, 'A computer scientist is someone who fixes things that aren''t broken.'); INSERT INTO "Fortune" (id, message) VALUES (3, 'After enough decimal places, nobody gives a damn.'); INSERT INTO "Fortune" (id, message) VALUES (4, 'A bad random number generator: 1, 1, 1, 1, 1, 4.33e+67, 1, 1, 1'); INSERT INTO "Fortune" (id, message) VALUES (5, 'A computer program does what you tell it to do, not what you want it to do.'); INSERT INTO "Fortune" (id, message) VALUES (6, 'Emacs is a nice operating system, but I prefer UNIX. — Tom Christaensen'); INSERT INTO "Fortune" (id, message) VALUES (7, 'Any program that runs right is obsolete.'); INSERT INTO "Fortune" (id, message) VALUES (8, 'A list is only as strong as its weakest link. — Donald Knuth'); INSERT INTO "Fortune" (id, message) VALUES (9, 'Feature: A bug with seniority.'); INSERT INTO "Fortune" (id, message) VALUES (10, 'Computers make very fast, very accurate mistakes.'); INSERT INTO "Fortune" (id, message) VALUES (11, ''); INSERT INTO "Fortune" (id, message) VALUES (12, 'フレームワークのベンチマーク'); -- All purpose testing table DROP TABLE IF EXISTS Test; CREATE TABLE Test ( id integer NOT NULL, val varchar(2048) NOT NULL, PRIMARY KEY (id) ); DROP TABLE IF EXISTS "NumericDataType"; CREATE TABLE "NumericDataType" ("id" INTEGER NOT NULL PRIMARY KEY, "Short" INT2, "Integer" INT4, "Long" INT8, "Float" FLOAT4, "Double" FLOAT8, "BigDecimal" NUMERIC, "Boolean" BOOLEAN); INSERT INTO "NumericDataType" ("id", "Short", "Integer", "Long", "Float", "Double", "BigDecimal", "Boolean") VALUES (1, 32767, 2147483647, 9223372036854775807, 3.4028235E38, 1.7976931348623157E308, '9.99999999999999999999999999999999999', true); INSERT INTO "NumericDataType" ("id", "Short", "Integer", "Long", "Float", "Double", "BigDecimal", "Boolean") VALUES (2, 32767, 2147483647, 9223372036854775807, 3.4028235E38, 1.7976931348623157E308, '9.99999999999999999999999999999999999', true); DROP TABLE IF EXISTS "TemporalDataType"; CREATE TABLE "TemporalDataType" ("id" INTEGER NOT NULL PRIMARY KEY, "Date" date, "Time" time without time zone, "TimeTz" time with time zone, "Timestamp" timestamp without time zone, "TimestampTz" timestamp with time zone, "Interval" interval); INSERT INTO "TemporalDataType" ("id" ,"Date", "Time", "TimeTz", "Timestamp", "TimestampTz", "Interval") VALUES (1 ,'1981-05-30', '17:55:04.90512', '17:55:04.90512+03:07', '2017-05-14 19:35:58.237666', '2017-05-14 23:59:59.237666-03', '10 years 3 months 332 days 20 hours 20 minutes 20.999999 seconds'); INSERT INTO "TemporalDataType" ("id" ,"Date", "Time", "TimeTz", "Timestamp", "TimestampTz", "Interval") VALUES (2 ,'2017-05-30', '12:55:04.90512', '02:55:04.90512+03:07', '1909-05-14 19:35:58.237666', '1909-05-14 22:35:58.237666-03', '02:01:33'); INSERT INTO "TemporalDataType" ("id" ,"Date", "Time", "TimeTz", "Timestamp", "TimestampTz", "Interval") VALUES (3 ,'1900-01-01', '23:59:04.90512', '08:08:03.90512+03:07', '1800-01-01 23:57:53.237666', '1800-01-01 23:59:59.237666-03', '04:33:59'); INSERT INTO "TemporalDataType" ("id" ,"Date", "Time", "TimeTz", "Timestamp", "TimestampTz", "Interval") VALUES (4 ,'1900-01-01', '23:59:04.90512', '08:08:03.90512+03:07', '1800-01-01 23:57:53.237666', '1800-01-01 23:59:59.237666-03', '04:33:59'); DROP TABLE IF EXISTS "CharacterDataType"; CREATE TABLE "CharacterDataType" ( "id" INTEGER NOT NULL PRIMARY KEY, "Name" NAME, "SingleChar" CHAR, "FixedChar" CHAR(3), "Text" TEXT, "VarCharacter" VARCHAR, "uuid" UUID ); INSERT INTO "CharacterDataType" ("id" ,"Name", "SingleChar", "FixedChar", "Text", "VarCharacter", "uuid") VALUES (1, 'What is my name ?', 'A', 'YES', 'Hello World', 'Great!', '6f790482-b5bd-438b-a8b7-4a0bed747011'); INSERT INTO "CharacterDataType" ("id" ,"Name", "SingleChar", "FixedChar", "Text", "VarCharacter", "uuid") VALUES (2, 'What is my name ?', 'A', 'YES', 'Hello World', 'Great!', '6f790482-b5bd-438b-a8b7-4a0bed747011'); DROP TABLE IF EXISTS "JsonDataType"; CREATE TABLE "JsonDataType" ( "id" INTEGER NOT NULL PRIMARY KEY, "JsonObject" JSON, "JsonArray" JSON, "Number" JSON, "String" JSON, "BooleanTrue" JSON, "BooleanFalse" JSON, "Null" JSON ); INSERT INTO "JsonDataType" ("id" ,"JsonObject", "JsonArray", "Number", "String", "BooleanTrue", "BooleanFalse", "Null") VALUES (1, ' {"str":"blah", "int" : 1, "float" : 3.5, "object": {}, "array" : [] }', '[1,true,null,9.5,"Hi"]', '4', '"Hello World"', 'true', 'false', 'null'); INSERT INTO "JsonDataType" ("id" ,"JsonObject", "JsonArray", "Number", "String", "BooleanTrue", "BooleanFalse", "Null") VALUES (2, ' {"str":"blah", "int" : 1, "float" : 3.5, "object": {}, "array" : [] }', '[1,true,null,9.5,"Hi"]', '4', '"Hello World"', 'true', 'false', 'null'); DROP TABLE IF EXISTS "JsonbDataType"; CREATE TABLE "JsonbDataType" ( "id" INTEGER NOT NULL PRIMARY KEY, "JsonObject" JSONB, "JsonArray" JSONB, "Number" JSONB, "String" JSONB, "BooleanTrue" JSONB, "BooleanFalse" JSONB, "Null" JSONB ); INSERT INTO "JsonbDataType" ("id" ,"JsonObject", "JsonArray", "Number", "String", "BooleanTrue", "BooleanFalse", "Null") VALUES (1, ' {"str":"blah", "int" : 1, "float" : 3.5, "object": {}, "array" : [] }', '[1,true,null,9.5,"Hi"]', '4', '"Hello World"', 'true', 'false', 'null'); INSERT INTO "JsonbDataType" ("id" ,"JsonObject", "JsonArray", "Number", "String", "BooleanTrue", "BooleanFalse", "Null") VALUES (2, ' {"str":"blah", "int" : 1, "float" : 3.5, "object": {}, "array" : [] }', '[1,true,null,9.5,"Hi"]', '4', '"Hello World"', 'true', 'false', 'null'); DROP TABLE IF EXISTS TxTest; CREATE TABLE TxTest ( id integer NOT NULL, PRIMARY KEY (id) ); DROP TABLE IF EXISTS "ArrayDataType"; CREATE TABLE "ArrayDataType" ( "id" INTEGER NOT NULL PRIMARY KEY, "Boolean" BOOLEAN [], "Short" INT2 [], "Integer" INT4 [], "Long" INT8 [], "Float" FLOAT4 [], "Double" FLOAT8 [], "Char" CHAR(8) [], "Varchar" VARCHAR [], "Text" TEXT [], "Name" NAME [], "LocalDate" DATE [], "LocalTime" TIME WITHOUT TIME ZONE [], "OffsetTime" TIME WITH TIME ZONE [], "LocalDateTime" TIMESTAMP WITHOUT TIME ZONE [], "OffsetDateTime" TIMESTAMP WITH TIME ZONE [], "UUID" UUID [], "Numeric" NUMERIC [], "Bytea" BYTEA[], "JSON" JSON[], "JSONB" JSONB[], "Enum" mood[], "Interval" INTERVAL [], "CustomType" full_address[] ); INSERT INTO "ArrayDataType" VALUES (1, ARRAY [TRUE], ARRAY [1], ARRAY [2], ARRAY [3], ARRAY [4.1], ARRAY [5.2], ARRAY ['01234567'], ARRAY ['Knock, knock.Who’s there?very long pause….Java.'], ARRAY ['Knock, knock.Who’s there?very long pause….Java.'], ARRAY ['Knock, knock.Who’s there?very long pause….Java.'], ARRAY ['1998-05-11' :: DATE, '1998-05-11' :: DATE], ARRAY ['17:55:04.90512' :: TIME WITHOUT TIME ZONE], ARRAY ['17:55:04.90512+03' :: TIME WITH TIME ZONE], ARRAY ['2017-05-14 19:35:58.237666' :: TIMESTAMP WITHOUT TIME ZONE], ARRAY ['2017-05-14 23:59:59.237666-03' :: TIMESTAMP WITH TIME ZONE], ARRAY ['6f790482-b5bd-438b-a8b7-4a0bed747011' :: UUID], ARRAY [0,1,2,3], ARRAY [decode('48454c4c4f', 'hex')], ARRAY [' {"str":"blah", "int" : 1, "float" : 3.5, "object": {}, "array" : [] }' :: JSON, '[1,true,null,9.5,"Hi"]' :: JSON, '4' :: JSON, '"Hello World"' :: JSON, 'true' :: JSON, 'false' :: JSON, 'null' :: JSON], ARRAY [' {"str":"blah", "int" : 1, "float" : 3.5, "object": {}, "array" : [] }' :: JSON, '[1,true,null,9.5,"Hi"]' :: JSON, '4' :: JSON, '"Hello World"' :: JSON, 'true' :: JSON, 'false' :: JSON, 'null' :: JSON], ARRAY['ok'::mood,'unhappy'::mood, 'happy'::mood], ARRAY['10 years 3 months 332 days 20 hours 20 minutes 20.999991 seconds'::INTERVAL, '20 minutes 20.123456 seconds'::INTERVAL, '30 months ago'::INTERVAL], ARRAY [ROW('Anytown', 'Main St', true)::full_address, ('Anytown', 'First St', false)::full_address]); INSERT INTO "ArrayDataType" VALUES (2, ARRAY [TRUE], ARRAY [1], ARRAY [2], ARRAY [3], ARRAY [4.1], ARRAY [5.2], ARRAY ['01234567'], ARRAY ['Knock, knock.Who’s there?very long pause….Java.'], ARRAY ['Knock, knock.Who’s there?very long pause….Java.'], ARRAY ['Knock, knock.Who’s there?very long pause….Java.'], ARRAY ['1998-05-11' :: DATE], ARRAY ['17:55:04.90512' :: TIME WITHOUT TIME ZONE], ARRAY ['17:55:04.90512+03' :: TIME WITH TIME ZONE], ARRAY ['2017-05-14 19:35:58.237666' :: TIMESTAMP WITHOUT TIME ZONE], ARRAY ['2017-05-14 23:59:59.237666-03' :: TIMESTAMP WITH TIME ZONE], ARRAY ['6f790482-b5bd-438b-a8b7-4a0bed747011' :: UUID], ARRAY [0,1,2,3], ARRAY [decode('48454c4c4f', 'hex')], ARRAY [' {"str":"blah", "int" : 1, "float" : 3.5, "object": {}, "array" : [] }' :: JSON, '[1,true,null,9.5,"Hi"]' :: JSON, '4' :: JSON, '"Hello World"' :: JSON, 'true' :: JSON, 'false' :: JSON, 'null' :: JSON], ARRAY [' {"str":"blah", "int" : 1, "float" : 3.5, "object": {}, "array" : [] }' :: JSON, '[1,true,null,9.5,"Hi"]' :: JSON, '4' :: JSON, '"Hello World"' :: JSON, 'true' :: JSON, 'false' :: JSON, 'null' :: JSON], ARRAY['unhappy'::mood, 'happy'::mood], ARRAY['0 years 0 months 0 days 0 hours 0 minutes 0 seconds'::INTERVAL], ARRAY [ROW('Anytown', 'Main St', true)::full_address, ('Anytown', 'First St', false)::full_address]); DROP TABLE IF EXISTS "EnumDataType"; CREATE TABLE "EnumDataType" ( "id" INTEGER NOT NULL PRIMARY KEY, "currentMood" mood, "currentWeather" weather ); INSERT INTO "EnumDataType" ("id", "currentMood", "currentWeather") VALUES (1, 'ok', 'sunny'); INSERT INTO "EnumDataType" ("id", "currentMood", "currentWeather") VALUES (2, 'unhappy', 'cloudy'); INSERT INTO "EnumDataType" ("id", "currentMood", "currentWeather") VALUES (3, 'happy', 'rainy'); INSERT INTO "EnumDataType" ("id", "currentMood", "currentWeather") VALUES (4, null, null); INSERT INTO "EnumDataType" ("id", "currentMood", "currentWeather") VALUES (5, 'ok', 'sunny'); DROP TABLE IF EXISTS "CustomDataType"; CREATE TABLE "CustomDataType" ( "id" INTEGER NOT NULL PRIMARY KEY, "address" full_address ); INSERT INTO "CustomDataType" ("id", "address") VALUES (1, ('Anytown', 'Main St', true)); INSERT INTO "CustomDataType" ("id", "address") VALUES (2, ('Anytown', 'First St', false)); CREATE TABLE "AllDataTypes" ( boolean BOOLEAN, int2 INT2, int4 INT4, int8 INT8, float4 FLOAT4, float8 FLOAT8, char CHAR, varchar VARCHAR, text TEXT, enum mood, name NAME, numeric NUMERIC, uuid UUID, date DATE, time TIME, timetz TIMETZ, timestamp TIMESTAMP, timestamptz TIMESTAMPTZ, interval INTERVAL, bytea BYTEA, json JSON, jsonb JSONB, point POINT, line LINE, lseg LSEG, box BOX, path PATH, polygon POLYGON, circle CIRCLE ); ================================================ FILE: docs/README.md ================================================ # The Reactive Postgres Client * Simple API focusing on scalability and low overhead. * Reactive and non blocking which able to handle many database connections with a single thread. * Ranked 1 in the [TechEmpower Benchmark Round 15](https://www.techempower.com/benchmarks/#section=data-r15&hw=ph&test=db) _Single query_ benchmark. * Top ranked in the TechEmpower Benchmark Round 16 * Single query benchmark: [Ranked 1 physical](https://www.techempower.com/benchmarks/#section=data-r16&hw=ph&test=db) / [Ranked 1 cloud](https://www.techempower.com/benchmarks/#section=data-r16&hw=cl&test=db) * Multiples queries benchmark: [Ranked 1 physical](https://www.techempower.com/benchmarks/#section=data-r16&hw=ph&test=query) / [Ranked 1 cloud](https://www.techempower.com/benchmarks/#section=data-r16&hw=cl&test=query) * Data updates: [Ranked 1 physical](https://www.techempower.com/benchmarks/#section=data-r16&hw=ph&test=update) / [Ranked 1 cloud](https://www.techempower.com/benchmarks/#section=data-r16&hw=cl&test=update) * Fortunes: [Ranked 3 physical](https://www.techempower.com/benchmarks/#section=data-r16&hw=ph&test=fortune) / [Ranked 2 cloud](https://www.techempower.com/benchmarks/#section=data-r16&hw=cl&test=fortune) ## Features * Event driven * Lightweight * Built-in connection pooling * Prepared queries caching * Publish / subscribe using Postgres `NOTIFY/LISTEN` * Batch and cursor * Row streaming * `java.util.stream.Collector` row set transformation * Command pipeling * RxJava 1 and RxJava 2 * Direct memory to object without unnecessary copies * Java 8 Date and Time * SSL/TLS * Unix domain socket * HTTP/1.x CONNECT, SOCKS4a or SOCKS5 proxy support ## Documentation * [Java](guide/java/index.md) * [Kotlin](guide/kotlin/index.md) * [Groovy](guide/groovy/index.md) * [JavaScript](guide/js/index.md) * [Ruby](guide/ruby/index.md) ================================================ FILE: docs/_config.yml ================================================ theme: jekyll-theme-minimal repository: reactiverse/reactive-pg-client ================================================ FILE: docs/apidocs/allclasses-frame.html ================================================ All Classes (Reactive Postgres Client 0.11.2 API)

All Classes

================================================ FILE: docs/apidocs/allclasses-noframe.html ================================================ All Classes (Reactive Postgres Client 0.11.2 API)

All Classes

================================================ FILE: docs/apidocs/constant-values.html ================================================ Constant Field Values (Reactive Postgres Client 0.11.2 API)

Constant Field Values

Contents

io.reactiverse.*

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/deprecated-list.html ================================================ Deprecated List (Reactive Postgres Client 0.11.2 API)

Deprecated API

Contents

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/help-doc.html ================================================ API Help (Reactive Postgres Client 0.11.2 API)

How This API Document Is Organized

This API (Application Programming Interface) document has pages corresponding to the items in the navigation bar, described as follows.
This help file applies to API documentation generated using the standard doclet.

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/index-all.html ================================================ Index (Reactive Postgres Client 0.11.2 API)
A B C D E F G H I J L M N O P Q R S T V X Y _ 

A

abortHandler(Handler<Void>) - Method in interface io.reactiverse.pgclient.PgTransaction
Set an handler to be called when the transaction is aborted.
abortHandler(Handler<Void>) - Method in class io.reactiverse.reactivex.pgclient.PgTransaction
Set an handler to be called when the transaction is aborted.
abortHandler(Handler<Void>) - Method in class io.reactiverse.rxjava.pgclient.PgTransaction
Set an handler to be called when the transaction is aborted.
actualConnection() - Method in interface io.reactiverse.pgclient.pubsub.PgSubscriber
 
actualConnection() - Method in class io.reactiverse.reactivex.pgclient.pubsub.PgSubscriber
 
actualConnection() - Method in class io.reactiverse.rxjava.pgclient.pubsub.PgSubscriber
 
addBigDecimal(BigDecimal) - Method in interface io.reactiverse.pgclient.Tuple
Add a BigDecimal value at the end of the tuple.
addBigDecimal(BigDecimal) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add a value at the end of the tuple.
addBigDecimal(BigDecimal) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add a value at the end of the tuple.
addBoolean(Boolean) - Method in interface io.reactiverse.pgclient.Tuple
Add a boolean value at the end of the tuple.
addBoolean(Boolean) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add a boolean value at the end of the tuple.
addBoolean(Boolean) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add a boolean value at the end of the tuple.
addBooleanArray(Boolean[]) - Method in interface io.reactiverse.pgclient.Tuple
Add an array of Boolean value at the end of the tuple.
addBooleanArray(Boolean[]) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add an array of Boolean value at the end of the tuple.
addBooleanArray(Boolean[]) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add an array of Boolean value at the end of the tuple.
addBox(Box) - Method in interface io.reactiverse.pgclient.Tuple
Add a Box value at the end of the tuple.
addBox(Box) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add a value at the end of the tuple.
addBox(Box) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add a value at the end of the tuple.
addBoxArray(Box[]) - Method in interface io.reactiverse.pgclient.Tuple
Add an array of Box value at the end of the tuple.
addBoxArray(Box[]) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add an array of value at the end of the tuple.
addBoxArray(Box[]) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add an array of value at the end of the tuple.
addBuffer(Buffer) - Method in interface io.reactiverse.pgclient.Tuple
Add a buffer value at the end of the tuple.
addBuffer(Buffer) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add a buffer value at the end of the tuple.
addBuffer(Buffer) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add a buffer value at the end of the tuple.
addBufferArray(Buffer[]) - Method in interface io.reactiverse.pgclient.Tuple
Add an array of Buffer value at the end of the tuple.
addCircle(Circle) - Method in interface io.reactiverse.pgclient.Tuple
Add a Circle value at the end of the tuple.
addCircle(Circle) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add a value at the end of the tuple.
addCircle(Circle) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add a value at the end of the tuple.
addCircleArray(Circle[]) - Method in interface io.reactiverse.pgclient.Tuple
Add an array of Circle value at the end of the tuple.
addCircleArray(Circle[]) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add an array of value at the end of the tuple.
addCircleArray(Circle[]) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add an array of value at the end of the tuple.
addCrlPath(String) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
addCrlPath(String) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
addCrlValue(Buffer) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
addCrlValue(Buffer) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
addDouble(Double) - Method in interface io.reactiverse.pgclient.Tuple
Add a double value at the end of the tuple.
addDouble(Double) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add a double value at the end of the tuple.
addDouble(Double) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add a double value at the end of the tuple.
addDoubleArray(Double[]) - Method in interface io.reactiverse.pgclient.Tuple
Add an array of Double value at the end of the tuple.
addDoubleArray(Double[]) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add an array of Double value at the end of the tuple.
addDoubleArray(Double[]) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add an array of Double value at the end of the tuple.
addEnabledCipherSuite(String) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
addEnabledCipherSuite(String) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
addEnabledSecureTransportProtocol(String) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
addEnabledSecureTransportProtocol(String) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
addFloat(Float) - Method in interface io.reactiverse.pgclient.Tuple
Add a float value at the end of the tuple.
addFloat(Float) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add a float value at the end of the tuple.
addFloat(Float) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add a float value at the end of the tuple.
addFloatArray(Float[]) - Method in interface io.reactiverse.pgclient.Tuple
Add an array of Float value at the end of the tuple.
addFloatArray(Float[]) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add an array of Float value at the end of the tuple.
addFloatArray(Float[]) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add an array of Float value at the end of the tuple.
addInteger(Integer) - Method in interface io.reactiverse.pgclient.Tuple
Add an integer value at the end of the tuple.
addInteger(Integer) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add an integer value at the end of the tuple.
addInteger(Integer) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add an integer value at the end of the tuple.
addIntegerArray(Integer[]) - Method in interface io.reactiverse.pgclient.Tuple
Add an array of Integer value at the end of the tuple.
addIntegerArray(Integer[]) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add an array of Integer value at the end of the tuple.
addIntegerArray(Integer[]) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add an array of Integer value at the end of the tuple.
addInterval(Interval) - Method in interface io.reactiverse.pgclient.Tuple
Add a Point value at the end of the tuple.
addInterval(Interval) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add a value at the end of the tuple.
addInterval(Interval) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add a value at the end of the tuple.
addIntervalArray(Interval[]) - Method in interface io.reactiverse.pgclient.Tuple
Add an array of Interval value at the end of the tuple.
addIntervalArray(Interval[]) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add an array of value at the end of the tuple.
addIntervalArray(Interval[]) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add an array of value at the end of the tuple.
addJson(Json) - Method in interface io.reactiverse.pgclient.Tuple
Add a json value at the end of the tuple.
addJson(Json) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add a json value at the end of the tuple.
addJson(Json) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add a json value at the end of the tuple.
addJsonArray(Json[]) - Method in interface io.reactiverse.pgclient.Tuple
Add an array of Json value at the end of the tuple.
addLine(Line) - Method in interface io.reactiverse.pgclient.Tuple
Add a Line value at the end of the tuple.
addLine(Line) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add a value at the end of the tuple.
addLine(Line) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add a value at the end of the tuple.
addLineArray(Line[]) - Method in interface io.reactiverse.pgclient.Tuple
Add an array of Line value at the end of the tuple.
addLineArray(Line[]) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add an array of Line value at the end of the tuple.
addLineArray(Line[]) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add an array of Line value at the end of the tuple.
addLineSegment(LineSegment) - Method in interface io.reactiverse.pgclient.Tuple
Add a LineSegment value at the end of the tuple.
addLineSegment(LineSegment) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add a value at the end of the tuple.
addLineSegment(LineSegment) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add a value at the end of the tuple.
addLineSegmentArray(LineSegment[]) - Method in interface io.reactiverse.pgclient.Tuple
Add an array of LineSegment value at the end of the tuple.
addLineSegmentArray(LineSegment[]) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add an array of value at the end of the tuple.
addLineSegmentArray(LineSegment[]) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add an array of value at the end of the tuple.
addLocalDate(LocalDate) - Method in interface io.reactiverse.pgclient.Tuple
Add a LocalDate value at the end of the tuple.
addLocalDate(LocalDate) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add a LocalDate value at the end of the tuple.
addLocalDate(LocalDate) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add a LocalDate value at the end of the tuple.
addLocalDateArray(LocalDate[]) - Method in interface io.reactiverse.pgclient.Tuple
Add an array of LocalDate value at the end of the tuple.
addLocalDateArray(LocalDate[]) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add an array of value at the end of the tuple.
addLocalDateArray(LocalDate[]) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add an array of value at the end of the tuple.
addLocalDateTime(LocalDateTime) - Method in interface io.reactiverse.pgclient.Tuple
Add a LocalDateTime value at the end of the tuple.
addLocalDateTime(LocalDateTime) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add a LocalDateTime value at the end of the tuple.
addLocalDateTime(LocalDateTime) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add a LocalDateTime value at the end of the tuple.
addLocalDateTimeArray(LocalDateTime[]) - Method in interface io.reactiverse.pgclient.Tuple
Add an array of LocalDateTime value at the end of the tuple.
addLocalDateTimeArray(LocalDateTime[]) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add an array of value at the end of the tuple.
addLocalDateTimeArray(LocalDateTime[]) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add an array of value at the end of the tuple.
addLocalTime(LocalTime) - Method in interface io.reactiverse.pgclient.Tuple
Add a LocalTime value at the end of the tuple.
addLocalTime(LocalTime) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add a LocalTime value at the end of the tuple.
addLocalTime(LocalTime) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add a LocalTime value at the end of the tuple.
addLocalTimeArray(LocalTime[]) - Method in interface io.reactiverse.pgclient.Tuple
Add an array of LocalTime value at the end of the tuple.
addLocalTimeArray(LocalTime[]) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add an array of value at the end of the tuple.
addLocalTimeArray(LocalTime[]) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add an array of value at the end of the tuple.
addLong(Long) - Method in interface io.reactiverse.pgclient.Tuple
Add a long value at the end of the tuple.
addLong(Long) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add a long value at the end of the tuple.
addLong(Long) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add a long value at the end of the tuple.
addLongArray(Long[]) - Method in interface io.reactiverse.pgclient.Tuple
Add an array of Long value at the end of the tuple.
addLongArray(Long[]) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add an array of Long value at the end of the tuple.
addLongArray(Long[]) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add an array of Long value at the end of the tuple.
addNumeric(Numeric) - Method in interface io.reactiverse.pgclient.Tuple
Add a Numeric value at the end of the tuple.
addNumeric(Numeric) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add a value at the end of the tuple.
addNumeric(Numeric) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add a value at the end of the tuple.
addNumericArray(Numeric[]) - Method in interface io.reactiverse.pgclient.Tuple
Add an array of Numeric value at the end of the tuple.
addNumericArray(Numeric[]) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add an array of value at the end of the tuple.
addNumericArray(Numeric[]) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add an array of value at the end of the tuple.
addOffsetDateTime(OffsetDateTime) - Method in interface io.reactiverse.pgclient.Tuple
Add a OffsetDateTime value at the end of the tuple.
addOffsetDateTime(OffsetDateTime) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add a OffsetDateTime value at the end of the tuple.
addOffsetDateTime(OffsetDateTime) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add a OffsetDateTime value at the end of the tuple.
addOffsetDateTimeArray(OffsetDateTime[]) - Method in interface io.reactiverse.pgclient.Tuple
Add an array of OffsetDateTime value at the end of the tuple.
addOffsetDateTimeArray(OffsetDateTime[]) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add an array of value at the end of the tuple.
addOffsetDateTimeArray(OffsetDateTime[]) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add an array of value at the end of the tuple.
addOffsetTime(OffsetTime) - Method in interface io.reactiverse.pgclient.Tuple
Add a OffsetTime value at the end of the tuple.
addOffsetTime(OffsetTime) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add a OffsetTime value at the end of the tuple.
addOffsetTime(OffsetTime) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add a OffsetTime value at the end of the tuple.
addOffsetTimeArray(OffsetTime[]) - Method in interface io.reactiverse.pgclient.Tuple
Add an array of OffsetTime value at the end of the tuple.
addOffsetTimeArray(OffsetTime[]) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add an array of value at the end of the tuple.
addOffsetTimeArray(OffsetTime[]) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add an array of value at the end of the tuple.
addPath(Path) - Method in interface io.reactiverse.pgclient.Tuple
Add a Path value at the end of the tuple.
addPath(Path) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add a value at the end of the tuple.
addPath(Path) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add a value at the end of the tuple.
addPathArray(Path[]) - Method in interface io.reactiverse.pgclient.Tuple
Add an array of Path value at the end of the tuple.
addPathArray(Path[]) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add an array of value at the end of the tuple.
addPathArray(Path[]) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add an array of value at the end of the tuple.
addPoint(Point) - Method in interface io.reactiverse.pgclient.Tuple
Add a Point value at the end of the tuple.
addPoint(Point) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add a value at the end of the tuple.
addPoint(Point) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add a value at the end of the tuple.
addPointArray(Point[]) - Method in interface io.reactiverse.pgclient.Tuple
Add an array of Point value at the end of the tuple.
addPointArray(Point[]) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add an array of value at the end of the tuple.
addPointArray(Point[]) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add an array of value at the end of the tuple.
addPolygon(Polygon) - Method in interface io.reactiverse.pgclient.Tuple
Add a Polygon value at the end of the tuple.
addPolygon(Polygon) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add a value at the end of the tuple.
addPolygon(Polygon) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add a value at the end of the tuple.
addPolygonArray(Polygon[]) - Method in interface io.reactiverse.pgclient.Tuple
Add an array of Polygon value at the end of the tuple.
addPolygonArray(Polygon[]) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add an array of value at the end of the tuple.
addPolygonArray(Polygon[]) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add an array of value at the end of the tuple.
addShort(Short) - Method in interface io.reactiverse.pgclient.Tuple
Add a short value at the end of the tuple.
addShort(Short) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add a short value at the end of the tuple.
addShort(Short) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add a short value at the end of the tuple.
addShortArray(Short[]) - Method in interface io.reactiverse.pgclient.Tuple
Add an array of Short value at the end of the tuple.
addShortArray(Short[]) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add an array of Short value at the end of the tuple.
addShortArray(Short[]) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add an array of Short value at the end of the tuple.
addString(String) - Method in interface io.reactiverse.pgclient.Tuple
Add a string value at the end of the tuple.
addString(String) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add a string value at the end of the tuple.
addString(String) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add a string value at the end of the tuple.
addStringArray(String[]) - Method in interface io.reactiverse.pgclient.Tuple
Add an array of String value at the end of the tuple.
addStringArray(String[]) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add an array of String value at the end of the tuple.
addStringArray(String[]) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add an array of String value at the end of the tuple.
addTemporal(Temporal) - Method in interface io.reactiverse.pgclient.Tuple
Add a Temporal value at the end of the tuple.
addTemporal(Temporal) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add a Temporal value at the end of the tuple.
addTemporal(Temporal) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add a Temporal value at the end of the tuple.
addUUID(UUID) - Method in interface io.reactiverse.pgclient.Tuple
Add a UUID value at the end of the tuple.
addUUID(UUID) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add a UUID value at the end of the tuple.
addUUID(UUID) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add a UUID value at the end of the tuple.
addUUIDArray(UUID[]) - Method in interface io.reactiverse.pgclient.Tuple
Add an array of UUID value at the end of the tuple.
addUUIDArray(UUID[]) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add an array of value at the end of the tuple.
addUUIDArray(UUID[]) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add an array of value at the end of the tuple.
addValue(Object) - Method in interface io.reactiverse.pgclient.Tuple
Add an object value at the end of the tuple.
addValue(Object) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Add an object value at the end of the tuple.
addValue(Object) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Add an object value at the end of the tuple.

B

batch(List<Tuple>, Handler<AsyncResult<PgRowSet>>) - Method in interface io.reactiverse.pgclient.PgPreparedQuery
Execute a batch.
batch(List<Tuple>, Collector<Row, ?, R>, Handler<AsyncResult<PgResult<R>>>) - Method in interface io.reactiverse.pgclient.PgPreparedQuery
Execute a batch.
batch(List<Tuple>, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.reactivex.pgclient.PgPreparedQuery
Execute a batch.
batch(List<Tuple>, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.rxjava.pgclient.PgPreparedQuery
Execute a batch.
begin() - Method in interface io.reactiverse.pgclient.PgConnection
Begin a transaction and returns a PgTransaction for controlling and tracking this transaction.
begin(Handler<AsyncResult<PgTransaction>>) - Method in interface io.reactiverse.pgclient.PgPool
Borrow a connection from the pool and begin a transaction, the underlying connection will be returned to the pool when the transaction ends.
begin() - Method in class io.reactiverse.reactivex.pgclient.PgConnection
Begin a transaction and returns a PgTransaction for controlling and tracking this transaction.
begin(Handler<AsyncResult<PgTransaction>>) - Method in class io.reactiverse.reactivex.pgclient.PgPool
Borrow a connection from the pool and begin a transaction, the underlying connection will be returned to the pool when the transaction ends.
begin() - Method in class io.reactiverse.rxjava.pgclient.PgConnection
Begin a transaction and returns a PgTransaction for controlling and tracking this transaction.
begin(Handler<AsyncResult<PgTransaction>>) - Method in class io.reactiverse.rxjava.pgclient.PgPool
Borrow a connection from the pool and begin a transaction, the underlying connection will be returned to the pool when the transaction ends.
bigDecimalValue() - Method in class io.reactiverse.pgclient.data.Numeric
 
bigIntegerValue() - Method in class io.reactiverse.pgclient.data.Numeric
 
Box - Class in io.reactiverse.pgclient.data
Rectangular box data type in Postgres represented by pairs of Points that are opposite corners of the box.
Box() - Constructor for class io.reactiverse.pgclient.data.Box
 
Box(Point, Point) - Constructor for class io.reactiverse.pgclient.data.Box
 
Box(JsonObject) - Constructor for class io.reactiverse.pgclient.data.Box
 
BoxConverter - Class in io.reactiverse.pgclient.data
Converter for Box.
BoxConverter() - Constructor for class io.reactiverse.pgclient.data.BoxConverter
 

C

cancelRequest(Handler<AsyncResult<Void>>) - Method in interface io.reactiverse.pgclient.PgConnection
Send a request cancellation message to tell the server to cancel processing request in this connection.
cancelRequest(Handler<AsyncResult<Void>>) - Method in class io.reactiverse.reactivex.pgclient.PgConnection
Send a request cancellation message to tell the server to cancel processing request in this connection.
cancelRequest(Handler<AsyncResult<Void>>) - Method in class io.reactiverse.rxjava.pgclient.PgConnection
Send a request cancellation message to tell the server to cancel processing request in this connection.
channel(String) - Method in interface io.reactiverse.pgclient.pubsub.PgSubscriber
Return a channel for the given name.
channel(String) - Method in class io.reactiverse.reactivex.pgclient.pubsub.PgSubscriber
Return a channel for the given name.
channel(String) - Method in class io.reactiverse.rxjava.pgclient.pubsub.PgSubscriber
Return a channel for the given name.
Circle - Class in io.reactiverse.pgclient.data
Circle data type in Postgres represented by a center Point and radius.
Circle() - Constructor for class io.reactiverse.pgclient.data.Circle
 
Circle(Point, double) - Constructor for class io.reactiverse.pgclient.data.Circle
 
Circle(JsonObject) - Constructor for class io.reactiverse.pgclient.data.Circle
 
CircleConverter - Class in io.reactiverse.pgclient.data
Converter for Circle.
CircleConverter() - Constructor for class io.reactiverse.pgclient.data.CircleConverter
 
clear() - Method in interface io.reactiverse.pgclient.Tuple
 
clear() - Method in class io.reactiverse.reactivex.pgclient.Tuple
 
clear() - Method in class io.reactiverse.rxjava.pgclient.Tuple
 
close() - Method in interface io.reactiverse.pgclient.PgConnection
Close the current connection after all the pending commands have been processed.
close() - Method in interface io.reactiverse.pgclient.PgCursor
Release the cursor.
close(Handler<AsyncResult<Void>>) - Method in interface io.reactiverse.pgclient.PgCursor
Like PgCursor.close() but with a completionHandler called when the cursor has been released.
close() - Method in interface io.reactiverse.pgclient.PgPool
Close the pool and release the associated resources.
close() - Method in interface io.reactiverse.pgclient.PgPreparedQuery
Close the prepared query and release its resources.
close(Handler<AsyncResult<Void>>) - Method in interface io.reactiverse.pgclient.PgPreparedQuery
Like PgPreparedQuery.close() but notifies the completionHandler when it's closed.
close() - Method in interface io.reactiverse.pgclient.PgStream
Close the stream and release the resources.
close(Handler<AsyncResult<Void>>) - Method in interface io.reactiverse.pgclient.PgStream
Close the stream and release the resources.
close() - Method in interface io.reactiverse.pgclient.pubsub.PgSubscriber
Close the subscriber, the retry policy will not be invoked.
close() - Method in class io.reactiverse.reactivex.pgclient.PgConnection
Close the current connection after all the pending commands have been processed.
close() - Method in class io.reactiverse.reactivex.pgclient.PgCursor
Release the cursor.
close(Handler<AsyncResult<Void>>) - Method in class io.reactiverse.reactivex.pgclient.PgCursor
Like PgCursor.close() but with a completionHandler called when the cursor has been released.
close() - Method in class io.reactiverse.reactivex.pgclient.PgPool
Close the pool and release the associated resources.
close() - Method in class io.reactiverse.reactivex.pgclient.PgPreparedQuery
Close the prepared query and release its resources.
close(Handler<AsyncResult<Void>>) - Method in class io.reactiverse.reactivex.pgclient.PgPreparedQuery
Like PgPreparedQuery.close() but notifies the completionHandler when it's closed.
close() - Method in class io.reactiverse.reactivex.pgclient.PgStream
Close the stream and release the resources.
close(Handler<AsyncResult<Void>>) - Method in class io.reactiverse.reactivex.pgclient.PgStream
Close the stream and release the resources.
close() - Method in class io.reactiverse.reactivex.pgclient.pubsub.PgSubscriber
Close the subscriber, the retry policy will not be invoked.
close() - Method in class io.reactiverse.rxjava.pgclient.PgConnection
Close the current connection after all the pending commands have been processed.
close() - Method in class io.reactiverse.rxjava.pgclient.PgCursor
Release the cursor.
close(Handler<AsyncResult<Void>>) - Method in class io.reactiverse.rxjava.pgclient.PgCursor
Like PgCursor.close() but with a completionHandler called when the cursor has been released.
close() - Method in class io.reactiverse.rxjava.pgclient.PgPool
Close the pool and release the associated resources.
close() - Method in class io.reactiverse.rxjava.pgclient.PgPreparedQuery
Close the prepared query and release its resources.
close(Handler<AsyncResult<Void>>) - Method in class io.reactiverse.rxjava.pgclient.PgPreparedQuery
Like PgPreparedQuery.close() but notifies the completionHandler when it's closed.
close() - Method in class io.reactiverse.rxjava.pgclient.PgStream
Close the stream and release the resources.
close(Handler<AsyncResult<Void>>) - Method in class io.reactiverse.rxjava.pgclient.PgStream
Close the stream and release the resources.
close() - Method in class io.reactiverse.rxjava.pgclient.pubsub.PgSubscriber
Close the subscriber, the retry policy will not be invoked.
closed() - Method in interface io.reactiverse.pgclient.pubsub.PgSubscriber
 
closed() - Method in class io.reactiverse.reactivex.pgclient.pubsub.PgSubscriber
 
closed() - Method in class io.reactiverse.rxjava.pgclient.pubsub.PgSubscriber
 
closeHandler(Handler<Void>) - Method in interface io.reactiverse.pgclient.PgConnection
Set an handler called when the connection is closed.
closeHandler(Handler<Void>) - Method in interface io.reactiverse.pgclient.pubsub.PgSubscriber
Set an handler called when the subscriber is closed.
closeHandler(Handler<Void>) - Method in class io.reactiverse.reactivex.pgclient.PgConnection
Set an handler called when the connection is closed.
closeHandler(Handler<Void>) - Method in class io.reactiverse.reactivex.pgclient.pubsub.PgSubscriber
Set an handler called when the subscriber is closed.
closeHandler(Handler<Void>) - Method in class io.reactiverse.rxjava.pgclient.PgConnection
Set an handler called when the connection is closed.
closeHandler(Handler<Void>) - Method in class io.reactiverse.rxjava.pgclient.pubsub.PgSubscriber
Set an handler called when the subscriber is closed.
columnsNames() - Method in interface io.reactiverse.pgclient.PgResult
Get the names of columns in the PgResult.
columnsNames() - Method in class io.reactiverse.reactivex.pgclient.PgResult
Get the names of columns in the PgResult.
columnsNames() - Method in class io.reactiverse.rxjava.pgclient.PgResult
Get the names of columns in the PgResult.
commit() - Method in interface io.reactiverse.pgclient.PgTransaction
Commit the current transaction.
commit(Handler<AsyncResult<Void>>) - Method in interface io.reactiverse.pgclient.PgTransaction
Like PgTransaction.commit() with an handler to be notified when the transaction commit has completed
commit() - Method in class io.reactiverse.reactivex.pgclient.PgTransaction
Commit the current transaction.
commit(Handler<AsyncResult<Void>>) - Method in class io.reactiverse.reactivex.pgclient.PgTransaction
Like PgTransaction.commit() with an handler to be notified when the transaction commit has completed
commit() - Method in class io.reactiverse.rxjava.pgclient.PgTransaction
Commit the current transaction.
commit(Handler<AsyncResult<Void>>) - Method in class io.reactiverse.rxjava.pgclient.PgTransaction
Like PgTransaction.commit() with an handler to be notified when the transaction commit has completed
connect(Vertx, PgConnectOptions, Handler<AsyncResult<PgConnection>>) - Static method in interface io.reactiverse.pgclient.PgClient
Connects to the database and returns the connection if that succeeds.
connect(Vertx, Handler<AsyncResult<PgConnection>>) - Static method in interface io.reactiverse.pgclient.PgClient
Like PgClient.connect(Vertx, PgConnectOptions, Handler) with options build from the environment variables.
connect(Vertx, String, Handler<AsyncResult<PgConnection>>) - Static method in interface io.reactiverse.pgclient.PgClient
Like PgClient.connect(Vertx, PgConnectOptions, Handler) with options build from connectionUri.
connect(Handler<AsyncResult<Void>>) - Method in interface io.reactiverse.pgclient.pubsub.PgSubscriber
Connect the subscriber to Postgres.
connect(Vertx, PgConnectOptions, Handler<AsyncResult<PgConnection>>) - Static method in class io.reactiverse.reactivex.pgclient.PgClient
Connects to the database and returns the connection if that succeeds.
connect(Vertx, Handler<AsyncResult<PgConnection>>) - Static method in class io.reactiverse.reactivex.pgclient.PgClient
connect(Vertx, String, Handler<AsyncResult<PgConnection>>) - Static method in class io.reactiverse.reactivex.pgclient.PgClient
connect(Handler<AsyncResult<Void>>) - Method in class io.reactiverse.reactivex.pgclient.pubsub.PgSubscriber
Connect the subscriber to Postgres.
connect(Vertx, PgConnectOptions, Handler<AsyncResult<PgConnection>>) - Static method in class io.reactiverse.rxjava.pgclient.PgClient
Connects to the database and returns the connection if that succeeds.
connect(Vertx, Handler<AsyncResult<PgConnection>>) - Static method in class io.reactiverse.rxjava.pgclient.PgClient
connect(Vertx, String, Handler<AsyncResult<PgConnection>>) - Static method in class io.reactiverse.rxjava.pgclient.PgClient
connect(Handler<AsyncResult<Void>>) - Method in class io.reactiverse.rxjava.pgclient.pubsub.PgSubscriber
Connect the subscriber to Postgres.
create(Object) - Static method in interface io.reactiverse.pgclient.data.Json
 
create(Number) - Static method in class io.reactiverse.pgclient.data.Numeric
Return a Numeric instance for the given number.
create(Object) - Static method in class io.reactiverse.reactivex.pgclient.data.Json
 
create(Object) - Static method in class io.reactiverse.rxjava.pgclient.data.Json
 
createStream(int, Tuple) - Method in interface io.reactiverse.pgclient.PgPreparedQuery
Execute the prepared query with a cursor and createStream the result.
createStream(int, Tuple) - Method in class io.reactiverse.reactivex.pgclient.PgPreparedQuery
Execute the prepared query with a cursor and createStream the result.
createStream(int, Tuple) - Method in class io.reactiverse.rxjava.pgclient.PgPreparedQuery
Execute the prepared query with a cursor and createStream the result.
cursor() - Method in interface io.reactiverse.pgclient.PgPreparedQuery
 
cursor(Tuple) - Method in interface io.reactiverse.pgclient.PgPreparedQuery
Create a cursor with the provided arguments.
cursor() - Method in class io.reactiverse.reactivex.pgclient.PgPreparedQuery
 
cursor(Tuple) - Method in class io.reactiverse.reactivex.pgclient.PgPreparedQuery
Create a cursor with the provided arguments.
cursor() - Method in class io.reactiverse.rxjava.pgclient.PgPreparedQuery
 
cursor(Tuple) - Method in class io.reactiverse.rxjava.pgclient.PgPreparedQuery
Create a cursor with the provided arguments.

D

days(int) - Method in class io.reactiverse.pgclient.data.Interval
 
DEFAULT_CACHE_PREPARED_STATEMENTS - Static variable in class io.reactiverse.pgclient.PgConnectOptions
 
DEFAULT_DATABASE - Static variable in class io.reactiverse.pgclient.PgConnectOptions
 
DEFAULT_HOST - Static variable in class io.reactiverse.pgclient.PgConnectOptions
 
DEFAULT_MAX_SIZE - Static variable in class io.reactiverse.pgclient.PgPoolOptions
The default maximum number of connections a client will pool = 4
DEFAULT_MAX_WAIT_QUEUE_SIZE - Static variable in class io.reactiverse.pgclient.PgPoolOptions
Default max wait queue size = -1 (unbounded)
DEFAULT_PASSWORD - Static variable in class io.reactiverse.pgclient.PgConnectOptions
 
DEFAULT_PIPELINING_LIMIT - Static variable in class io.reactiverse.pgclient.PgConnectOptions
 
DEFAULT_PORT - Static variable in class io.reactiverse.pgclient.PgConnectOptions
 
DEFAULT_SSLMODE - Static variable in class io.reactiverse.pgclient.PgConnectOptions
 
DEFAULT_USER - Static variable in class io.reactiverse.pgclient.PgConnectOptions
 
doubleValue() - Method in class io.reactiverse.pgclient.data.Numeric
 

E

endHandler(Handler<Void>) - Method in interface io.reactiverse.pgclient.PgStream
 
endHandler(Handler<Void>) - Method in interface io.reactiverse.pgclient.pubsub.PgChannel
Set an handler to be called when no more notifications will be received.
endHandler(Handler<Void>) - Method in class io.reactiverse.reactivex.pgclient.PgStream
 
endHandler(Handler<Void>) - Method in class io.reactiverse.reactivex.pgclient.pubsub.PgChannel
Set an handler to be called when no more notifications will be received.
endHandler(Handler<Void>) - Method in class io.reactiverse.rxjava.pgclient.PgStream
 
endHandler(Handler<Void>) - Method in class io.reactiverse.rxjava.pgclient.pubsub.PgChannel
Set an handler to be called when no more notifications will be received.
equals(Object) - Method in class io.reactiverse.pgclient.data.Box
 
equals(Object) - Method in class io.reactiverse.pgclient.data.Circle
 
equals(Object) - Method in class io.reactiverse.pgclient.data.Interval
 
equals(Object) - Method in class io.reactiverse.pgclient.data.Line
 
equals(Object) - Method in class io.reactiverse.pgclient.data.LineSegment
 
equals(Object) - Method in class io.reactiverse.pgclient.data.Numeric
 
equals(Object) - Method in class io.reactiverse.pgclient.data.Path
 
equals(Object) - Method in class io.reactiverse.pgclient.data.Point
 
equals(Object) - Method in class io.reactiverse.pgclient.data.Polygon
 
equals(Object) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
equals(Object) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
equals(Object) - Method in class io.reactiverse.reactivex.pgclient.data.Json
 
equals(Object) - Method in class io.reactiverse.reactivex.pgclient.PgClient
 
equals(Object) - Method in class io.reactiverse.reactivex.pgclient.PgConnection
 
equals(Object) - Method in class io.reactiverse.reactivex.pgclient.PgCursor
 
equals(Object) - Method in class io.reactiverse.reactivex.pgclient.PgIterator
 
equals(Object) - Method in class io.reactiverse.reactivex.pgclient.PgPool
 
equals(Object) - Method in class io.reactiverse.reactivex.pgclient.PgPreparedQuery
 
equals(Object) - Method in class io.reactiverse.reactivex.pgclient.PgResult
 
equals(Object) - Method in class io.reactiverse.reactivex.pgclient.PgRowSet
 
equals(Object) - Method in class io.reactiverse.reactivex.pgclient.PgStream
 
equals(Object) - Method in class io.reactiverse.reactivex.pgclient.PgTransaction
 
equals(Object) - Method in class io.reactiverse.reactivex.pgclient.pubsub.PgChannel
 
equals(Object) - Method in class io.reactiverse.reactivex.pgclient.pubsub.PgSubscriber
 
equals(Object) - Method in class io.reactiverse.reactivex.pgclient.Row
 
equals(Object) - Method in class io.reactiverse.reactivex.pgclient.Tuple
 
equals(Object) - Method in class io.reactiverse.rxjava.pgclient.data.Json
 
equals(Object) - Method in class io.reactiverse.rxjava.pgclient.PgClient
 
equals(Object) - Method in class io.reactiverse.rxjava.pgclient.PgConnection
 
equals(Object) - Method in class io.reactiverse.rxjava.pgclient.PgCursor
 
equals(Object) - Method in class io.reactiverse.rxjava.pgclient.PgIterator
 
equals(Object) - Method in class io.reactiverse.rxjava.pgclient.PgPool
 
equals(Object) - Method in class io.reactiverse.rxjava.pgclient.PgPreparedQuery
 
equals(Object) - Method in class io.reactiverse.rxjava.pgclient.PgResult
 
equals(Object) - Method in class io.reactiverse.rxjava.pgclient.PgRowSet
 
equals(Object) - Method in class io.reactiverse.rxjava.pgclient.PgStream
 
equals(Object) - Method in class io.reactiverse.rxjava.pgclient.PgTransaction
 
equals(Object) - Method in class io.reactiverse.rxjava.pgclient.pubsub.PgChannel
 
equals(Object) - Method in class io.reactiverse.rxjava.pgclient.pubsub.PgSubscriber
 
equals(Object) - Method in class io.reactiverse.rxjava.pgclient.Row
 
equals(Object) - Method in class io.reactiverse.rxjava.pgclient.Tuple
 
exceptionHandler(Handler<Throwable>) - Method in interface io.reactiverse.pgclient.PgConnection
Set an handler called with connection errors.
exceptionHandler(Handler<Throwable>) - Method in interface io.reactiverse.pgclient.PgStream
 
exceptionHandler(Handler<Throwable>) - Method in interface io.reactiverse.pgclient.pubsub.PgChannel
 
exceptionHandler(Handler<Throwable>) - Method in class io.reactiverse.reactivex.pgclient.PgConnection
Set an handler called with connection errors.
exceptionHandler(Handler<Throwable>) - Method in class io.reactiverse.reactivex.pgclient.PgStream
 
exceptionHandler(Handler<Throwable>) - Method in class io.reactiverse.reactivex.pgclient.pubsub.PgChannel
 
exceptionHandler(Handler<Throwable>) - Method in class io.reactiverse.rxjava.pgclient.PgConnection
Set an handler called with connection errors.
exceptionHandler(Handler<Throwable>) - Method in class io.reactiverse.rxjava.pgclient.PgStream
 
exceptionHandler(Handler<Throwable>) - Method in class io.reactiverse.rxjava.pgclient.pubsub.PgChannel
 
execute(Handler<AsyncResult<PgRowSet>>) - Method in interface io.reactiverse.pgclient.PgPreparedQuery
Calls PgPreparedQuery.execute(Tuple, Handler) with an empty tuple argument.
execute(Collector<Row, ?, R>, Handler<AsyncResult<PgResult<R>>>) - Method in interface io.reactiverse.pgclient.PgPreparedQuery
Calls PgPreparedQuery.execute(Tuple, Collector, Handler) with an empty tuple argument.
execute(Tuple, Handler<AsyncResult<PgRowSet>>) - Method in interface io.reactiverse.pgclient.PgPreparedQuery
Create a cursor with the provided arguments.
execute(Tuple, Collector<Row, ?, R>, Handler<AsyncResult<PgResult<R>>>) - Method in interface io.reactiverse.pgclient.PgPreparedQuery
Create a cursor with the provided arguments.
execute(Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.reactivex.pgclient.PgPreparedQuery
execute(Tuple, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.reactivex.pgclient.PgPreparedQuery
Create a cursor with the provided arguments.
execute(Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.rxjava.pgclient.PgPreparedQuery
execute(Tuple, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.rxjava.pgclient.PgPreparedQuery
Create a cursor with the provided arguments.

F

fetch(long) - Method in class io.reactiverse.reactivex.pgclient.PgStream
 
fetch(long) - Method in class io.reactiverse.reactivex.pgclient.pubsub.PgChannel
 
fetch(long) - Method in class io.reactiverse.rxjava.pgclient.PgStream
 
fetch(long) - Method in class io.reactiverse.rxjava.pgclient.pubsub.PgChannel
 
floatValue() - Method in class io.reactiverse.pgclient.data.Numeric
 
fromEnv() - Static method in class io.reactiverse.pgclient.PgConnectOptions
Provide a PgConnectOptions configured with environment variables, if the environment variable is not set, then a default value will take precedence over this.
fromEnv() - Static method in class io.reactiverse.pgclient.PgPoolOptions
Provide a PgPoolOptions configured with environment variables, if the environment variable is not set, then a default value will take precedence over this.
fromJson(Iterable<Map.Entry<String, Object>>, Box) - Static method in class io.reactiverse.pgclient.data.BoxConverter
 
fromJson(Iterable<Map.Entry<String, Object>>, Circle) - Static method in class io.reactiverse.pgclient.data.CircleConverter
 
fromJson(Iterable<Map.Entry<String, Object>>, Interval) - Static method in class io.reactiverse.pgclient.data.IntervalConverter
 
fromJson(Iterable<Map.Entry<String, Object>>, Line) - Static method in class io.reactiverse.pgclient.data.LineConverter
 
fromJson(Iterable<Map.Entry<String, Object>>, LineSegment) - Static method in class io.reactiverse.pgclient.data.LineSegmentConverter
 
fromJson(Iterable<Map.Entry<String, Object>>, Path) - Static method in class io.reactiverse.pgclient.data.PathConverter
 
fromJson(Iterable<Map.Entry<String, Object>>, Point) - Static method in class io.reactiverse.pgclient.data.PointConverter
 
fromJson(Iterable<Map.Entry<String, Object>>, Polygon) - Static method in class io.reactiverse.pgclient.data.PolygonConverter
 
fromJson(Iterable<Map.Entry<String, Object>>, PgConnectOptions) - Static method in class io.reactiverse.pgclient.PgConnectOptionsConverter
 
fromJson(Iterable<Map.Entry<String, Object>>, PgNotification) - Static method in class io.reactiverse.pgclient.PgNotificationConverter
 
fromJson(Iterable<Map.Entry<String, Object>>, PgPoolOptions) - Static method in class io.reactiverse.pgclient.PgPoolOptionsConverter
 
fromUri(String) - Static method in class io.reactiverse.pgclient.PgConnectOptions
Provide a PgConnectOptions configured from a connection URI.
fromUri(String) - Static method in class io.reactiverse.pgclient.PgPoolOptions
Provide a PgPoolOptions configured from a connection URI.

G

getA() - Method in class io.reactiverse.pgclient.data.Line
 
getB() - Method in class io.reactiverse.pgclient.data.Line
 
getBigDecimal(String) - Method in interface io.reactiverse.pgclient.Row
Get BigDecimal value at pos.
getBigDecimal(int) - Method in interface io.reactiverse.pgclient.Tuple
Get BigDecimal value at pos.
getBigDecimal(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get value at pos.
getBigDecimal(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get value at pos.
getBigDecimal(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get value at pos.
getBigDecimal(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get value at pos.
getBoolean(String) - Method in interface io.reactiverse.pgclient.Row
Get a boolean value at pos.
getBoolean(int) - Method in interface io.reactiverse.pgclient.Tuple
Get a boolean value at pos.
getBoolean(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get a boolean value at pos.
getBoolean(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get a boolean value at pos.
getBoolean(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get a boolean value at pos.
getBoolean(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get a boolean value at pos.
getBooleanArray(String) - Method in interface io.reactiverse.pgclient.Row
Get an array of Boolean value at pos.
getBooleanArray(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an array of Boolean value at pos.
getBooleanArray(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get an array of Boolean value at pos.
getBooleanArray(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get an array of Boolean value at pos.
getBooleanArray(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get an array of Boolean value at pos.
getBooleanArray(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get an array of Boolean value at pos.
getBox(String) - Method in interface io.reactiverse.pgclient.Row
Get Box value at pos.
getBox(int) - Method in interface io.reactiverse.pgclient.Tuple
Get Box value at pos.
getBox(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get value at pos.
getBox(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get value at pos.
getBox(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get value at pos.
getBox(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get value at pos.
getBoxArray(String) - Method in interface io.reactiverse.pgclient.Row
Get an array of Box value at pos.
getBoxArray(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an array of Box value at pos.
getBoxArray(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get an array of value at pos.
getBoxArray(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get an array of value at pos.
getBoxArray(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get an array of value at pos.
getBoxArray(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get an array of value at pos.
getBuffer(String) - Method in interface io.reactiverse.pgclient.Row
Get a buffer value at pos.
getBuffer(int) - Method in interface io.reactiverse.pgclient.Tuple
Get a buffer value at pos.
getBuffer(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get a buffer value at pos.
getBuffer(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get a buffer value at pos.
getBuffer(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get a buffer value at pos.
getBuffer(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get a buffer value at pos.
getBufferArray(String) - Method in interface io.reactiverse.pgclient.Row
Get an array of Buffer value at pos.
getBufferArray(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an array of Buffer value at pos.
getC() - Method in class io.reactiverse.pgclient.data.Line
 
getCachePreparedStatements() - Method in class io.reactiverse.pgclient.PgConnectOptions
 
getCenterPoint() - Method in class io.reactiverse.pgclient.data.Circle
 
getChannel() - Method in class io.reactiverse.pgclient.PgNotification
 
getCircle(String) - Method in interface io.reactiverse.pgclient.Row
Get Circle value at pos.
getCircle(int) - Method in interface io.reactiverse.pgclient.Tuple
Get Circle value at pos.
getCircle(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get value at pos.
getCircle(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get value at pos.
getCircle(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get value at pos.
getCircle(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get value at pos.
getCircleArray(String) - Method in interface io.reactiverse.pgclient.Row
Get an array of Circle value at pos.
getCircleArray(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an array of Circle value at pos.
getCircleArray(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get an array of value at pos.
getCircleArray(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get an array of value at pos.
getCircleArray(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get an array of value at pos.
getCircleArray(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get an array of value at pos.
getCode() - Method in exception io.reactiverse.pgclient.PgException
 
getColumnName(int) - Method in interface io.reactiverse.pgclient.Row
Get a column name at pos.
getColumnName(int) - Method in class io.reactiverse.reactivex.pgclient.Row
Get a column name at pos.
getColumnName(int) - Method in class io.reactiverse.rxjava.pgclient.Row
Get a column name at pos.
getConnection(Handler<AsyncResult<PgConnection>>) - Method in interface io.reactiverse.pgclient.PgPool
Get a connection from the pool.
getConnection(Handler<AsyncResult<PgConnection>>) - Method in class io.reactiverse.reactivex.pgclient.PgPool
Get a connection from the pool.
getConnection(Handler<AsyncResult<PgConnection>>) - Method in class io.reactiverse.rxjava.pgclient.PgPool
Get a connection from the pool.
getDatabase() - Method in class io.reactiverse.pgclient.PgConnectOptions
 
getDays() - Method in class io.reactiverse.pgclient.data.Interval
 
getDelegate() - Method in class io.reactiverse.reactivex.pgclient.data.Json
 
getDelegate() - Method in class io.reactiverse.reactivex.pgclient.PgClient
 
getDelegate() - Method in class io.reactiverse.reactivex.pgclient.PgConnection
 
getDelegate() - Method in class io.reactiverse.reactivex.pgclient.PgCursor
 
getDelegate() - Method in class io.reactiverse.reactivex.pgclient.PgIterator
 
getDelegate() - Method in class io.reactiverse.reactivex.pgclient.PgPool
 
getDelegate() - Method in class io.reactiverse.reactivex.pgclient.PgPreparedQuery
 
getDelegate() - Method in class io.reactiverse.reactivex.pgclient.PgResult
 
getDelegate() - Method in class io.reactiverse.reactivex.pgclient.PgRowSet
 
getDelegate() - Method in class io.reactiverse.reactivex.pgclient.PgStream
 
getDelegate() - Method in class io.reactiverse.reactivex.pgclient.PgTransaction
 
getDelegate() - Method in class io.reactiverse.reactivex.pgclient.pubsub.PgChannel
 
getDelegate() - Method in class io.reactiverse.reactivex.pgclient.pubsub.PgSubscriber
 
getDelegate() - Method in class io.reactiverse.reactivex.pgclient.Row
 
getDelegate() - Method in class io.reactiverse.reactivex.pgclient.Tuple
 
getDelegate() - Method in class io.reactiverse.rxjava.pgclient.data.Json
 
getDelegate() - Method in class io.reactiverse.rxjava.pgclient.PgClient
 
getDelegate() - Method in class io.reactiverse.rxjava.pgclient.PgConnection
 
getDelegate() - Method in class io.reactiverse.rxjava.pgclient.PgCursor
 
getDelegate() - Method in class io.reactiverse.rxjava.pgclient.PgIterator
 
getDelegate() - Method in class io.reactiverse.rxjava.pgclient.PgPool
 
getDelegate() - Method in class io.reactiverse.rxjava.pgclient.PgPreparedQuery
 
getDelegate() - Method in class io.reactiverse.rxjava.pgclient.PgResult
 
getDelegate() - Method in class io.reactiverse.rxjava.pgclient.PgRowSet
 
getDelegate() - Method in class io.reactiverse.rxjava.pgclient.PgStream
 
getDelegate() - Method in class io.reactiverse.rxjava.pgclient.PgTransaction
 
getDelegate() - Method in class io.reactiverse.rxjava.pgclient.pubsub.PgChannel
 
getDelegate() - Method in class io.reactiverse.rxjava.pgclient.pubsub.PgSubscriber
 
getDelegate() - Method in class io.reactiverse.rxjava.pgclient.Row
 
getDelegate() - Method in class io.reactiverse.rxjava.pgclient.Tuple
 
getDetail() - Method in exception io.reactiverse.pgclient.PgException
 
getDouble(String) - Method in interface io.reactiverse.pgclient.Row
Get a double value at pos.
getDouble(int) - Method in interface io.reactiverse.pgclient.Tuple
Get a double value at pos.
getDouble(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get a double value at pos.
getDouble(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get a double value at pos.
getDouble(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get a double value at pos.
getDouble(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get a double value at pos.
getDoubleArray(String) - Method in interface io.reactiverse.pgclient.Row
Get an array of Double value at pos.
getDoubleArray(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an array of Double value at pos.
getDoubleArray(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get an array of Double value at pos.
getDoubleArray(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get an array of Double value at pos.
getDoubleArray(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get an array of Double value at pos.
getDoubleArray(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get an array of Double value at pos.
getFloat(String) - Method in interface io.reactiverse.pgclient.Row
Get a float value at pos.
getFloat(int) - Method in interface io.reactiverse.pgclient.Tuple
Get a float value at pos.
getFloat(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get a float value at pos.
getFloat(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get a float value at pos.
getFloat(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get a float value at pos.
getFloat(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get a float value at pos.
getFloatArray(String) - Method in interface io.reactiverse.pgclient.Row
Get an array of Float value at pos.
getFloatArray(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an array of Float value at pos.
getFloatArray(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get an array of Float value at pos.
getFloatArray(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get an array of Float value at pos.
getFloatArray(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get an array of Float value at pos.
getFloatArray(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get an array of Float value at pos.
getHost() - Method in class io.reactiverse.pgclient.PgConnectOptions
 
getHours() - Method in class io.reactiverse.pgclient.data.Interval
 
getInteger(String) - Method in interface io.reactiverse.pgclient.Row
Get an integer value at pos.
getInteger(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an integer value at pos.
getInteger(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get an integer value at pos.
getInteger(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get an integer value at pos.
getInteger(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get an integer value at pos.
getInteger(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get an integer value at pos.
getIntegerArray(String) - Method in interface io.reactiverse.pgclient.Row
Get an array of Integer value at pos.
getIntegerArray(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an array of Integer value at pos.
getIntegerArray(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get an array of Integer value at pos.
getIntegerArray(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get an array of Integer value at pos.
getIntegerArray(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get an array of Integer value at pos.
getIntegerArray(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get an array of Integer value at pos.
getInterval(String) - Method in interface io.reactiverse.pgclient.Row
Get Interval value at pos.
getInterval(int) - Method in interface io.reactiverse.pgclient.Tuple
Get Interval value at pos.
getInterval(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get value at pos.
getInterval(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get value at pos.
getInterval(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get value at pos.
getInterval(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get value at pos.
getIntervalArray(String) - Method in interface io.reactiverse.pgclient.Row
Get an array of Interval value at pos.
getIntervalArray(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an array of Interval value at pos.
getIntervalArray(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get an array of value at pos.
getIntervalArray(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get an array of value at pos.
getIntervalArray(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get an array of value at pos.
getIntervalArray(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get an array of value at pos.
getJson(String) - Method in interface io.reactiverse.pgclient.Row
Get a json value at pos.
getJson(int) - Method in interface io.reactiverse.pgclient.Tuple
Get a json value at pos.
getJson(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get a json value at pos.
getJson(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get a json value at pos.
getJson(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get a json value at pos.
getJson(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get a json value at pos.
getJsonArray(String) - Method in interface io.reactiverse.pgclient.Row
Get an array of Json value at pos.
getJsonArray(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an array of Json value at pos.
getLine(String) - Method in interface io.reactiverse.pgclient.Row
Get Line value at pos.
getLine(int) - Method in interface io.reactiverse.pgclient.Tuple
Get Line value at pos.
getLine(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get value at pos.
getLine(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get value at pos.
getLine(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get value at pos.
getLine(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get value at pos.
getLineArray(String) - Method in interface io.reactiverse.pgclient.Row
Get an array of Line value at pos.
getLineArray(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an array of Line value at pos.
getLineArray(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get an array of value at pos.
getLineArray(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get an array of value at pos.
getLineArray(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get an array of value at pos.
getLineArray(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get an array of value at pos.
getLineSegment(String) - Method in interface io.reactiverse.pgclient.Row
Get LineSegment value at pos.
getLineSegment(int) - Method in interface io.reactiverse.pgclient.Tuple
Get LineSegment value at pos.
getLineSegment(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get value at pos.
getLineSegment(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get value at pos.
getLineSegment(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get value at pos.
getLineSegment(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get value at pos.
getLineSegmentArray(String) - Method in interface io.reactiverse.pgclient.Row
Get an array of LineSegment value at pos.
getLineSegmentArray(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an array of LineSegment value at pos.
getLineSegmentArray(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get an array of value at pos.
getLineSegmentArray(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get an array of value at pos.
getLineSegmentArray(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get an array of value at pos.
getLineSegmentArray(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get an array of value at pos.
getLocalDate(String) - Method in interface io.reactiverse.pgclient.Row
Get LocalDate value at pos.
getLocalDate(int) - Method in interface io.reactiverse.pgclient.Tuple
Get LocalDate value at pos.
getLocalDate(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get LocalDate value at pos.
getLocalDate(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get LocalDate value at pos.
getLocalDate(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get LocalDate value at pos.
getLocalDate(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get LocalDate value at pos.
getLocalDateArray(String) - Method in interface io.reactiverse.pgclient.Row
Get an array of LocalDate value at pos.
getLocalDateArray(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an array of LocalDate value at pos.
getLocalDateArray(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get an array of value at pos.
getLocalDateArray(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get an array of value at pos.
getLocalDateArray(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get an array of value at pos.
getLocalDateArray(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get an array of value at pos.
getLocalDateTime(String) - Method in interface io.reactiverse.pgclient.Row
Get LocalDateTime value at pos.
getLocalDateTime(int) - Method in interface io.reactiverse.pgclient.Tuple
Get LocalDateTime value at pos.
getLocalDateTime(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get LocalDateTime value at pos.
getLocalDateTime(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get LocalDateTime value at pos.
getLocalDateTime(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get LocalDateTime value at pos.
getLocalDateTime(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get LocalDateTime value at pos.
getLocalDateTimeArray(String) - Method in interface io.reactiverse.pgclient.Row
Get an array of LocalDateTime value at pos.
getLocalDateTimeArray(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an array of LocalDateTime value at pos.
getLocalDateTimeArray(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get an array of value at pos.
getLocalDateTimeArray(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get an array of value at pos.
getLocalDateTimeArray(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get an array of value at pos.
getLocalDateTimeArray(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get an array of value at pos.
getLocalTime(String) - Method in interface io.reactiverse.pgclient.Row
Get LocalTime value at pos.
getLocalTime(int) - Method in interface io.reactiverse.pgclient.Tuple
Get LocalTime value at pos.
getLocalTime(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get LocalTime value at pos.
getLocalTime(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get LocalTime value at pos.
getLocalTime(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get LocalTime value at pos.
getLocalTime(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get LocalTime value at pos.
getLocalTimeArray(String) - Method in interface io.reactiverse.pgclient.Row
Get an array of LocalTime value at pos.
getLocalTimeArray(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an array of LocalTime value at pos.
getLocalTimeArray(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get an array of value at pos.
getLocalTimeArray(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get an array of value at pos.
getLocalTimeArray(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get an array of value at pos.
getLocalTimeArray(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get an array of value at pos.
getLong(String) - Method in interface io.reactiverse.pgclient.Row
Get a long value at pos.
getLong(int) - Method in interface io.reactiverse.pgclient.Tuple
Get a long value at pos.
getLong(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get a long value at pos.
getLong(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get a long value at pos.
getLong(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get a long value at pos.
getLong(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get a long value at pos.
getLongArray(String) - Method in interface io.reactiverse.pgclient.Row
Get an array of Long value at pos.
getLongArray(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an array of Long value at pos.
getLongArray(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get an array of Long value at pos.
getLongArray(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get an array of Long value at pos.
getLongArray(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get an array of Long value at pos.
getLongArray(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get an array of Long value at pos.
getLowerLeftCorner() - Method in class io.reactiverse.pgclient.data.Box
 
getMaxSize() - Method in class io.reactiverse.pgclient.PgPoolOptions
 
getMaxWaitQueueSize() - Method in class io.reactiverse.pgclient.PgPoolOptions
 
getMicroseconds() - Method in class io.reactiverse.pgclient.data.Interval
 
getMinutes() - Method in class io.reactiverse.pgclient.data.Interval
 
getMonths() - Method in class io.reactiverse.pgclient.data.Interval
 
getNumeric(String) - Method in interface io.reactiverse.pgclient.Row
Get Numeric value at pos.
getNumeric(int) - Method in interface io.reactiverse.pgclient.Tuple
Get Numeric value at pos.
getNumeric(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get value at pos.
getNumeric(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get value at pos.
getNumeric(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get value at pos.
getNumeric(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get value at pos.
getNumericArray(String) - Method in interface io.reactiverse.pgclient.Row
Get an array of Numeric value at pos.
getNumericArray(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an array of Numeric value at pos.
getNumericArray(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get an array of value at pos.
getNumericArray(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get an array of value at pos.
getNumericArray(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get an array of value at pos.
getNumericArray(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get an array of value at pos.
getOffsetDateTime(String) - Method in interface io.reactiverse.pgclient.Row
Get OffsetDateTime value at pos.
getOffsetDateTime(int) - Method in interface io.reactiverse.pgclient.Tuple
Get OffsetDateTime value at pos.
getOffsetDateTime(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get OffsetDateTime value at pos.
getOffsetDateTime(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get OffsetDateTime value at pos.
getOffsetDateTime(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get OffsetDateTime value at pos.
getOffsetDateTime(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get OffsetDateTime value at pos.
getOffsetDateTimeArray(String) - Method in interface io.reactiverse.pgclient.Row
Get an array of OffsetDateTime value at pos.
getOffsetDateTimeArray(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an array of OffsetDateTime value at pos.
getOffsetDateTimeArray(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get an array of value at pos.
getOffsetDateTimeArray(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get an array of value at pos.
getOffsetDateTimeArray(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get an array of value at pos.
getOffsetDateTimeArray(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get an array of value at pos.
getOffsetTime(String) - Method in interface io.reactiverse.pgclient.Row
Get OffsetTime value at pos.
getOffsetTime(int) - Method in interface io.reactiverse.pgclient.Tuple
Get OffsetTime value at pos.
getOffsetTime(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get OffsetTime value at pos.
getOffsetTime(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get OffsetTime value at pos.
getOffsetTime(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get OffsetTime value at pos.
getOffsetTime(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get OffsetTime value at pos.
getOffsetTimeArray(String) - Method in interface io.reactiverse.pgclient.Row
Get an array of OffsetTime value at pos.
getOffsetTimeArray(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an array of OffsetTime value at pos.
getOffsetTimeArray(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get an array of value at pos.
getOffsetTimeArray(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get an array of value at pos.
getOffsetTimeArray(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get an array of value at pos.
getOffsetTimeArray(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get an array of value at pos.
getP1() - Method in class io.reactiverse.pgclient.data.LineSegment
 
getP2() - Method in class io.reactiverse.pgclient.data.LineSegment
 
getPassword() - Method in class io.reactiverse.pgclient.PgConnectOptions
 
getPath(String) - Method in interface io.reactiverse.pgclient.Row
Get Path value at pos.
getPath(int) - Method in interface io.reactiverse.pgclient.Tuple
Get Path value at pos.
getPath(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get value at pos.
getPath(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get value at pos.
getPath(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get value at pos.
getPath(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get value at pos.
getPathArray(String) - Method in interface io.reactiverse.pgclient.Row
Get an array of Path value at pos.
getPathArray(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an array of Path value at pos.
getPathArray(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get an array of value at pos.
getPathArray(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get an array of value at pos.
getPathArray(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get an array of value at pos.
getPathArray(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get an array of value at pos.
getPayload() - Method in class io.reactiverse.pgclient.PgNotification
 
getPipeliningLimit() - Method in class io.reactiverse.pgclient.PgConnectOptions
 
getPoint(String) - Method in interface io.reactiverse.pgclient.Row
Get Point value at pos.
getPoint(int) - Method in interface io.reactiverse.pgclient.Tuple
Get Point value at pos.
getPoint(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get value at pos.
getPoint(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get value at pos.
getPoint(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get value at pos.
getPoint(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get value at pos.
getPointArray(String) - Method in interface io.reactiverse.pgclient.Row
Get an array of Point value at pos.
getPointArray(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an array of Point value at pos.
getPointArray(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get an array of value at pos.
getPointArray(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get an array of value at pos.
getPointArray(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get an array of value at pos.
getPointArray(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get an array of value at pos.
getPoints() - Method in class io.reactiverse.pgclient.data.Path
 
getPoints() - Method in class io.reactiverse.pgclient.data.Polygon
 
getPolygon(String) - Method in interface io.reactiverse.pgclient.Row
Get Polygon value at pos.
getPolygon(int) - Method in interface io.reactiverse.pgclient.Tuple
Get Polygon value at pos.
getPolygon(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get value at pos.
getPolygon(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get value at pos.
getPolygon(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get value at pos.
getPolygon(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get value at pos.
getPolygonArray(String) - Method in interface io.reactiverse.pgclient.Row
Get an array of Polygon value at pos.
getPolygonArray(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an array of Polygon value at pos.
getPolygonArray(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get an array of value at pos.
getPolygonArray(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get an array of value at pos.
getPolygonArray(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get an array of value at pos.
getPolygonArray(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get an array of value at pos.
getPort() - Method in class io.reactiverse.pgclient.PgConnectOptions
 
getProcessId() - Method in class io.reactiverse.pgclient.PgNotification
 
getRadius() - Method in class io.reactiverse.pgclient.data.Circle
 
getSeconds() - Method in class io.reactiverse.pgclient.data.Interval
 
getSeverity() - Method in exception io.reactiverse.pgclient.PgException
 
getShort(String) - Method in interface io.reactiverse.pgclient.Row
Get a short value at pos.
getShort(int) - Method in interface io.reactiverse.pgclient.Tuple
Get a short value at pos.
getShort(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get a short value at pos.
getShort(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get a short value at pos.
getShort(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get a short value at pos.
getShort(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get a short value at pos.
getShortArray(String) - Method in interface io.reactiverse.pgclient.Row
Get an array of Short value at pos.
getShortArray(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an array of Short value at pos.
getShortArray(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get an array of Short value at pos.
getShortArray(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get an array of Short value at pos.
getShortArray(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get an array of Short value at pos.
getShortArray(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get an array of Short value at pos.
getSslMode() - Method in class io.reactiverse.pgclient.PgConnectOptions
 
getString(String) - Method in interface io.reactiverse.pgclient.Row
Get a string value at pos.
getString(int) - Method in interface io.reactiverse.pgclient.Tuple
Get a string value at pos.
getString(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get a string value at pos.
getString(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get a string value at pos.
getString(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get a string value at pos.
getString(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get a string value at pos.
getStringArray(String) - Method in interface io.reactiverse.pgclient.Row
Get an array of String value at pos.
getStringArray(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an array of String value at pos.
getStringArray(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get an array of String value at pos.
getStringArray(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get an array of String value at pos.
getStringArray(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get an array of String value at pos.
getStringArray(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get an array of String value at pos.
getTemporal(String) - Method in interface io.reactiverse.pgclient.Row
Get a temporal value at pos.
getTemporal(int) - Method in interface io.reactiverse.pgclient.Tuple
Get a Temporal value at pos.
getTemporal(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get a temporal value at pos.
getTemporal(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get a Temporal value at pos.
getTemporal(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get a temporal value at pos.
getTemporal(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get a Temporal value at pos.
getUpperRightCorner() - Method in class io.reactiverse.pgclient.data.Box
 
getUser() - Method in class io.reactiverse.pgclient.PgConnectOptions
 
getUUID(String) - Method in interface io.reactiverse.pgclient.Row
Get UUID value at pos.
getUUID(int) - Method in interface io.reactiverse.pgclient.Tuple
Get UUID value at pos.
getUUID(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get UUID value at pos.
getUUID(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get UUID value at pos.
getUUID(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get UUID value at pos.
getUUID(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get UUID value at pos.
getUUIDArray(String) - Method in interface io.reactiverse.pgclient.Row
Get an array of UUID value at pos.
getUUIDArray(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an array of UUID value at pos.
getUUIDArray(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get an array of value at pos.
getUUIDArray(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get an array of value at pos.
getUUIDArray(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get an array of value at pos.
getUUIDArray(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get an array of value at pos.
getValue(String) - Method in interface io.reactiverse.pgclient.Row
Get an object value at pos.
getValue(int) - Method in interface io.reactiverse.pgclient.Tuple
Get an object value at pos.
getValue(String) - Method in class io.reactiverse.reactivex.pgclient.Row
Get an object value at pos.
getValue(int) - Method in class io.reactiverse.reactivex.pgclient.Tuple
Get an object value at pos.
getValue(String) - Method in class io.reactiverse.rxjava.pgclient.Row
Get an object value at pos.
getValue(int) - Method in class io.reactiverse.rxjava.pgclient.Tuple
Get an object value at pos.
getX() - Method in class io.reactiverse.pgclient.data.Point
 
getY() - Method in class io.reactiverse.pgclient.data.Point
 
getYears() - Method in class io.reactiverse.pgclient.data.Interval
 

H

handler(Handler<T>) - Method in interface io.reactiverse.pgclient.PgStream
 
handler(Handler<String>) - Method in interface io.reactiverse.pgclient.pubsub.PgChannel
Set or unset an handler to be called when a the channel is notified by Postgres.
handler(Handler<T>) - Method in class io.reactiverse.reactivex.pgclient.PgStream
 
handler(Handler<String>) - Method in class io.reactiverse.reactivex.pgclient.pubsub.PgChannel
Set or unset an handler to be called when a the channel is notified by Postgres.
handler(Handler<T>) - Method in class io.reactiverse.rxjava.pgclient.PgStream
 
handler(Handler<String>) - Method in class io.reactiverse.rxjava.pgclient.pubsub.PgChannel
Set or unset an handler to be called when a the channel is notified by Postgres.
hashCode() - Method in class io.reactiverse.pgclient.data.Box
 
hashCode() - Method in class io.reactiverse.pgclient.data.Circle
 
hashCode() - Method in class io.reactiverse.pgclient.data.Interval
 
hashCode() - Method in class io.reactiverse.pgclient.data.Line
 
hashCode() - Method in class io.reactiverse.pgclient.data.LineSegment
 
hashCode() - Method in class io.reactiverse.pgclient.data.Numeric
 
hashCode() - Method in class io.reactiverse.pgclient.data.Path
 
hashCode() - Method in class io.reactiverse.pgclient.data.Polygon
 
hashCode() - Method in class io.reactiverse.pgclient.PgConnectOptions
 
hashCode() - Method in class io.reactiverse.pgclient.PgPoolOptions
 
hashCode() - Method in class io.reactiverse.reactivex.pgclient.data.Json
 
hashCode() - Method in class io.reactiverse.reactivex.pgclient.PgClient
 
hashCode() - Method in class io.reactiverse.reactivex.pgclient.PgConnection
 
hashCode() - Method in class io.reactiverse.reactivex.pgclient.PgCursor
 
hashCode() - Method in class io.reactiverse.reactivex.pgclient.PgIterator
 
hashCode() - Method in class io.reactiverse.reactivex.pgclient.PgPool
 
hashCode() - Method in class io.reactiverse.reactivex.pgclient.PgPreparedQuery
 
hashCode() - Method in class io.reactiverse.reactivex.pgclient.PgResult
 
hashCode() - Method in class io.reactiverse.reactivex.pgclient.PgRowSet
 
hashCode() - Method in class io.reactiverse.reactivex.pgclient.PgStream
 
hashCode() - Method in class io.reactiverse.reactivex.pgclient.PgTransaction
 
hashCode() - Method in class io.reactiverse.reactivex.pgclient.pubsub.PgChannel
 
hashCode() - Method in class io.reactiverse.reactivex.pgclient.pubsub.PgSubscriber
 
hashCode() - Method in class io.reactiverse.reactivex.pgclient.Row
 
hashCode() - Method in class io.reactiverse.reactivex.pgclient.Tuple
 
hashCode() - Method in class io.reactiverse.rxjava.pgclient.data.Json
 
hashCode() - Method in class io.reactiverse.rxjava.pgclient.PgClient
 
hashCode() - Method in class io.reactiverse.rxjava.pgclient.PgConnection
 
hashCode() - Method in class io.reactiverse.rxjava.pgclient.PgCursor
 
hashCode() - Method in class io.reactiverse.rxjava.pgclient.PgIterator
 
hashCode() - Method in class io.reactiverse.rxjava.pgclient.PgPool
 
hashCode() - Method in class io.reactiverse.rxjava.pgclient.PgPreparedQuery
 
hashCode() - Method in class io.reactiverse.rxjava.pgclient.PgResult
 
hashCode() - Method in class io.reactiverse.rxjava.pgclient.PgRowSet
 
hashCode() - Method in class io.reactiverse.rxjava.pgclient.PgStream
 
hashCode() - Method in class io.reactiverse.rxjava.pgclient.PgTransaction
 
hashCode() - Method in class io.reactiverse.rxjava.pgclient.pubsub.PgChannel
 
hashCode() - Method in class io.reactiverse.rxjava.pgclient.pubsub.PgSubscriber
 
hashCode() - Method in class io.reactiverse.rxjava.pgclient.Row
 
hashCode() - Method in class io.reactiverse.rxjava.pgclient.Tuple
 
hasMore() - Method in interface io.reactiverse.pgclient.PgCursor
Returns true when the cursor has results in progress and the #execute should be called to retrieve them.
hasMore() - Method in class io.reactiverse.reactivex.pgclient.PgCursor
Returns true when the cursor has results in progress and the should be called to retrieve them.
hasMore() - Method in class io.reactiverse.rxjava.pgclient.PgCursor
Returns true when the cursor has results in progress and the should be called to retrieve them.
hasNext() - Method in interface io.reactiverse.pgclient.PgIterator
 
hasNext() - Method in class io.reactiverse.reactivex.pgclient.PgIterator
 
hasNext() - Method in class io.reactiverse.rxjava.pgclient.PgIterator
 
hours(int) - Method in class io.reactiverse.pgclient.data.Interval
 

I

Interval - Class in io.reactiverse.pgclient.data
Postgres Interval is date and time based such as 120 years 3 months 332 days 20 hours 20 minutes 20.999999 seconds
Interval() - Constructor for class io.reactiverse.pgclient.data.Interval
 
Interval(int, int, int, int, int, int, int) - Constructor for class io.reactiverse.pgclient.data.Interval
 
Interval(int, int, int, int, int, int) - Constructor for class io.reactiverse.pgclient.data.Interval
 
Interval(int, int, int, int, int) - Constructor for class io.reactiverse.pgclient.data.Interval
 
Interval(int, int, int, int) - Constructor for class io.reactiverse.pgclient.data.Interval
 
Interval(int, int, int) - Constructor for class io.reactiverse.pgclient.data.Interval
 
Interval(int, int) - Constructor for class io.reactiverse.pgclient.data.Interval
 
Interval(int) - Constructor for class io.reactiverse.pgclient.data.Interval
 
Interval(JsonObject) - Constructor for class io.reactiverse.pgclient.data.Interval
 
IntervalConverter - Class in io.reactiverse.pgclient.data
Converter for Interval.
IntervalConverter() - Constructor for class io.reactiverse.pgclient.data.IntervalConverter
 
intValue() - Method in class io.reactiverse.pgclient.data.Numeric
 
io.reactiverse.pgclient - package io.reactiverse.pgclient
 
io.reactiverse.pgclient.data - package io.reactiverse.pgclient.data
 
io.reactiverse.pgclient.pubsub - package io.reactiverse.pgclient.pubsub
 
io.reactiverse.reactivex.pgclient - package io.reactiverse.reactivex.pgclient
 
io.reactiverse.reactivex.pgclient.data - package io.reactiverse.reactivex.pgclient.data
 
io.reactiverse.reactivex.pgclient.pubsub - package io.reactiverse.reactivex.pgclient.pubsub
 
io.reactiverse.rxjava.pgclient - package io.reactiverse.rxjava.pgclient
 
io.reactiverse.rxjava.pgclient.data - package io.reactiverse.rxjava.pgclient.data
 
io.reactiverse.rxjava.pgclient.pubsub - package io.reactiverse.rxjava.pgclient.pubsub
 
isNaN() - Method in class io.reactiverse.pgclient.data.Numeric
 
isOpen() - Method in class io.reactiverse.pgclient.data.Path
 
isSSL() - Method in interface io.reactiverse.pgclient.PgConnection
 
isSSL() - Method in class io.reactiverse.reactivex.pgclient.PgConnection
 
isSSL() - Method in class io.reactiverse.rxjava.pgclient.PgConnection
 
isUsingDomainSocket() - Method in class io.reactiverse.pgclient.PgConnectOptions
 
iterator() - Method in interface io.reactiverse.pgclient.PgRowSet
 
iterator() - Method in class io.reactiverse.reactivex.pgclient.PgRowSet
 
iterator() - Method in class io.reactiverse.rxjava.pgclient.PgRowSet
 

J

Json - Interface in io.reactiverse.pgclient.data
 
Json - Class in io.reactiverse.reactivex.pgclient.data
 
Json(Json) - Constructor for class io.reactiverse.reactivex.pgclient.data.Json
 
Json - Class in io.reactiverse.rxjava.pgclient.data
 
Json(Json) - Constructor for class io.reactiverse.rxjava.pgclient.data.Json
 

L

Line - Class in io.reactiverse.pgclient.data
Line data type in Postgres represented by the linear equation Ax + By + C = 0, where A and B are not both zero.
Line() - Constructor for class io.reactiverse.pgclient.data.Line
 
Line(double, double, double) - Constructor for class io.reactiverse.pgclient.data.Line
 
Line(JsonObject) - Constructor for class io.reactiverse.pgclient.data.Line
 
LineConverter - Class in io.reactiverse.pgclient.data
Converter for Line.
LineConverter() - Constructor for class io.reactiverse.pgclient.data.LineConverter
 
LineSegment - Class in io.reactiverse.pgclient.data
Finite line segment data type in Postgres represented by pairs of Points that are the endpoints of the segment.
LineSegment() - Constructor for class io.reactiverse.pgclient.data.LineSegment
 
LineSegment(Point, Point) - Constructor for class io.reactiverse.pgclient.data.LineSegment
 
LineSegment(JsonObject) - Constructor for class io.reactiverse.pgclient.data.LineSegment
 
LineSegmentConverter - Class in io.reactiverse.pgclient.data
Converter for LineSegment.
LineSegmentConverter() - Constructor for class io.reactiverse.pgclient.data.LineSegmentConverter
 
longValue() - Method in class io.reactiverse.pgclient.data.Numeric
 

M

microseconds(int) - Method in class io.reactiverse.pgclient.data.Interval
 
minutes(int) - Method in class io.reactiverse.pgclient.data.Interval
 
months(int) - Method in class io.reactiverse.pgclient.data.Interval
 

N

NaN - Static variable in class io.reactiverse.pgclient.data.Numeric
Constant for the NaN value.
newInstance(Json) - Static method in class io.reactiverse.reactivex.pgclient.data.Json
 
newInstance(PgClient) - Static method in class io.reactiverse.reactivex.pgclient.PgClient
 
newInstance(PgConnection) - Static method in class io.reactiverse.reactivex.pgclient.PgConnection
 
newInstance(PgCursor) - Static method in class io.reactiverse.reactivex.pgclient.PgCursor
 
newInstance(PgIterator) - Static method in class io.reactiverse.reactivex.pgclient.PgIterator
 
newInstance(PgPool) - Static method in class io.reactiverse.reactivex.pgclient.PgPool
 
newInstance(PgPreparedQuery) - Static method in class io.reactiverse.reactivex.pgclient.PgPreparedQuery
 
newInstance(PgResult) - Static method in class io.reactiverse.reactivex.pgclient.PgResult
 
newInstance(PgResult, TypeArg<T>) - Static method in class io.reactiverse.reactivex.pgclient.PgResult
 
newInstance(PgRowSet) - Static method in class io.reactiverse.reactivex.pgclient.PgRowSet
 
newInstance(PgStream) - Static method in class io.reactiverse.reactivex.pgclient.PgStream
 
newInstance(PgStream, TypeArg<T>) - Static method in class io.reactiverse.reactivex.pgclient.PgStream
 
newInstance(PgTransaction) - Static method in class io.reactiverse.reactivex.pgclient.PgTransaction
 
newInstance(PgChannel) - Static method in class io.reactiverse.reactivex.pgclient.pubsub.PgChannel
 
newInstance(PgSubscriber) - Static method in class io.reactiverse.reactivex.pgclient.pubsub.PgSubscriber
 
newInstance(Row) - Static method in class io.reactiverse.reactivex.pgclient.Row
 
newInstance(Tuple) - Static method in class io.reactiverse.reactivex.pgclient.Tuple
 
newInstance(Json) - Static method in class io.reactiverse.rxjava.pgclient.data.Json
 
newInstance(PgClient) - Static method in class io.reactiverse.rxjava.pgclient.PgClient
 
newInstance(PgConnection) - Static method in class io.reactiverse.rxjava.pgclient.PgConnection
 
newInstance(PgCursor) - Static method in class io.reactiverse.rxjava.pgclient.PgCursor
 
newInstance(PgIterator) - Static method in class io.reactiverse.rxjava.pgclient.PgIterator
 
newInstance(PgPool) - Static method in class io.reactiverse.rxjava.pgclient.PgPool
 
newInstance(PgPreparedQuery) - Static method in class io.reactiverse.rxjava.pgclient.PgPreparedQuery
 
newInstance(PgResult) - Static method in class io.reactiverse.rxjava.pgclient.PgResult
 
newInstance(PgResult, TypeArg<T>) - Static method in class io.reactiverse.rxjava.pgclient.PgResult
 
newInstance(PgRowSet) - Static method in class io.reactiverse.rxjava.pgclient.PgRowSet
 
newInstance(PgStream) - Static method in class io.reactiverse.rxjava.pgclient.PgStream
 
newInstance(PgStream, TypeArg<T>) - Static method in class io.reactiverse.rxjava.pgclient.PgStream
 
newInstance(PgTransaction) - Static method in class io.reactiverse.rxjava.pgclient.PgTransaction
 
newInstance(PgChannel) - Static method in class io.reactiverse.rxjava.pgclient.pubsub.PgChannel
 
newInstance(PgSubscriber) - Static method in class io.reactiverse.rxjava.pgclient.pubsub.PgSubscriber
 
newInstance(Row) - Static method in class io.reactiverse.rxjava.pgclient.Row
 
newInstance(Tuple) - Static method in class io.reactiverse.rxjava.pgclient.Tuple
 
next() - Method in interface io.reactiverse.pgclient.PgIterator
 
next() - Method in interface io.reactiverse.pgclient.PgResult
Return the next available result or null, e.g for a simple query that executed multiple queries or for a batch result.
next() - Method in interface io.reactiverse.pgclient.PgRowSet
 
next() - Method in class io.reactiverse.reactivex.pgclient.PgIterator
 
next() - Method in class io.reactiverse.reactivex.pgclient.PgResult
Return the next available result or null, e.g for a simple query that executed multiple queries or for a batch result.
next() - Method in class io.reactiverse.reactivex.pgclient.PgRowSet
 
next() - Method in class io.reactiverse.rxjava.pgclient.PgIterator
 
next() - Method in class io.reactiverse.rxjava.pgclient.PgResult
Return the next available result or null, e.g for a simple query that executed multiple queries or for a batch result.
next() - Method in class io.reactiverse.rxjava.pgclient.PgRowSet
 
notificationHandler(Handler<PgNotification>) - Method in interface io.reactiverse.pgclient.PgConnection
Set an handler called when the connection receives notification on a channel.
notificationHandler(Handler<PgNotification>) - Method in class io.reactiverse.reactivex.pgclient.PgConnection
Set an handler called when the connection receives notification on a channel.
notificationHandler(Handler<PgNotification>) - Method in class io.reactiverse.rxjava.pgclient.PgConnection
Set an handler called when the connection receives notification on a channel.
Numeric - Class in io.reactiverse.pgclient.data
The Postgres NUMERIC type.

O

of() - Static method in class io.reactiverse.pgclient.data.Interval
 
of(int, int, int, int, int, int, int) - Static method in class io.reactiverse.pgclient.data.Interval
 
of(int, int, int, int, int, int) - Static method in class io.reactiverse.pgclient.data.Interval
 
of(int, int, int, int, int) - Static method in class io.reactiverse.pgclient.data.Interval
 
of(int, int, int, int) - Static method in class io.reactiverse.pgclient.data.Interval
 
of(int, int, int) - Static method in class io.reactiverse.pgclient.data.Interval
 
of(int, int) - Static method in class io.reactiverse.pgclient.data.Interval
 
of(int) - Static method in class io.reactiverse.pgclient.data.Interval
 
of(String) - Static method in enum io.reactiverse.pgclient.SslMode
 
of(Object) - Static method in interface io.reactiverse.pgclient.Tuple
Create a tuple of one element.
of(Object, Object) - Static method in interface io.reactiverse.pgclient.Tuple
Create a tuple of two elements.
of(Object, Object, Object) - Static method in interface io.reactiverse.pgclient.Tuple
Create a tuple of three elements.
of(Object, Object, Object, Object) - Static method in interface io.reactiverse.pgclient.Tuple
Create a tuple of four elements.
of(Object, Object, Object, Object, Object) - Static method in interface io.reactiverse.pgclient.Tuple
Create a tuple of five elements.
of(Object, Object, Object, Object, Object, Object) - Static method in interface io.reactiverse.pgclient.Tuple
Create a tuple of six elements.
of(Object, Object...) - Static method in interface io.reactiverse.pgclient.Tuple
Create a tuple of an arbitrary number of elements.
of(Object) - Static method in class io.reactiverse.reactivex.pgclient.Tuple
Create a tuple of one element.
of(Object, Object) - Static method in class io.reactiverse.reactivex.pgclient.Tuple
Create a tuple of two elements.
of(Object, Object, Object) - Static method in class io.reactiverse.reactivex.pgclient.Tuple
Create a tuple of three elements.
of(Object, Object, Object, Object) - Static method in class io.reactiverse.reactivex.pgclient.Tuple
Create a tuple of four elements.
of(Object, Object, Object, Object, Object) - Static method in class io.reactiverse.reactivex.pgclient.Tuple
Create a tuple of five elements.
of(Object, Object, Object, Object, Object, Object) - Static method in class io.reactiverse.reactivex.pgclient.Tuple
Create a tuple of six elements.
of(Object) - Static method in class io.reactiverse.rxjava.pgclient.Tuple
Create a tuple of one element.
of(Object, Object) - Static method in class io.reactiverse.rxjava.pgclient.Tuple
Create a tuple of two elements.
of(Object, Object, Object) - Static method in class io.reactiverse.rxjava.pgclient.Tuple
Create a tuple of three elements.
of(Object, Object, Object, Object) - Static method in class io.reactiverse.rxjava.pgclient.Tuple
Create a tuple of four elements.
of(Object, Object, Object, Object, Object) - Static method in class io.reactiverse.rxjava.pgclient.Tuple
Create a tuple of five elements.
of(Object, Object, Object, Object, Object, Object) - Static method in class io.reactiverse.rxjava.pgclient.Tuple
Create a tuple of six elements.

P

parse(String) - Static method in class io.reactiverse.pgclient.data.Numeric
Parse and return a Numeric instance for the given s.
Path - Class in io.reactiverse.pgclient.data
Path data type in Postgres represented by lists of connected points.
Path() - Constructor for class io.reactiverse.pgclient.data.Path
 
Path(boolean, List<Point>) - Constructor for class io.reactiverse.pgclient.data.Path
 
Path(JsonObject) - Constructor for class io.reactiverse.pgclient.data.Path
 
PathConverter - Class in io.reactiverse.pgclient.data
Converter for Path.
PathConverter() - Constructor for class io.reactiverse.pgclient.data.PathConverter
 
pause() - Method in interface io.reactiverse.pgclient.PgStream
 
pause() - Method in interface io.reactiverse.pgclient.pubsub.PgChannel
Pause the channel, all notifications are discarded.
pause() - Method in class io.reactiverse.reactivex.pgclient.PgStream
 
pause() - Method in class io.reactiverse.reactivex.pgclient.pubsub.PgChannel
Pause the channel, all notifications are discarded.
pause() - Method in class io.reactiverse.rxjava.pgclient.PgStream
 
pause() - Method in class io.reactiverse.rxjava.pgclient.pubsub.PgChannel
Pause the channel, all notifications are discarded.
PgChannel - Interface in io.reactiverse.pgclient.pubsub
A channel to Postgres that tracks the subscription to a given Postgres channel using the LISTEN/UNLISTEN commands.
PgChannel - Class in io.reactiverse.reactivex.pgclient.pubsub
A channel to Postgres that tracks the subscription to a given Postgres channel using the LISTEN/UNLISTEN commands.
PgChannel(PgChannel) - Constructor for class io.reactiverse.reactivex.pgclient.pubsub.PgChannel
 
PgChannel - Class in io.reactiverse.rxjava.pgclient.pubsub
A channel to Postgres that tracks the subscription to a given Postgres channel using the LISTEN/UNLISTEN commands.
PgChannel(PgChannel) - Constructor for class io.reactiverse.rxjava.pgclient.pubsub.PgChannel
 
PgClient - Interface in io.reactiverse.pgclient
Defines the client operations with a Postgres Database.
PgClient - Class in io.reactiverse.reactivex.pgclient
Defines the client operations with a Postgres Database.
PgClient(PgClient) - Constructor for class io.reactiverse.reactivex.pgclient.PgClient
 
PgClient - Class in io.reactiverse.rxjava.pgclient
Defines the client operations with a Postgres Database.
PgClient(PgClient) - Constructor for class io.reactiverse.rxjava.pgclient.PgClient
 
PgConnection - Interface in io.reactiverse.pgclient
A connection to Postgres.
PgConnection - Class in io.reactiverse.reactivex.pgclient
A connection to Postgres.
PgConnection(PgConnection) - Constructor for class io.reactiverse.reactivex.pgclient.PgConnection
 
PgConnection - Class in io.reactiverse.rxjava.pgclient
A connection to Postgres.
PgConnection(PgConnection) - Constructor for class io.reactiverse.rxjava.pgclient.PgConnection
 
PgConnectOptions - Class in io.reactiverse.pgclient
 
PgConnectOptions() - Constructor for class io.reactiverse.pgclient.PgConnectOptions
 
PgConnectOptions(JsonObject) - Constructor for class io.reactiverse.pgclient.PgConnectOptions
 
PgConnectOptions(PgConnectOptions) - Constructor for class io.reactiverse.pgclient.PgConnectOptions
 
PgConnectOptionsConverter - Class in io.reactiverse.pgclient
Converter for PgConnectOptions.
PgConnectOptionsConverter() - Constructor for class io.reactiverse.pgclient.PgConnectOptionsConverter
 
PgCursor - Interface in io.reactiverse.pgclient
A cursor that reads progressively the rows from Postgres, it is usefull for reading very large result.
PgCursor - Class in io.reactiverse.reactivex.pgclient
A cursor that reads progressively the rows from Postgres, it is usefull for reading very large result.
PgCursor(PgCursor) - Constructor for class io.reactiverse.reactivex.pgclient.PgCursor
 
PgCursor - Class in io.reactiverse.rxjava.pgclient
A cursor that reads progressively the rows from Postgres, it is usefull for reading very large result.
PgCursor(PgCursor) - Constructor for class io.reactiverse.rxjava.pgclient.PgCursor
 
PgException - Exception in io.reactiverse.pgclient
 
PgException(ErrorResponse) - Constructor for exception io.reactiverse.pgclient.PgException
 
PgIterator - Interface in io.reactiverse.pgclient
An iterator for processing postgres items synchronously.
PgIterator - Class in io.reactiverse.reactivex.pgclient
An iterator for processing postgres items synchronously.
PgIterator(PgIterator) - Constructor for class io.reactiverse.reactivex.pgclient.PgIterator
 
PgIterator - Class in io.reactiverse.rxjava.pgclient
An iterator for processing postgres items synchronously.
PgIterator(PgIterator) - Constructor for class io.reactiverse.rxjava.pgclient.PgIterator
 
PgNotification - Class in io.reactiverse.pgclient
A notification emited by Postgres.
PgNotification() - Constructor for class io.reactiverse.pgclient.PgNotification
 
PgNotification(JsonObject) - Constructor for class io.reactiverse.pgclient.PgNotification
 
PgNotificationConverter - Class in io.reactiverse.pgclient
Converter for PgNotification.
PgNotificationConverter() - Constructor for class io.reactiverse.pgclient.PgNotificationConverter
 
PgPool - Interface in io.reactiverse.pgclient
A pool of connection.
PgPool - Class in io.reactiverse.reactivex.pgclient
A pool of connection.
PgPool(PgPool) - Constructor for class io.reactiverse.reactivex.pgclient.PgPool
 
PgPool - Class in io.reactiverse.rxjava.pgclient
A pool of connection.
PgPool(PgPool) - Constructor for class io.reactiverse.rxjava.pgclient.PgPool
 
PgPoolOptions - Class in io.reactiverse.pgclient
The options for configuring a connection pool.
PgPoolOptions() - Constructor for class io.reactiverse.pgclient.PgPoolOptions
 
PgPoolOptions(JsonObject) - Constructor for class io.reactiverse.pgclient.PgPoolOptions
 
PgPoolOptions(PgPoolOptions) - Constructor for class io.reactiverse.pgclient.PgPoolOptions
 
PgPoolOptions(PgConnectOptions) - Constructor for class io.reactiverse.pgclient.PgPoolOptions
 
PgPoolOptionsConverter - Class in io.reactiverse.pgclient
Converter for PgPoolOptions.
PgPoolOptionsConverter() - Constructor for class io.reactiverse.pgclient.PgPoolOptionsConverter
 
PgPreparedQuery - Interface in io.reactiverse.pgclient
A prepared query.
PgPreparedQuery - Class in io.reactiverse.reactivex.pgclient
A prepared query.
PgPreparedQuery(PgPreparedQuery) - Constructor for class io.reactiverse.reactivex.pgclient.PgPreparedQuery
 
PgPreparedQuery - Class in io.reactiverse.rxjava.pgclient
A prepared query.
PgPreparedQuery(PgPreparedQuery) - Constructor for class io.reactiverse.rxjava.pgclient.PgPreparedQuery
 
PgResult<T> - Interface in io.reactiverse.pgclient
Represents the result of an operation on database.
PgResult<T> - Class in io.reactiverse.reactivex.pgclient
Represents the result of an operation on database.
PgResult(PgResult) - Constructor for class io.reactiverse.reactivex.pgclient.PgResult
 
PgResult(PgResult, TypeArg<T>) - Constructor for class io.reactiverse.reactivex.pgclient.PgResult
 
PgResult<T> - Class in io.reactiverse.rxjava.pgclient
Represents the result of an operation on database.
PgResult(PgResult) - Constructor for class io.reactiverse.rxjava.pgclient.PgResult
 
PgResult(PgResult, TypeArg<T>) - Constructor for class io.reactiverse.rxjava.pgclient.PgResult
 
PgRowSet - Interface in io.reactiverse.pgclient
A set of rows.
PgRowSet - Class in io.reactiverse.reactivex.pgclient
A set of rows.
PgRowSet(PgRowSet) - Constructor for class io.reactiverse.reactivex.pgclient.PgRowSet
 
PgRowSet - Class in io.reactiverse.rxjava.pgclient
A set of rows.
PgRowSet(PgRowSet) - Constructor for class io.reactiverse.rxjava.pgclient.PgRowSet
 
PgStream<T> - Interface in io.reactiverse.pgclient
A row oriented stream.
PgStream<T> - Class in io.reactiverse.reactivex.pgclient
A row oriented stream.
PgStream(PgStream) - Constructor for class io.reactiverse.reactivex.pgclient.PgStream
 
PgStream(PgStream, TypeArg<T>) - Constructor for class io.reactiverse.reactivex.pgclient.PgStream
 
PgStream<T> - Class in io.reactiverse.rxjava.pgclient
A row oriented stream.
PgStream(PgStream) - Constructor for class io.reactiverse.rxjava.pgclient.PgStream
 
PgStream(PgStream, TypeArg<T>) - Constructor for class io.reactiverse.rxjava.pgclient.PgStream
 
PgSubscriber - Interface in io.reactiverse.pgclient.pubsub
A class for managing subscriptions using LISTEN/UNLISTEN to Postgres channels.
PgSubscriber - Class in io.reactiverse.reactivex.pgclient.pubsub
A class for managing subscriptions using LISTEN/UNLISTEN to Postgres channels.
PgSubscriber(PgSubscriber) - Constructor for class io.reactiverse.reactivex.pgclient.pubsub.PgSubscriber
 
PgSubscriber - Class in io.reactiverse.rxjava.pgclient.pubsub
A class for managing subscriptions using LISTEN/UNLISTEN to Postgres channels.
PgSubscriber(PgSubscriber) - Constructor for class io.reactiverse.rxjava.pgclient.pubsub.PgSubscriber
 
PgTransaction - Interface in io.reactiverse.pgclient
A transaction that allows to control the transaction and receive events.
PgTransaction - Class in io.reactiverse.reactivex.pgclient
A transaction that allows to control the transaction and receive events.
PgTransaction(PgTransaction) - Constructor for class io.reactiverse.reactivex.pgclient.PgTransaction
 
PgTransaction - Class in io.reactiverse.rxjava.pgclient
A transaction that allows to control the transaction and receive events.
PgTransaction(PgTransaction) - Constructor for class io.reactiverse.rxjava.pgclient.PgTransaction
 
Point - Class in io.reactiverse.pgclient.data
A Postgresql point.
Point() - Constructor for class io.reactiverse.pgclient.data.Point
 
Point(double, double) - Constructor for class io.reactiverse.pgclient.data.Point
 
Point(JsonObject) - Constructor for class io.reactiverse.pgclient.data.Point
 
PointConverter - Class in io.reactiverse.pgclient.data
Converter for Point.
PointConverter() - Constructor for class io.reactiverse.pgclient.data.PointConverter
 
Polygon - Class in io.reactiverse.pgclient.data
Polygon data type in Postgres represented by lists of points (the vertexes of the polygon).
Polygon() - Constructor for class io.reactiverse.pgclient.data.Polygon
 
Polygon(List<Point>) - Constructor for class io.reactiverse.pgclient.data.Polygon
 
Polygon(JsonObject) - Constructor for class io.reactiverse.pgclient.data.Polygon
 
PolygonConverter - Class in io.reactiverse.pgclient.data
Converter for Polygon.
PolygonConverter() - Constructor for class io.reactiverse.pgclient.data.PolygonConverter
 
pool() - Static method in interface io.reactiverse.pgclient.PgClient
Like PgClient.pool(PgPoolOptions) with options build from the environment variables.
pool(String) - Static method in interface io.reactiverse.pgclient.PgClient
Like PgClient.pool(PgPoolOptions) with options build from connectionUri.
pool(Vertx) - Static method in interface io.reactiverse.pgclient.PgClient
Like PgClient.pool(Vertx, PgPoolOptions) with options build from the environment variables.
pool(Vertx, String) - Static method in interface io.reactiverse.pgclient.PgClient
Like PgClient.pool(Vertx, PgPoolOptions) with options build from connectionUri.
pool(PgPoolOptions) - Static method in interface io.reactiverse.pgclient.PgClient
Create a connection pool to the database configured with the given options.
pool(Vertx, PgPoolOptions) - Static method in interface io.reactiverse.pgclient.PgClient
Like PgClient.pool(PgPoolOptions) with a specific Vertx instance.
pool() - Static method in class io.reactiverse.reactivex.pgclient.PgClient
Like PgClient.pool() with options build from the environment variables.
pool(String) - Static method in class io.reactiverse.reactivex.pgclient.PgClient
Like PgClient.pool() with options build from connectionUri.
pool(Vertx) - Static method in class io.reactiverse.reactivex.pgclient.PgClient
Like PgClient.pool() with options build from the environment variables.
pool(Vertx, String) - Static method in class io.reactiverse.reactivex.pgclient.PgClient
Like PgClient.pool() with options build from connectionUri.
pool(PgPoolOptions) - Static method in class io.reactiverse.reactivex.pgclient.PgClient
Create a connection pool to the database configured with the given options.
pool(Vertx, PgPoolOptions) - Static method in class io.reactiverse.reactivex.pgclient.PgClient
Like PgClient.pool() with a specific instance.
pool() - Static method in class io.reactiverse.rxjava.pgclient.PgClient
Like PgClient.pool() with options build from the environment variables.
pool(String) - Static method in class io.reactiverse.rxjava.pgclient.PgClient
Like PgClient.pool() with options build from connectionUri.
pool(Vertx) - Static method in class io.reactiverse.rxjava.pgclient.PgClient
Like PgClient.pool() with options build from the environment variables.
pool(Vertx, String) - Static method in class io.reactiverse.rxjava.pgclient.PgClient
Like PgClient.pool() with options build from connectionUri.
pool(PgPoolOptions) - Static method in class io.reactiverse.rxjava.pgclient.PgClient
Create a connection pool to the database configured with the given options.
pool(Vertx, PgPoolOptions) - Static method in class io.reactiverse.rxjava.pgclient.PgClient
Like PgClient.pool() with a specific instance.
prepare(String, Handler<AsyncResult<PgPreparedQuery>>) - Method in interface io.reactiverse.pgclient.PgConnection
Create a prepared query.
prepare(String, Handler<AsyncResult<PgPreparedQuery>>) - Method in interface io.reactiverse.pgclient.PgTransaction
Create a prepared query.
prepare(String, Handler<AsyncResult<PgPreparedQuery>>) - Method in class io.reactiverse.reactivex.pgclient.PgConnection
Create a prepared query.
prepare(String, Handler<AsyncResult<PgPreparedQuery>>) - Method in class io.reactiverse.reactivex.pgclient.PgTransaction
Create a prepared query.
prepare(String, Handler<AsyncResult<PgPreparedQuery>>) - Method in class io.reactiverse.rxjava.pgclient.PgConnection
Create a prepared query.
prepare(String, Handler<AsyncResult<PgPreparedQuery>>) - Method in class io.reactiverse.rxjava.pgclient.PgTransaction
Create a prepared query.
preparedBatch(String, List<Tuple>, Handler<AsyncResult<PgRowSet>>) - Method in interface io.reactiverse.pgclient.PgClient
Prepare and execute a createBatch.
preparedBatch(String, List<Tuple>, Collector<Row, ?, R>, Handler<AsyncResult<PgResult<R>>>) - Method in interface io.reactiverse.pgclient.PgClient
Prepare and execute a createBatch.
preparedBatch(String, List<Tuple>, Handler<AsyncResult<PgRowSet>>) - Method in interface io.reactiverse.pgclient.PgConnection
 
preparedBatch(String, List<Tuple>, Collector<Row, ?, R>, Handler<AsyncResult<PgResult<R>>>) - Method in interface io.reactiverse.pgclient.PgConnection
 
preparedBatch(String, List<Tuple>, Handler<AsyncResult<PgRowSet>>) - Method in interface io.reactiverse.pgclient.PgPool
 
preparedBatch(String, List<Tuple>, Collector<Row, ?, R>, Handler<AsyncResult<PgResult<R>>>) - Method in interface io.reactiverse.pgclient.PgPool
 
preparedBatch(String, List<Tuple>, Handler<AsyncResult<PgRowSet>>) - Method in interface io.reactiverse.pgclient.PgTransaction
 
preparedBatch(String, List<Tuple>, Collector<Row, ?, R>, Handler<AsyncResult<PgResult<R>>>) - Method in interface io.reactiverse.pgclient.PgTransaction
 
preparedBatch(String, List<Tuple>, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.reactivex.pgclient.PgClient
Prepare and execute a createBatch.
preparedBatch(String, List<Tuple>, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.reactivex.pgclient.PgConnection
 
preparedBatch(String, List<Tuple>, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.reactivex.pgclient.PgPool
 
preparedBatch(String, List<Tuple>, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.reactivex.pgclient.PgTransaction
 
preparedBatch(String, List<Tuple>, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.rxjava.pgclient.PgClient
Prepare and execute a createBatch.
preparedBatch(String, List<Tuple>, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.rxjava.pgclient.PgConnection
 
preparedBatch(String, List<Tuple>, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.rxjava.pgclient.PgPool
 
preparedBatch(String, List<Tuple>, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.rxjava.pgclient.PgTransaction
 
preparedQuery(String, Handler<AsyncResult<PgRowSet>>) - Method in interface io.reactiverse.pgclient.PgClient
Prepare and execute a query.
preparedQuery(String, Collector<Row, ?, R>, Handler<AsyncResult<PgResult<R>>>) - Method in interface io.reactiverse.pgclient.PgClient
Prepare and execute a query.
preparedQuery(String, Tuple, Handler<AsyncResult<PgRowSet>>) - Method in interface io.reactiverse.pgclient.PgClient
Prepare and execute a query.
preparedQuery(String, Tuple, Collector<Row, ?, R>, Handler<AsyncResult<PgResult<R>>>) - Method in interface io.reactiverse.pgclient.PgClient
Prepare and execute a query.
preparedQuery(String, Handler<AsyncResult<PgRowSet>>) - Method in interface io.reactiverse.pgclient.PgConnection
 
preparedQuery(String, Collector<Row, ?, R>, Handler<AsyncResult<PgResult<R>>>) - Method in interface io.reactiverse.pgclient.PgConnection
 
preparedQuery(String, Tuple, Handler<AsyncResult<PgRowSet>>) - Method in interface io.reactiverse.pgclient.PgConnection
 
preparedQuery(String, Tuple, Collector<Row, ?, R>, Handler<AsyncResult<PgResult<R>>>) - Method in interface io.reactiverse.pgclient.PgConnection
 
preparedQuery(String, Handler<AsyncResult<PgRowSet>>) - Method in interface io.reactiverse.pgclient.PgPool
 
preparedQuery(String, Collector<Row, ?, R>, Handler<AsyncResult<PgResult<R>>>) - Method in interface io.reactiverse.pgclient.PgPool
 
preparedQuery(String, Tuple, Handler<AsyncResult<PgRowSet>>) - Method in interface io.reactiverse.pgclient.PgPool
 
preparedQuery(String, Tuple, Collector<Row, ?, R>, Handler<AsyncResult<PgResult<R>>>) - Method in interface io.reactiverse.pgclient.PgPool
 
preparedQuery(String, Handler<AsyncResult<PgRowSet>>) - Method in interface io.reactiverse.pgclient.PgTransaction
 
preparedQuery(String, Collector<Row, ?, R>, Handler<AsyncResult<PgResult<R>>>) - Method in interface io.reactiverse.pgclient.PgTransaction
 
preparedQuery(String, Tuple, Handler<AsyncResult<PgRowSet>>) - Method in interface io.reactiverse.pgclient.PgTransaction
 
preparedQuery(String, Tuple, Collector<Row, ?, R>, Handler<AsyncResult<PgResult<R>>>) - Method in interface io.reactiverse.pgclient.PgTransaction
 
preparedQuery(String, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.reactivex.pgclient.PgClient
Prepare and execute a query.
preparedQuery(String, Tuple, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.reactivex.pgclient.PgClient
Prepare and execute a query.
preparedQuery(String, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.reactivex.pgclient.PgConnection
 
preparedQuery(String, Tuple, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.reactivex.pgclient.PgConnection
 
preparedQuery(String, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.reactivex.pgclient.PgPool
 
preparedQuery(String, Tuple, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.reactivex.pgclient.PgPool
 
preparedQuery(String, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.reactivex.pgclient.PgTransaction
 
preparedQuery(String, Tuple, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.reactivex.pgclient.PgTransaction
 
preparedQuery(String, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.rxjava.pgclient.PgClient
Prepare and execute a query.
preparedQuery(String, Tuple, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.rxjava.pgclient.PgClient
Prepare and execute a query.
preparedQuery(String, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.rxjava.pgclient.PgConnection
 
preparedQuery(String, Tuple, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.rxjava.pgclient.PgConnection
 
preparedQuery(String, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.rxjava.pgclient.PgPool
 
preparedQuery(String, Tuple, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.rxjava.pgclient.PgPool
 
preparedQuery(String, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.rxjava.pgclient.PgTransaction
 
preparedQuery(String, Tuple, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.rxjava.pgclient.PgTransaction
 
processId() - Method in interface io.reactiverse.pgclient.PgConnection
 
processId() - Method in class io.reactiverse.reactivex.pgclient.PgConnection
 
processId() - Method in class io.reactiverse.rxjava.pgclient.PgConnection
 

Q

query(String, Handler<AsyncResult<PgRowSet>>) - Method in interface io.reactiverse.pgclient.PgClient
Execute a simple query.
query(String, Collector<Row, ?, R>, Handler<AsyncResult<PgResult<R>>>) - Method in interface io.reactiverse.pgclient.PgClient
Execute a simple query.
query(String, Handler<AsyncResult<PgRowSet>>) - Method in interface io.reactiverse.pgclient.PgConnection
 
query(String, Collector<Row, ?, R>, Handler<AsyncResult<PgResult<R>>>) - Method in interface io.reactiverse.pgclient.PgConnection
 
query(String, Handler<AsyncResult<PgRowSet>>) - Method in interface io.reactiverse.pgclient.PgPool
 
query(String, Collector<Row, ?, R>, Handler<AsyncResult<PgResult<R>>>) - Method in interface io.reactiverse.pgclient.PgPool
 
query(String, Handler<AsyncResult<PgRowSet>>) - Method in interface io.reactiverse.pgclient.PgTransaction
 
query(String, Collector<Row, ?, R>, Handler<AsyncResult<PgResult<R>>>) - Method in interface io.reactiverse.pgclient.PgTransaction
 
query(String, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.reactivex.pgclient.PgClient
Execute a simple query.
query(String, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.reactivex.pgclient.PgConnection
 
query(String, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.reactivex.pgclient.PgPool
 
query(String, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.reactivex.pgclient.PgTransaction
 
query(String, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.rxjava.pgclient.PgClient
Execute a simple query.
query(String, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.rxjava.pgclient.PgConnection
 
query(String, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.rxjava.pgclient.PgPool
 
query(String, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.rxjava.pgclient.PgTransaction
 

R

read(int, Handler<AsyncResult<PgRowSet>>) - Method in interface io.reactiverse.pgclient.PgCursor
Read rows from the cursor, the result is provided asynchronously to the handler.
read(int, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.reactivex.pgclient.PgCursor
Read rows from the cursor, the result is provided asynchronously to the handler.
read(int, Handler<AsyncResult<PgRowSet>>) - Method in class io.reactiverse.rxjava.pgclient.PgCursor
Read rows from the cursor, the result is provided asynchronously to the handler.
reconnectPolicy(Function<Integer, Long>) - Method in interface io.reactiverse.pgclient.pubsub.PgSubscriber
Set the reconnect policy that is executed when the subscriber is disconnected.
reconnectPolicy(Function<Integer, Long>) - Method in class io.reactiverse.reactivex.pgclient.pubsub.PgSubscriber
Set the reconnect policy that is executed when the subscriber is disconnected.
reconnectPolicy(Function<Integer, Long>) - Method in class io.reactiverse.rxjava.pgclient.pubsub.PgSubscriber
Set the reconnect policy that is executed when the subscriber is disconnected.
resume() - Method in interface io.reactiverse.pgclient.PgStream
 
resume() - Method in interface io.reactiverse.pgclient.pubsub.PgChannel
Resume the channel.
resume() - Method in class io.reactiverse.reactivex.pgclient.PgStream
 
resume() - Method in class io.reactiverse.reactivex.pgclient.pubsub.PgChannel
Resume the channel.
resume() - Method in class io.reactiverse.rxjava.pgclient.PgStream
 
resume() - Method in class io.reactiverse.rxjava.pgclient.pubsub.PgChannel
Resume the channel.
rollback() - Method in interface io.reactiverse.pgclient.PgTransaction
Rollback the current transaction.
rollback(Handler<AsyncResult<Void>>) - Method in interface io.reactiverse.pgclient.PgTransaction
Like PgTransaction.rollback() with an handler to be notified when the transaction rollback has completed
rollback() - Method in class io.reactiverse.reactivex.pgclient.PgTransaction
Rollback the current transaction.
rollback(Handler<AsyncResult<Void>>) - Method in class io.reactiverse.reactivex.pgclient.PgTransaction
Like PgTransaction.rollback() with an handler to be notified when the transaction rollback has completed
rollback() - Method in class io.reactiverse.rxjava.pgclient.PgTransaction
Rollback the current transaction.
rollback(Handler<AsyncResult<Void>>) - Method in class io.reactiverse.rxjava.pgclient.PgTransaction
Like PgTransaction.rollback() with an handler to be notified when the transaction rollback has completed
Row - Interface in io.reactiverse.pgclient
 
Row - Class in io.reactiverse.reactivex.pgclient
 
Row(Row) - Constructor for class io.reactiverse.reactivex.pgclient.Row
 
Row - Class in io.reactiverse.rxjava.pgclient
 
Row(Row) - Constructor for class io.reactiverse.rxjava.pgclient.Row
 
rowCount() - Method in interface io.reactiverse.pgclient.PgResult
Get the number of the affected rows in the operation to this PgResult.
rowCount() - Method in class io.reactiverse.reactivex.pgclient.PgResult
Get the number of the affected rows in the operation to this PgResult.
rowCount() - Method in class io.reactiverse.rxjava.pgclient.PgResult
Get the number of the affected rows in the operation to this PgResult.
rxBatch(List<Tuple>) - Method in class io.reactiverse.reactivex.pgclient.PgPreparedQuery
Execute a batch.
rxBatch(List<Tuple>) - Method in class io.reactiverse.rxjava.pgclient.PgPreparedQuery
Execute a batch.
rxBegin() - Method in class io.reactiverse.reactivex.pgclient.PgPool
Borrow a connection from the pool and begin a transaction, the underlying connection will be returned to the pool when the transaction ends.
rxBegin() - Method in class io.reactiverse.rxjava.pgclient.PgPool
Borrow a connection from the pool and begin a transaction, the underlying connection will be returned to the pool when the transaction ends.
rxClose() - Method in class io.reactiverse.reactivex.pgclient.PgCursor
Like PgCursor.close() but with a completionHandler called when the cursor has been released.
rxClose() - Method in class io.reactiverse.reactivex.pgclient.PgPreparedQuery
Like PgPreparedQuery.close() but notifies the completionHandler when it's closed.
rxClose() - Method in class io.reactiverse.reactivex.pgclient.PgStream
Close the stream and release the resources.
rxClose() - Method in class io.reactiverse.rxjava.pgclient.PgCursor
Like PgCursor.close() but with a completionHandler called when the cursor has been released.
rxClose() - Method in class io.reactiverse.rxjava.pgclient.PgPreparedQuery
Like PgPreparedQuery.close() but notifies the completionHandler when it's closed.
rxClose() - Method in class io.reactiverse.rxjava.pgclient.PgStream
Close the stream and release the resources.
rxCommit() - Method in class io.reactiverse.reactivex.pgclient.PgTransaction
Like PgTransaction.commit() with an handler to be notified when the transaction commit has completed
rxCommit() - Method in class io.reactiverse.rxjava.pgclient.PgTransaction
Like PgTransaction.commit() with an handler to be notified when the transaction commit has completed
rxConnect(Vertx, PgConnectOptions) - Static method in class io.reactiverse.reactivex.pgclient.PgClient
Connects to the database and returns the connection if that succeeds.
rxConnect(Vertx) - Static method in class io.reactiverse.reactivex.pgclient.PgClient
rxConnect(Vertx, String) - Static method in class io.reactiverse.reactivex.pgclient.PgClient
rxConnect() - Method in class io.reactiverse.reactivex.pgclient.pubsub.PgSubscriber
Connect the subscriber to Postgres.
rxConnect(Vertx, PgConnectOptions) - Static method in class io.reactiverse.rxjava.pgclient.PgClient
Connects to the database and returns the connection if that succeeds.
rxConnect(Vertx) - Static method in class io.reactiverse.rxjava.pgclient.PgClient
rxConnect(Vertx, String) - Static method in class io.reactiverse.rxjava.pgclient.PgClient
rxConnect() - Method in class io.reactiverse.rxjava.pgclient.pubsub.PgSubscriber
Connect the subscriber to Postgres.
rxExecute() - Method in class io.reactiverse.reactivex.pgclient.PgPreparedQuery
rxExecute(Tuple) - Method in class io.reactiverse.reactivex.pgclient.PgPreparedQuery
Create a cursor with the provided arguments.
rxExecute() - Method in class io.reactiverse.rxjava.pgclient.PgPreparedQuery
rxExecute(Tuple) - Method in class io.reactiverse.rxjava.pgclient.PgPreparedQuery
Create a cursor with the provided arguments.
rxGetConnection() - Method in class io.reactiverse.reactivex.pgclient.PgPool
Get a connection from the pool.
rxGetConnection() - Method in class io.reactiverse.rxjava.pgclient.PgPool
Get a connection from the pool.
rxPrepare(String) - Method in class io.reactiverse.reactivex.pgclient.PgConnection
Create a prepared query.
rxPrepare(String) - Method in class io.reactiverse.reactivex.pgclient.PgTransaction
Create a prepared query.
rxPrepare(String) - Method in class io.reactiverse.rxjava.pgclient.PgConnection
Create a prepared query.
rxPrepare(String) - Method in class io.reactiverse.rxjava.pgclient.PgTransaction
Create a prepared query.
rxPreparedBatch(String, List<Tuple>) - Method in class io.reactiverse.reactivex.pgclient.PgClient
Prepare and execute a createBatch.
rxPreparedBatch(String, List<Tuple>) - Method in class io.reactiverse.reactivex.pgclient.PgConnection
 
rxPreparedBatch(String, List<Tuple>) - Method in class io.reactiverse.reactivex.pgclient.PgPool
 
rxPreparedBatch(String, List<Tuple>) - Method in class io.reactiverse.reactivex.pgclient.PgTransaction
 
rxPreparedBatch(String, List<Tuple>) - Method in class io.reactiverse.rxjava.pgclient.PgClient
Prepare and execute a createBatch.
rxPreparedBatch(String, List<Tuple>) - Method in class io.reactiverse.rxjava.pgclient.PgConnection
 
rxPreparedBatch(String, List<Tuple>) - Method in class io.reactiverse.rxjava.pgclient.PgPool
 
rxPreparedBatch(String, List<Tuple>) - Method in class io.reactiverse.rxjava.pgclient.PgTransaction
 
rxPreparedQuery(String) - Method in class io.reactiverse.reactivex.pgclient.PgClient
Prepare and execute a query.
rxPreparedQuery(String, Tuple) - Method in class io.reactiverse.reactivex.pgclient.PgClient
Prepare and execute a query.
rxPreparedQuery(String) - Method in class io.reactiverse.reactivex.pgclient.PgConnection
 
rxPreparedQuery(String, Tuple) - Method in class io.reactiverse.reactivex.pgclient.PgConnection
 
rxPreparedQuery(String) - Method in class io.reactiverse.reactivex.pgclient.PgPool
 
rxPreparedQuery(String, Tuple) - Method in class io.reactiverse.reactivex.pgclient.PgPool
 
rxPreparedQuery(String) - Method in class io.reactiverse.reactivex.pgclient.PgTransaction
 
rxPreparedQuery(String, Tuple) - Method in class io.reactiverse.reactivex.pgclient.PgTransaction
 
rxPreparedQuery(String) - Method in class io.reactiverse.rxjava.pgclient.PgClient
Prepare and execute a query.
rxPreparedQuery(String, Tuple) - Method in class io.reactiverse.rxjava.pgclient.PgClient
Prepare and execute a query.
rxPreparedQuery(String) - Method in class io.reactiverse.rxjava.pgclient.PgConnection
 
rxPreparedQuery(String, Tuple) - Method in class io.reactiverse.rxjava.pgclient.PgConnection
 
rxPreparedQuery(String) - Method in class io.reactiverse.rxjava.pgclient.PgPool
 
rxPreparedQuery(String, Tuple) - Method in class io.reactiverse.rxjava.pgclient.PgPool
 
rxPreparedQuery(String) - Method in class io.reactiverse.rxjava.pgclient.PgTransaction
 
rxPreparedQuery(String, Tuple) - Method in class io.reactiverse.rxjava.pgclient.PgTransaction
 
rxQuery(String) - Method in class io.reactiverse.reactivex.pgclient.PgClient
Execute a simple query.
rxQuery(String) - Method in class io.reactiverse.reactivex.pgclient.PgConnection
 
rxQuery(String) - Method in class io.reactiverse.reactivex.pgclient.PgPool
 
rxQuery(String) - Method in class io.reactiverse.reactivex.pgclient.PgTransaction
 
rxQuery(String) - Method in class io.reactiverse.rxjava.pgclient.PgClient
Execute a simple query.
rxQuery(String) - Method in class io.reactiverse.rxjava.pgclient.PgConnection
 
rxQuery(String) - Method in class io.reactiverse.rxjava.pgclient.PgPool
 
rxQuery(String) - Method in class io.reactiverse.rxjava.pgclient.PgTransaction
 
rxRead(int) - Method in class io.reactiverse.reactivex.pgclient.PgCursor
Read rows from the cursor, the result is provided asynchronously to the handler.
rxRead(int) - Method in class io.reactiverse.rxjava.pgclient.PgCursor
Read rows from the cursor, the result is provided asynchronously to the handler.
rxRollback() - Method in class io.reactiverse.reactivex.pgclient.PgTransaction
Like PgTransaction.rollback() with an handler to be notified when the transaction rollback has completed
rxRollback() - Method in class io.reactiverse.rxjava.pgclient.PgTransaction
Like PgTransaction.rollback() with an handler to be notified when the transaction rollback has completed

S

seconds(int) - Method in class io.reactiverse.pgclient.data.Interval
 
secretKey() - Method in interface io.reactiverse.pgclient.PgConnection
 
secretKey() - Method in class io.reactiverse.reactivex.pgclient.PgConnection
 
secretKey() - Method in class io.reactiverse.rxjava.pgclient.PgConnection
 
setA(double) - Method in class io.reactiverse.pgclient.data.Line
 
setB(double) - Method in class io.reactiverse.pgclient.data.Line
 
setC(double) - Method in class io.reactiverse.pgclient.data.Line
 
setCachePreparedStatements(boolean) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setCachePreparedStatements(boolean) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setCenterPoint(Point) - Method in class io.reactiverse.pgclient.data.Circle
 
setChannel(String) - Method in class io.reactiverse.pgclient.PgNotification
Set the channel value.
setConnectTimeout(int) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setConnectTimeout(int) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setDatabase(String) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setDatabase(String) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setDays(int) - Method in class io.reactiverse.pgclient.data.Interval
 
setEnabledSecureTransportProtocols(Set<String>) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setHost(String) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setHost(String) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setHostnameVerificationAlgorithm(String) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setHostnameVerificationAlgorithm(String) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setHours(int) - Method in class io.reactiverse.pgclient.data.Interval
 
setIdleTimeout(int) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setIdleTimeout(int) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setJdkSslEngineOptions(JdkSSLEngineOptions) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setJdkSslEngineOptions(JdkSSLEngineOptions) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setKeyCertOptions(KeyCertOptions) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setKeyCertOptions(KeyCertOptions) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setKeyStoreOptions(JksOptions) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setKeyStoreOptions(JksOptions) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setLocalAddress(String) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setLocalAddress(String) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setLogActivity(boolean) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setLogActivity(boolean) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setLowerLeftCorner(Point) - Method in class io.reactiverse.pgclient.data.Box
 
setMaxSize(int) - Method in class io.reactiverse.pgclient.PgPoolOptions
Set the maximum pool size
setMaxWaitQueueSize(int) - Method in class io.reactiverse.pgclient.PgPoolOptions
Set the maximum connection request allowed in the wait queue, any requests beyond the max size will result in an failure.
setMetricsName(String) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setMetricsName(String) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setMicroseconds(int) - Method in class io.reactiverse.pgclient.data.Interval
 
setMinutes(int) - Method in class io.reactiverse.pgclient.data.Interval
 
setMonths(int) - Method in class io.reactiverse.pgclient.data.Interval
 
setOpen(boolean) - Method in class io.reactiverse.pgclient.data.Path
 
setOpenSslEngineOptions(OpenSSLEngineOptions) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setOpenSslEngineOptions(OpenSSLEngineOptions) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setP1(Point) - Method in class io.reactiverse.pgclient.data.LineSegment
 
setP2(Point) - Method in class io.reactiverse.pgclient.data.LineSegment
 
setPassword(String) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setPassword(String) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setPayload(String) - Method in class io.reactiverse.pgclient.PgNotification
Set the payload value.
setPemKeyCertOptions(PemKeyCertOptions) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setPemKeyCertOptions(PemKeyCertOptions) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setPemTrustOptions(PemTrustOptions) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setPemTrustOptions(PemTrustOptions) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setPfxKeyCertOptions(PfxOptions) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setPfxKeyCertOptions(PfxOptions) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setPfxTrustOptions(PfxOptions) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setPfxTrustOptions(PfxOptions) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setPipeliningLimit(int) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setPipeliningLimit(int) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setPoints(List<Point>) - Method in class io.reactiverse.pgclient.data.Path
 
setPoints(List<Point>) - Method in class io.reactiverse.pgclient.data.Polygon
 
setPort(int) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setPort(int) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setProcessId(int) - Method in class io.reactiverse.pgclient.PgNotification
Set the process id.
setProxyOptions(ProxyOptions) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setProxyOptions(ProxyOptions) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setRadius(double) - Method in class io.reactiverse.pgclient.data.Circle
 
setReceiveBufferSize(int) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setReceiveBufferSize(int) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setReconnectAttempts(int) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setReconnectAttempts(int) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setReconnectInterval(long) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setReconnectInterval(long) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setReuseAddress(boolean) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setReuseAddress(boolean) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setReusePort(boolean) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setReusePort(boolean) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setSeconds(int) - Method in class io.reactiverse.pgclient.data.Interval
 
setSendBufferSize(int) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setSendBufferSize(int) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setSoLinger(int) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setSoLinger(int) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setSsl(boolean) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setSsl(boolean) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setSslEngineOptions(SSLEngineOptions) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setSslEngineOptions(SSLEngineOptions) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setSslMode(SslMode) - Method in class io.reactiverse.pgclient.PgConnectOptions
Set SslMode for the client, this option can be used to provide different levels of secure protection.
setSslMode(SslMode) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setTcpCork(boolean) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setTcpCork(boolean) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setTcpFastOpen(boolean) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setTcpFastOpen(boolean) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setTcpKeepAlive(boolean) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setTcpKeepAlive(boolean) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setTcpNoDelay(boolean) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setTcpNoDelay(boolean) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setTcpQuickAck(boolean) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setTcpQuickAck(boolean) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setTrafficClass(int) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setTrafficClass(int) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setTrustAll(boolean) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setTrustAll(boolean) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setTrustOptions(TrustOptions) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setTrustOptions(TrustOptions) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setTrustStoreOptions(JksOptions) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setTrustStoreOptions(JksOptions) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setUpperRightCorner(Point) - Method in class io.reactiverse.pgclient.data.Box
 
setUseAlpn(boolean) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setUseAlpn(boolean) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setUsePooledBuffers(boolean) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setUsePooledBuffers(boolean) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setUser(String) - Method in class io.reactiverse.pgclient.PgConnectOptions
 
setUser(String) - Method in class io.reactiverse.pgclient.PgPoolOptions
 
setX(double) - Method in class io.reactiverse.pgclient.data.Point
 
setY(double) - Method in class io.reactiverse.pgclient.data.Point
 
setYears(int) - Method in class io.reactiverse.pgclient.data.Interval
 
shortValue() - Method in class io.reactiverse.pgclient.data.Numeric
 
size() - Method in interface io.reactiverse.pgclient.PgResult
Get the number of rows in the PgResult.
size() - Method in interface io.reactiverse.pgclient.Tuple
 
size() - Method in class io.reactiverse.reactivex.pgclient.PgResult
Get the number of rows in the PgResult.
size() - Method in class io.reactiverse.reactivex.pgclient.Tuple
 
size() - Method in class io.reactiverse.rxjava.pgclient.PgResult
Get the number of rows in the PgResult.
size() - Method in class io.reactiverse.rxjava.pgclient.Tuple
 
SslMode - Enum in io.reactiverse.pgclient
The different values for the sslmode parameter provide different levels of protection.
subscribeHandler(Handler<Void>) - Method in interface io.reactiverse.pgclient.pubsub.PgChannel
Set an handler called when the the channel get subscribed.
subscribeHandler(Handler<Void>) - Method in class io.reactiverse.reactivex.pgclient.pubsub.PgChannel
Set an handler called when the the channel get subscribed.
subscribeHandler(Handler<Void>) - Method in class io.reactiverse.rxjava.pgclient.pubsub.PgChannel
Set an handler called when the the channel get subscribed.
subscriber(Vertx, PgConnectOptions) - Static method in interface io.reactiverse.pgclient.pubsub.PgSubscriber
Create a subscriber.
subscriber(Vertx, PgConnectOptions) - Static method in class io.reactiverse.reactivex.pgclient.pubsub.PgSubscriber
Create a subscriber.
subscriber(Vertx, PgConnectOptions) - Static method in class io.reactiverse.rxjava.pgclient.pubsub.PgSubscriber
Create a subscriber.

T

toFlowable() - Method in class io.reactiverse.reactivex.pgclient.PgStream
 
toFlowable() - Method in class io.reactiverse.reactivex.pgclient.pubsub.PgChannel
 
toJson() - Method in class io.reactiverse.pgclient.data.Box
 
toJson(Box, JsonObject) - Static method in class io.reactiverse.pgclient.data.BoxConverter
 
toJson(Box, Map<String, Object>) - Static method in class io.reactiverse.pgclient.data.BoxConverter
 
toJson() - Method in class io.reactiverse.pgclient.data.Circle
 
toJson(Circle, JsonObject) - Static method in class io.reactiverse.pgclient.data.CircleConverter
 
toJson(Circle, Map<String, Object>) - Static method in class io.reactiverse.pgclient.data.CircleConverter
 
toJson() - Method in class io.reactiverse.pgclient.data.Interval
 
toJson(Interval, JsonObject) - Static method in class io.reactiverse.pgclient.data.IntervalConverter
 
toJson(Interval, Map<String, Object>) - Static method in class io.reactiverse.pgclient.data.IntervalConverter
 
toJson() - Method in class io.reactiverse.pgclient.data.Line
 
toJson(Line, JsonObject) - Static method in class io.reactiverse.pgclient.data.LineConverter
 
toJson(Line, Map<String, Object>) - Static method in class io.reactiverse.pgclient.data.LineConverter
 
toJson() - Method in class io.reactiverse.pgclient.data.LineSegment
 
toJson(LineSegment, JsonObject) - Static method in class io.reactiverse.pgclient.data.LineSegmentConverter
 
toJson(LineSegment, Map<String, Object>) - Static method in class io.reactiverse.pgclient.data.LineSegmentConverter
 
toJson() - Method in class io.reactiverse.pgclient.data.Path
 
toJson(Path, JsonObject) - Static method in class io.reactiverse.pgclient.data.PathConverter
 
toJson(Path, Map<String, Object>) - Static method in class io.reactiverse.pgclient.data.PathConverter
 
toJson() - Method in class io.reactiverse.pgclient.data.Point
 
toJson(Point, JsonObject) - Static method in class io.reactiverse.pgclient.data.PointConverter
 
toJson(Point, Map<String, Object>) - Static method in class io.reactiverse.pgclient.data.PointConverter
 
toJson() - Method in class io.reactiverse.pgclient.data.Polygon
 
toJson(Polygon, JsonObject) - Static method in class io.reactiverse.pgclient.data.PolygonConverter
 
toJson(Polygon, Map<String, Object>) - Static method in class io.reactiverse.pgclient.data.PolygonConverter
 
toJson() - Method in class io.reactiverse.pgclient.PgConnectOptions
 
toJson(PgConnectOptions, JsonObject) - Static method in class io.reactiverse.pgclient.PgConnectOptionsConverter
 
toJson(PgConnectOptions, Map<String, Object>) - Static method in class io.reactiverse.pgclient.PgConnectOptionsConverter
 
toJson() - Method in class io.reactiverse.pgclient.PgNotification
 
toJson(PgNotification, JsonObject) - Static method in class io.reactiverse.pgclient.PgNotificationConverter
 
toJson(PgNotification, Map<String, Object>) - Static method in class io.reactiverse.pgclient.PgNotificationConverter
 
toJson() - Method in class io.reactiverse.pgclient.PgPoolOptions
 
toJson(PgPoolOptions, JsonObject) - Static method in class io.reactiverse.pgclient.PgPoolOptionsConverter
 
toJson(PgPoolOptions, Map<String, Object>) - Static method in class io.reactiverse.pgclient.PgPoolOptionsConverter
 
toObservable() - Method in class io.reactiverse.reactivex.pgclient.PgStream
 
toObservable() - Method in class io.reactiverse.reactivex.pgclient.pubsub.PgChannel
 
toObservable() - Method in class io.reactiverse.rxjava.pgclient.PgStream
 
toObservable() - Method in class io.reactiverse.rxjava.pgclient.pubsub.PgChannel
 
toString() - Method in class io.reactiverse.pgclient.data.Box
 
toString() - Method in class io.reactiverse.pgclient.data.Circle
 
toString() - Method in class io.reactiverse.pgclient.data.Interval
 
toString() - Method in class io.reactiverse.pgclient.data.Line
 
toString() - Method in class io.reactiverse.pgclient.data.LineSegment
 
toString() - Method in class io.reactiverse.pgclient.data.Numeric
 
toString() - Method in class io.reactiverse.pgclient.data.Path
 
toString() - Method in class io.reactiverse.pgclient.data.Point
 
toString() - Method in class io.reactiverse.pgclient.data.Polygon
 
toString() - Method in class io.reactiverse.reactivex.pgclient.data.Json
 
toString() - Method in class io.reactiverse.reactivex.pgclient.PgClient
 
toString() - Method in class io.reactiverse.reactivex.pgclient.PgConnection
 
toString() - Method in class io.reactiverse.reactivex.pgclient.PgCursor
 
toString() - Method in class io.reactiverse.reactivex.pgclient.PgIterator
 
toString() - Method in class io.reactiverse.reactivex.pgclient.PgPool
 
toString() - Method in class io.reactiverse.reactivex.pgclient.PgPreparedQuery
 
toString() - Method in class io.reactiverse.reactivex.pgclient.PgResult
 
toString() - Method in class io.reactiverse.reactivex.pgclient.PgRowSet
 
toString() - Method in class io.reactiverse.reactivex.pgclient.PgStream
 
toString() - Method in class io.reactiverse.reactivex.pgclient.PgTransaction
 
toString() - Method in class io.reactiverse.reactivex.pgclient.pubsub.PgChannel
 
toString() - Method in class io.reactiverse.reactivex.pgclient.pubsub.PgSubscriber
 
toString() - Method in class io.reactiverse.reactivex.pgclient.Row
 
toString() - Method in class io.reactiverse.reactivex.pgclient.Tuple
 
toString() - Method in class io.reactiverse.rxjava.pgclient.data.Json
 
toString() - Method in class io.reactiverse.rxjava.pgclient.PgClient
 
toString() - Method in class io.reactiverse.rxjava.pgclient.PgConnection
 
toString() - Method in class io.reactiverse.rxjava.pgclient.PgCursor
 
toString() - Method in class io.reactiverse.rxjava.pgclient.PgIterator
 
toString() - Method in class io.reactiverse.rxjava.pgclient.PgPool
 
toString() - Method in class io.reactiverse.rxjava.pgclient.PgPreparedQuery
 
toString() - Method in class io.reactiverse.rxjava.pgclient.PgResult
 
toString() - Method in class io.reactiverse.rxjava.pgclient.PgRowSet
 
toString() - Method in class io.reactiverse.rxjava.pgclient.PgStream
 
toString() - Method in class io.reactiverse.rxjava.pgclient.PgTransaction
 
toString() - Method in class io.reactiverse.rxjava.pgclient.pubsub.PgChannel
 
toString() - Method in class io.reactiverse.rxjava.pgclient.pubsub.PgSubscriber
 
toString() - Method in class io.reactiverse.rxjava.pgclient.Row
 
toString() - Method in class io.reactiverse.rxjava.pgclient.Tuple
 
Tuple - Interface in io.reactiverse.pgclient
A general purpose tuple.
tuple() - Static method in interface io.reactiverse.pgclient.Tuple
 
Tuple - Class in io.reactiverse.reactivex.pgclient
A general purpose tuple.
Tuple(Tuple) - Constructor for class io.reactiverse.reactivex.pgclient.Tuple
 
tuple() - Static method in class io.reactiverse.reactivex.pgclient.Tuple
 
Tuple - Class in io.reactiverse.rxjava.pgclient
A general purpose tuple.
Tuple(Tuple) - Constructor for class io.reactiverse.rxjava.pgclient.Tuple
 
tuple() - Static method in class io.reactiverse.rxjava.pgclient.Tuple
 

V

value() - Method in interface io.reactiverse.pgclient.data.Json
 
value() - Method in interface io.reactiverse.pgclient.PgResult
Get the result value.
value - Variable in enum io.reactiverse.pgclient.SslMode
 
value() - Method in class io.reactiverse.reactivex.pgclient.data.Json
 
value() - Method in class io.reactiverse.reactivex.pgclient.PgResult
Get the result value.
value() - Method in class io.reactiverse.reactivex.pgclient.PgRowSet
Get the result value.
value() - Method in class io.reactiverse.rxjava.pgclient.data.Json
 
value() - Method in class io.reactiverse.rxjava.pgclient.PgResult
Get the result value.
value() - Method in class io.reactiverse.rxjava.pgclient.PgRowSet
Get the result value.
valueOf(String) - Static method in enum io.reactiverse.pgclient.SslMode
Returns the enum constant of this type with the specified name.
VALUES - Static variable in enum io.reactiverse.pgclient.SslMode
 
values() - Static method in enum io.reactiverse.pgclient.SslMode
Returns an array containing the constants of this enum type, in the order they are declared.

X

x - Variable in class io.reactiverse.pgclient.data.Point
 

Y

y - Variable in class io.reactiverse.pgclient.data.Point
 
years(int) - Method in class io.reactiverse.pgclient.data.Interval
 

_

__TYPE_ARG - Static variable in class io.reactiverse.reactivex.pgclient.data.Json
 
__TYPE_ARG - Static variable in class io.reactiverse.reactivex.pgclient.PgClient
 
__TYPE_ARG - Static variable in class io.reactiverse.reactivex.pgclient.PgConnection
 
__TYPE_ARG - Static variable in class io.reactiverse.reactivex.pgclient.PgCursor
 
__TYPE_ARG - Static variable in class io.reactiverse.reactivex.pgclient.PgIterator
 
__TYPE_ARG - Static variable in class io.reactiverse.reactivex.pgclient.PgPool
 
__TYPE_ARG - Static variable in class io.reactiverse.reactivex.pgclient.PgPreparedQuery
 
__TYPE_ARG - Static variable in class io.reactiverse.reactivex.pgclient.PgResult
 
__TYPE_ARG - Static variable in class io.reactiverse.reactivex.pgclient.PgRowSet
 
__TYPE_ARG - Static variable in class io.reactiverse.reactivex.pgclient.PgStream
 
__TYPE_ARG - Static variable in class io.reactiverse.reactivex.pgclient.PgTransaction
 
__TYPE_ARG - Static variable in class io.reactiverse.reactivex.pgclient.pubsub.PgChannel
 
__TYPE_ARG - Static variable in class io.reactiverse.reactivex.pgclient.pubsub.PgSubscriber
 
__TYPE_ARG - Static variable in class io.reactiverse.reactivex.pgclient.Row
 
__TYPE_ARG - Static variable in class io.reactiverse.reactivex.pgclient.Tuple
 
__TYPE_ARG - Static variable in class io.reactiverse.rxjava.pgclient.data.Json
 
__TYPE_ARG - Static variable in class io.reactiverse.rxjava.pgclient.PgClient
 
__TYPE_ARG - Static variable in class io.reactiverse.rxjava.pgclient.PgConnection
 
__TYPE_ARG - Static variable in class io.reactiverse.rxjava.pgclient.PgCursor
 
__TYPE_ARG - Static variable in class io.reactiverse.rxjava.pgclient.PgIterator
 
__TYPE_ARG - Static variable in class io.reactiverse.rxjava.pgclient.PgPool
 
__TYPE_ARG - Static variable in class io.reactiverse.rxjava.pgclient.PgPreparedQuery
 
__TYPE_ARG - Static variable in class io.reactiverse.rxjava.pgclient.PgResult
 
__TYPE_ARG - Static variable in class io.reactiverse.rxjava.pgclient.PgRowSet
 
__TYPE_ARG - Static variable in class io.reactiverse.rxjava.pgclient.PgStream
 
__TYPE_ARG - Static variable in class io.reactiverse.rxjava.pgclient.PgTransaction
 
__TYPE_ARG - Static variable in class io.reactiverse.rxjava.pgclient.pubsub.PgChannel
 
__TYPE_ARG - Static variable in class io.reactiverse.rxjava.pgclient.pubsub.PgSubscriber
 
__TYPE_ARG - Static variable in class io.reactiverse.rxjava.pgclient.Row
 
__TYPE_ARG - Static variable in class io.reactiverse.rxjava.pgclient.Tuple
 
__typeArg_0 - Variable in class io.reactiverse.reactivex.pgclient.PgResult
 
__typeArg_0 - Variable in class io.reactiverse.reactivex.pgclient.PgStream
 
__typeArg_0 - Variable in class io.reactiverse.rxjava.pgclient.PgResult
 
__typeArg_0 - Variable in class io.reactiverse.rxjava.pgclient.PgStream
 
A B C D E F G H I J L M N O P Q R S T V X Y _ 

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/index.html ================================================ Reactive Postgres Client 0.11.2 API <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <h2>Frame Alert</h2> <p>This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. Link to <a href="overview-summary.html">Non-frame version</a>.</p> ================================================ FILE: docs/apidocs/io/reactiverse/pgclient/Json.html ================================================ Json (Reactive Postgres Client 0.9.0 API)
io.reactiverse.pgclient

Interface Json



  • public interface Json

Copyright © 2018 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/JsonImpl.html ================================================ JsonImpl (Reactive Postgres Client 0.7.1-SNAPSHOT API)
io.reactiverse.pgclient

Class JsonImpl

  • All Implemented Interfaces:
    Json


    public class JsonImpl
    extends Object
    implements Json

Copyright © 2018 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/Numeric.html ================================================ Numeric (Reactive Postgres Client 0.9.0 API)
io.reactiverse.pgclient

Class Numeric

    • Field Detail

      • NaN

        public static final Numeric NaN
        Constant for the NaN value.
    • Method Detail

      • create

        public static Numeric create(Number number)
        Return a Numeric instance for the given number.

        Null values or infinite Double or Float are rejected.

        Parameters:
        number - the number
        Returns:
        the Numeric value
        Throws:
        NumberFormatException - when the number is infinite
      • parse

        public static Numeric parse(String s)
        Parse and return a Numeric instance for the given s.

        The string "Nan" will return the NaN instance.

        Parameters:
        s - the string
        Returns:
        the Numeric value
      • shortValue

        public short shortValue()
        Overrides:
        shortValue in class Number
      • intValue

        public int intValue()
        Specified by:
        intValue in class Number
      • longValue

        public long longValue()
        Specified by:
        longValue in class Number
      • floatValue

        public float floatValue()
        Specified by:
        floatValue in class Number
      • doubleValue

        public double doubleValue()
        Specified by:
        doubleValue in class Number
      • isNaN

        public boolean isNaN()
        Returns:
        true when this number represents NaN
      • bigDecimalValue

        public BigDecimal bigDecimalValue()
        Returns:
        the numeric value represented by this object after conversion to decodingType BigDecimal. It can be null when this instance represents the NaN value.
      • bigIntegerValue

        public BigInteger bigIntegerValue()
        Returns:
        the numeric value represented by this object after conversion to decodingType BigInteger. It can be null when this instance represents the NaN value.
      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Object

Copyright © 2018 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/PgClient.html ================================================ PgClient (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient

Interface PgClient

    • Method Detail

      • pool

        static PgPool pool(PgPoolOptions options)
        Create a connection pool to the database configured with the given options.
        Parameters:
        options - the options for creating the pool
        Returns:
        the connection pool
      • connect

        static void connect(io.vertx.core.Vertx vertx,
                            PgConnectOptions options,
                            io.vertx.core.Handler<io.vertx.core.AsyncResult<PgConnection>> handler)
        Connects to the database and returns the connection if that succeeds.

        The connection interracts directly with the database is not a proxy, so closing the connection will close the underlying connection to the database.

        Parameters:
        vertx - the vertx instance
        options - the connect options
        handler - the handler called with the connection or the failure
      • query

        PgClient query(String sql,
                       io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Execute a simple query.
        Parameters:
        sql - the query SQL
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • query

        <R> PgClient query(String sql,
                           Collector<Row,?,R> collector,
                           io.vertx.core.Handler<io.vertx.core.AsyncResult<PgResult<R>>> handler)
        Execute a simple query.
        Parameters:
        sql - the query SQL
        collector - the collector
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • preparedQuery

        PgClient preparedQuery(String sql,
                               io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Prepare and execute a query.
        Parameters:
        sql - the prepared query SQL
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • preparedQuery

        <R> PgClient preparedQuery(String sql,
                                   Collector<Row,?,R> collector,
                                   io.vertx.core.Handler<io.vertx.core.AsyncResult<PgResult<R>>> handler)
        Prepare and execute a query.
        Parameters:
        sql - the prepared query SQL
        collector - the collector
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • preparedQuery

        PgClient preparedQuery(String sql,
                               Tuple arguments,
                               io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Prepare and execute a query.
        Parameters:
        sql - the prepared query SQL
        arguments - the list of arguments
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • preparedQuery

        <R> PgClient preparedQuery(String sql,
                                   Tuple arguments,
                                   Collector<Row,?,R> collector,
                                   io.vertx.core.Handler<io.vertx.core.AsyncResult<PgResult<R>>> handler)
        Prepare and execute a query.
        Parameters:
        sql - the prepared query SQL
        arguments - the list of arguments
        collector - the collector
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • preparedBatch

        PgClient preparedBatch(String sql,
                               List<Tuple> batch,
                               io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Prepare and execute a createBatch.
        Parameters:
        sql - the prepared query SQL
        batch - the batch of tuples
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • preparedBatch

        <R> PgClient preparedBatch(String sql,
                                   List<Tuple> batch,
                                   Collector<Row,?,R> collector,
                                   io.vertx.core.Handler<io.vertx.core.AsyncResult<PgResult<R>>> handler)
        Prepare and execute a createBatch.
        Parameters:
        sql - the prepared query SQL
        batch - the batch of tuples
        collector - the collector
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/PgConnectOptions.html ================================================ PgConnectOptions (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient

Class PgConnectOptions

  • Direct Known Subclasses:
    PgPoolOptions


    public class PgConnectOptions
    extends io.vertx.core.net.NetClientOptions
    Author:
    Julien Viet, Billy Yuan
    • Constructor Detail

      • PgConnectOptions

        public PgConnectOptions()
      • PgConnectOptions

        public PgConnectOptions(io.vertx.core.json.JsonObject json)
    • Method Detail

      • fromEnv

        public static PgConnectOptions fromEnv()
        Provide a PgConnectOptions configured with environment variables, if the environment variable is not set, then a default value will take precedence over this.
      • getHost

        public String getHost()
      • getPort

        public int getPort()
      • getDatabase

        public String getDatabase()
      • getUser

        public String getUser()
      • getPassword

        public String getPassword()
      • getPipeliningLimit

        public int getPipeliningLimit()
      • setPipeliningLimit

        public PgConnectOptions setPipeliningLimit(int pipeliningLimit)
      • getCachePreparedStatements

        public boolean getCachePreparedStatements()
      • setCachePreparedStatements

        public PgConnectOptions setCachePreparedStatements(boolean cachePreparedStatements)
      • getSslMode

        public SslMode getSslMode()
        Returns:
        the value of current sslmode
      • setSslMode

        public PgConnectOptions setSslMode(SslMode sslmode)
        Set SslMode for the client, this option can be used to provide different levels of secure protection.
        Parameters:
        sslmode - the value of sslmode
        Returns:
        a reference to this, so the API can be used fluently
      • setSendBufferSize

        public PgConnectOptions setSendBufferSize(int sendBufferSize)
        Overrides:
        setSendBufferSize in class io.vertx.core.net.NetClientOptions
      • setReceiveBufferSize

        public PgConnectOptions setReceiveBufferSize(int receiveBufferSize)
        Overrides:
        setReceiveBufferSize in class io.vertx.core.net.NetClientOptions
      • setReuseAddress

        public PgConnectOptions setReuseAddress(boolean reuseAddress)
        Overrides:
        setReuseAddress in class io.vertx.core.net.NetClientOptions
      • setTrafficClass

        public PgConnectOptions setTrafficClass(int trafficClass)
        Overrides:
        setTrafficClass in class io.vertx.core.net.NetClientOptions
      • setTcpNoDelay

        public PgConnectOptions setTcpNoDelay(boolean tcpNoDelay)
        Overrides:
        setTcpNoDelay in class io.vertx.core.net.NetClientOptions
      • setTcpKeepAlive

        public PgConnectOptions setTcpKeepAlive(boolean tcpKeepAlive)
        Overrides:
        setTcpKeepAlive in class io.vertx.core.net.NetClientOptions
      • setSoLinger

        public PgConnectOptions setSoLinger(int soLinger)
        Overrides:
        setSoLinger in class io.vertx.core.net.NetClientOptions
      • setUsePooledBuffers

        public PgConnectOptions setUsePooledBuffers(boolean usePooledBuffers)
        Overrides:
        setUsePooledBuffers in class io.vertx.core.net.NetClientOptions
      • setIdleTimeout

        public PgConnectOptions setIdleTimeout(int idleTimeout)
        Overrides:
        setIdleTimeout in class io.vertx.core.net.NetClientOptions
      • setSsl

        public PgConnectOptions setSsl(boolean ssl)
        Overrides:
        setSsl in class io.vertx.core.net.NetClientOptions
      • setKeyCertOptions

        public PgConnectOptions setKeyCertOptions(io.vertx.core.net.KeyCertOptions options)
        Overrides:
        setKeyCertOptions in class io.vertx.core.net.NetClientOptions
      • setKeyStoreOptions

        public PgConnectOptions setKeyStoreOptions(io.vertx.core.net.JksOptions options)
        Overrides:
        setKeyStoreOptions in class io.vertx.core.net.NetClientOptions
      • setPfxKeyCertOptions

        public PgConnectOptions setPfxKeyCertOptions(io.vertx.core.net.PfxOptions options)
        Overrides:
        setPfxKeyCertOptions in class io.vertx.core.net.NetClientOptions
      • setPemKeyCertOptions

        public PgConnectOptions setPemKeyCertOptions(io.vertx.core.net.PemKeyCertOptions options)
        Overrides:
        setPemKeyCertOptions in class io.vertx.core.net.NetClientOptions
      • setTrustOptions

        public PgConnectOptions setTrustOptions(io.vertx.core.net.TrustOptions options)
        Overrides:
        setTrustOptions in class io.vertx.core.net.NetClientOptions
      • setTrustStoreOptions

        public PgConnectOptions setTrustStoreOptions(io.vertx.core.net.JksOptions options)
        Overrides:
        setTrustStoreOptions in class io.vertx.core.net.NetClientOptions
      • setPemTrustOptions

        public PgConnectOptions setPemTrustOptions(io.vertx.core.net.PemTrustOptions options)
        Overrides:
        setPemTrustOptions in class io.vertx.core.net.NetClientOptions
      • setPfxTrustOptions

        public PgConnectOptions setPfxTrustOptions(io.vertx.core.net.PfxOptions options)
        Overrides:
        setPfxTrustOptions in class io.vertx.core.net.NetClientOptions
      • addEnabledCipherSuite

        public PgConnectOptions addEnabledCipherSuite(String suite)
        Overrides:
        addEnabledCipherSuite in class io.vertx.core.net.NetClientOptions
      • addEnabledSecureTransportProtocol

        public PgConnectOptions addEnabledSecureTransportProtocol(String protocol)
        Overrides:
        addEnabledSecureTransportProtocol in class io.vertx.core.net.NetClientOptions
      • setTrustAll

        public PgConnectOptions setTrustAll(boolean trustAll)
        Overrides:
        setTrustAll in class io.vertx.core.net.NetClientOptions
      • setConnectTimeout

        public PgConnectOptions setConnectTimeout(int connectTimeout)
        Overrides:
        setConnectTimeout in class io.vertx.core.net.NetClientOptions
      • setMetricsName

        public PgConnectOptions setMetricsName(String metricsName)
        Overrides:
        setMetricsName in class io.vertx.core.net.NetClientOptions
      • setReconnectAttempts

        public PgConnectOptions setReconnectAttempts(int attempts)
        Overrides:
        setReconnectAttempts in class io.vertx.core.net.NetClientOptions
      • setHostnameVerificationAlgorithm

        public PgConnectOptions setHostnameVerificationAlgorithm(String hostnameVerificationAlgorithm)
        Overrides:
        setHostnameVerificationAlgorithm in class io.vertx.core.net.NetClientOptions
      • setLogActivity

        public PgConnectOptions setLogActivity(boolean logEnabled)
        Overrides:
        setLogActivity in class io.vertx.core.net.NetClientOptions
      • setReconnectInterval

        public PgConnectOptions setReconnectInterval(long interval)
        Overrides:
        setReconnectInterval in class io.vertx.core.net.NetClientOptions
      • setProxyOptions

        public PgConnectOptions setProxyOptions(io.vertx.core.net.ProxyOptions proxyOptions)
        Overrides:
        setProxyOptions in class io.vertx.core.net.NetClientOptions
      • setLocalAddress

        public PgConnectOptions setLocalAddress(String localAddress)
        Overrides:
        setLocalAddress in class io.vertx.core.net.NetClientOptions
      • setUseAlpn

        public PgConnectOptions setUseAlpn(boolean useAlpn)
        Overrides:
        setUseAlpn in class io.vertx.core.net.NetClientOptions
      • setSslEngineOptions

        public PgConnectOptions setSslEngineOptions(io.vertx.core.net.SSLEngineOptions sslEngineOptions)
        Overrides:
        setSslEngineOptions in class io.vertx.core.net.NetClientOptions
      • setJdkSslEngineOptions

        public PgConnectOptions setJdkSslEngineOptions(io.vertx.core.net.JdkSSLEngineOptions sslEngineOptions)
        Overrides:
        setJdkSslEngineOptions in class io.vertx.core.net.NetClientOptions
      • setOpenSslEngineOptions

        public PgConnectOptions setOpenSslEngineOptions(io.vertx.core.net.OpenSSLEngineOptions sslEngineOptions)
        Overrides:
        setOpenSslEngineOptions in class io.vertx.core.net.NetClientOptions
      • setReusePort

        public PgConnectOptions setReusePort(boolean reusePort)
        Overrides:
        setReusePort in class io.vertx.core.net.NetClientOptions
      • setTcpFastOpen

        public PgConnectOptions setTcpFastOpen(boolean tcpFastOpen)
        Overrides:
        setTcpFastOpen in class io.vertx.core.net.NetClientOptions
      • setTcpCork

        public PgConnectOptions setTcpCork(boolean tcpCork)
        Overrides:
        setTcpCork in class io.vertx.core.net.NetClientOptions
      • setTcpQuickAck

        public PgConnectOptions setTcpQuickAck(boolean tcpQuickAck)
        Overrides:
        setTcpQuickAck in class io.vertx.core.net.NetClientOptions
      • setEnabledSecureTransportProtocols

        public PgConnectOptions setEnabledSecureTransportProtocols(Set<String> enabledSecureTransportProtocols)
        Overrides:
        setEnabledSecureTransportProtocols in class io.vertx.core.net.NetClientOptions
      • toJson

        public io.vertx.core.json.JsonObject toJson()
        Overrides:
        toJson in class io.vertx.core.net.ClientOptionsBase
      • equals

        public boolean equals(Object o)
        Overrides:
        equals in class io.vertx.core.net.NetClientOptions
      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class io.vertx.core.net.NetClientOptions
      • isUsingDomainSocket

        public boolean isUsingDomainSocket()

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/PgConnectOptionsConverter.html ================================================ PgConnectOptionsConverter (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient

Class PgConnectOptionsConverter



  • public class PgConnectOptionsConverter
    extends Object
    Converter for PgConnectOptions. NOTE: This class has been automatically generated from the PgConnectOptions original class using Vert.x codegen.

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/PgConnection.html ================================================ PgConnection (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient

Interface PgConnection

    • Method Detail

      • prepare

        PgConnection prepare(String sql,
                             io.vertx.core.Handler<io.vertx.core.AsyncResult<PgPreparedQuery>> handler)
        Create a prepared query.
        Parameters:
        sql - the sql
        handler - the handler notified with the prepared query asynchronously
      • exceptionHandler

        PgConnection exceptionHandler(io.vertx.core.Handler<Throwable> handler)
        Set an handler called with connection errors.
        Parameters:
        handler - the handler
        Returns:
        a reference to this, so the API can be used fluently
      • closeHandler

        PgConnection closeHandler(io.vertx.core.Handler<Void> handler)
        Set an handler called when the connection is closed.
        Parameters:
        handler - the handler
        Returns:
        a reference to this, so the API can be used fluently
      • begin

        PgTransaction begin()
        Begin a transaction and returns a PgTransaction for controlling and tracking this transaction.

        When the connection is explicitely closed, any inflight transaction is rollbacked.

        Returns:
        the transaction instance
      • notificationHandler

        PgConnection notificationHandler(io.vertx.core.Handler<PgNotification> handler)
        Set an handler called when the connection receives notification on a channel.

        The handler is called with the PgNotification and has access to the channel name and the notification payload.

        Parameters:
        handler - the handler
        Returns:
        the transaction instance
      • processId

        int processId()
        Returns:
        The process ID of the target backend
      • secretKey

        int secretKey()
        Returns:
        The secret key for the target backend
      • cancelRequest

        PgConnection cancelRequest(io.vertx.core.Handler<io.vertx.core.AsyncResult<Void>> handler)
        Send a request cancellation message to tell the server to cancel processing request in this connection.
        Note: Use this with caution because the cancellation signal may or may not have any effect.
        Parameters:
        handler - the handler notified if cancelling request is sent
        Returns:
        a reference to this, so the API can be used fluently
      • isSSL

        boolean isSSL()
        Returns:
        whether the connection uses SSL
      • close

        void close()
        Close the current connection after all the pending commands have been processed.
      • preparedQuery

        PgConnection preparedQuery(String sql,
                                   io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from interface: PgClient
        Prepare and execute a query.
        Specified by:
        preparedQuery in interface PgClient
        Parameters:
        sql - the prepared query SQL
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • preparedQuery

        <R> PgConnection preparedQuery(String sql,
                                       Collector<Row,?,R> collector,
                                       io.vertx.core.Handler<io.vertx.core.AsyncResult<PgResult<R>>> handler)
        Description copied from interface: PgClient
        Prepare and execute a query.
        Specified by:
        preparedQuery in interface PgClient
        Parameters:
        sql - the prepared query SQL
        collector - the collector
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • query

        PgConnection query(String sql,
                           io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from interface: PgClient
        Execute a simple query.
        Specified by:
        query in interface PgClient
        Parameters:
        sql - the query SQL
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • query

        <R> PgConnection query(String sql,
                               Collector<Row,?,R> collector,
                               io.vertx.core.Handler<io.vertx.core.AsyncResult<PgResult<R>>> handler)
        Description copied from interface: PgClient
        Execute a simple query.
        Specified by:
        query in interface PgClient
        Parameters:
        sql - the query SQL
        collector - the collector
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • preparedQuery

        PgConnection preparedQuery(String sql,
                                   Tuple arguments,
                                   io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from interface: PgClient
        Prepare and execute a query.
        Specified by:
        preparedQuery in interface PgClient
        Parameters:
        sql - the prepared query SQL
        arguments - the list of arguments
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • preparedQuery

        <R> PgConnection preparedQuery(String sql,
                                       Tuple arguments,
                                       Collector<Row,?,R> collector,
                                       io.vertx.core.Handler<io.vertx.core.AsyncResult<PgResult<R>>> handler)
        Description copied from interface: PgClient
        Prepare and execute a query.
        Specified by:
        preparedQuery in interface PgClient
        Parameters:
        sql - the prepared query SQL
        arguments - the list of arguments
        collector - the collector
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • preparedBatch

        PgConnection preparedBatch(String sql,
                                   List<Tuple> batch,
                                   io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from interface: PgClient
        Prepare and execute a createBatch.
        Specified by:
        preparedBatch in interface PgClient
        Parameters:
        sql - the prepared query SQL
        batch - the batch of tuples
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • preparedBatch

        <R> PgConnection preparedBatch(String sql,
                                       List<Tuple> batch,
                                       Collector<Row,?,R> collector,
                                       io.vertx.core.Handler<io.vertx.core.AsyncResult<PgResult<R>>> handler)
        Description copied from interface: PgClient
        Prepare and execute a createBatch.
        Specified by:
        preparedBatch in interface PgClient
        Parameters:
        sql - the prepared query SQL
        batch - the batch of tuples
        collector - the collector
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/PgCursor.html ================================================ PgCursor (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient

Interface PgCursor



  • public interface PgCursor
    A cursor that reads progressively the rows from Postgres, it is usefull for reading very large result.
    • Method Summary

      All Methods Instance Methods Abstract Methods Default Methods 
      Modifier and Type Method and Description
      default void close()
      Release the cursor.
      void close(io.vertx.core.Handler<io.vertx.core.AsyncResult<Void>> completionHandler)
      Like close() but with a completionHandler called when the cursor has been released.
      boolean hasMore()
      Returns true when the cursor has results in progress and the #execute should be called to retrieve them.
      void read(int count, io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
      Read rows from the cursor, the result is provided asynchronously to the handler.
    • Method Detail

      • read

        void read(int count,
                  io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Read rows from the cursor, the result is provided asynchronously to the handler.
        Parameters:
        count - the amount of rows to read
        handler - the handler for the result
      • hasMore

        boolean hasMore()
        Returns true when the cursor has results in progress and the #execute should be called to retrieve them.
        Returns:
        whether the cursor has more results,
      • close

        default void close()
        Release the cursor.

        It should be called for prepared queries executed with a fetch size.

      • close

        void close(io.vertx.core.Handler<io.vertx.core.AsyncResult<Void>> completionHandler)
        Like close() but with a completionHandler called when the cursor has been released.

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/PgException.html ================================================ PgException (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient

Class PgException

    • Constructor Detail

      • PgException

        public PgException(io.reactiverse.pgclient.impl.codec.decoder.ErrorResponse error)
    • Method Detail

      • getSeverity

        public String getSeverity()
      • getCode

        public String getCode()
      • getDetail

        public String getDetail()
        Returns:
        the detail error message

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/PgIterator.html ================================================ PgIterator (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient

Interface PgIterator

  • All Superinterfaces:
    Iterator<Row>


    public interface PgIterator
    extends Iterator<Row>
    An iterator for processing postgres items synchronously.

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/PgNotification.html ================================================ PgNotification (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient

Class PgNotification



  • public class PgNotification
    extends Object
    A notification emited by Postgres.
    • Constructor Detail

      • PgNotification

        public PgNotification()
      • PgNotification

        public PgNotification(io.vertx.core.json.JsonObject json)
    • Method Detail

      • getProcessId

        public int getProcessId()
        Returns:
        the notification process id
      • setProcessId

        public PgNotification setProcessId(int processId)
        Set the process id.
        Returns:
        a reference to this, so the API can be used fluently
      • getChannel

        public String getChannel()
        Returns:
        the notification channel value
      • setChannel

        public PgNotification setChannel(String channel)
        Set the channel value.
        Returns:
        a reference to this, so the API can be used fluently
      • getPayload

        public String getPayload()
        Returns:
        the notification payload value
      • setPayload

        public PgNotification setPayload(String payload)
        Set the payload value.
        Returns:
        a reference to this, so the API can be used fluently
      • toJson

        public io.vertx.core.json.JsonObject toJson()

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/PgNotificationConverter.html ================================================ PgNotificationConverter (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient

Class PgNotificationConverter



  • public class PgNotificationConverter
    extends Object
    Converter for PgNotification. NOTE: This class has been automatically generated from the PgNotification original class using Vert.x codegen.

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/PgPool.html ================================================ PgPool (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient

Interface PgPool

    • Method Detail

      • preparedQuery

        PgPool preparedQuery(String sql,
                             io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from interface: PgClient
        Prepare and execute a query.
        Specified by:
        preparedQuery in interface PgClient
        Parameters:
        sql - the prepared query SQL
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • preparedQuery

        <R> PgPool preparedQuery(String sql,
                                 Collector<Row,?,R> collector,
                                 io.vertx.core.Handler<io.vertx.core.AsyncResult<PgResult<R>>> handler)
        Description copied from interface: PgClient
        Prepare and execute a query.
        Specified by:
        preparedQuery in interface PgClient
        Parameters:
        sql - the prepared query SQL
        collector - the collector
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • query

        PgPool query(String sql,
                     io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from interface: PgClient
        Execute a simple query.
        Specified by:
        query in interface PgClient
        Parameters:
        sql - the query SQL
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • query

        <R> PgPool query(String sql,
                         Collector<Row,?,R> collector,
                         io.vertx.core.Handler<io.vertx.core.AsyncResult<PgResult<R>>> handler)
        Description copied from interface: PgClient
        Execute a simple query.
        Specified by:
        query in interface PgClient
        Parameters:
        sql - the query SQL
        collector - the collector
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • preparedQuery

        PgPool preparedQuery(String sql,
                             Tuple arguments,
                             io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from interface: PgClient
        Prepare and execute a query.
        Specified by:
        preparedQuery in interface PgClient
        Parameters:
        sql - the prepared query SQL
        arguments - the list of arguments
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • preparedQuery

        <R> PgPool preparedQuery(String sql,
                                 Tuple arguments,
                                 Collector<Row,?,R> collector,
                                 io.vertx.core.Handler<io.vertx.core.AsyncResult<PgResult<R>>> handler)
        Description copied from interface: PgClient
        Prepare and execute a query.
        Specified by:
        preparedQuery in interface PgClient
        Parameters:
        sql - the prepared query SQL
        arguments - the list of arguments
        collector - the collector
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • preparedBatch

        PgPool preparedBatch(String sql,
                             List<Tuple> batch,
                             io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from interface: PgClient
        Prepare and execute a createBatch.
        Specified by:
        preparedBatch in interface PgClient
        Parameters:
        sql - the prepared query SQL
        batch - the batch of tuples
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • preparedBatch

        <R> PgPool preparedBatch(String sql,
                                 List<Tuple> batch,
                                 Collector<Row,?,R> collector,
                                 io.vertx.core.Handler<io.vertx.core.AsyncResult<PgResult<R>>> handler)
        Description copied from interface: PgClient
        Prepare and execute a createBatch.
        Specified by:
        preparedBatch in interface PgClient
        Parameters:
        sql - the prepared query SQL
        batch - the batch of tuples
        collector - the collector
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • getConnection

        void getConnection(io.vertx.core.Handler<io.vertx.core.AsyncResult<PgConnection>> handler)
        Get a connection from the pool.
        Parameters:
        handler - the handler that will get the connection result
      • begin

        void begin(io.vertx.core.Handler<io.vertx.core.AsyncResult<PgTransaction>> handler)
        Borrow a connection from the pool and begin a transaction, the underlying connection will be returned to the pool when the transaction ends.
      • close

        void close()
        Close the pool and release the associated resources.

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/PgPoolOptions.html ================================================ PgPoolOptions (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient

Class PgPoolOptions

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/PgPoolOptionsConverter.html ================================================ PgPoolOptionsConverter (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient

Class PgPoolOptionsConverter



  • public class PgPoolOptionsConverter
    extends Object
    Converter for PgPoolOptions. NOTE: This class has been automatically generated from the PgPoolOptions original class using Vert.x codegen.

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/PgPreparedQuery.html ================================================ PgPreparedQuery (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient

Interface PgPreparedQuery



  • public interface PgPreparedQuery
    A prepared query.
    Author:
    Julien Viet
    • Method Detail

      • execute

        PgPreparedQuery execute(Tuple args,
                                io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Create a cursor with the provided arguments.
        Parameters:
        args - the list of arguments
        Returns:
        the query
      • execute

        <R> PgPreparedQuery execute(Tuple args,
                                    Collector<Row,?,R> collector,
                                    io.vertx.core.Handler<io.vertx.core.AsyncResult<PgResult<R>>> handler)
        Create a cursor with the provided arguments.
        Parameters:
        args - the list of arguments
        collector - the collector
        Returns:
        the query
      • cursor

        default PgCursor cursor()
        Returns:
        create a query cursor with a fetch size and empty arguments
      • cursor

        PgCursor cursor(Tuple args)
        Create a cursor with the provided arguments.
        Parameters:
        args - the list of arguments
        Returns:
        the query
      • createStream

        PgStream<Row> createStream(int fetch,
                                   Tuple args)
        Execute the prepared query with a cursor and createStream the result. The createStream opens a cursor with a fetch size to fetch the results.

        Note: this requires to be in a transaction, since cursors require it.

        Parameters:
        fetch - the cursor fetch size
        args - the prepared query arguments
        Returns:
        the createStream
      • batch

        PgPreparedQuery batch(List<Tuple> argsList,
                              io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Execute a batch.
        Parameters:
        argsList - the list of tuple for the batch
        Returns:
        the createBatch
      • batch

        <R> PgPreparedQuery batch(List<Tuple> argsList,
                                  Collector<Row,?,R> collector,
                                  io.vertx.core.Handler<io.vertx.core.AsyncResult<PgResult<R>>> handler)
        Execute a batch.
        Parameters:
        argsList - the list of tuple for the batch
        collector - the collector
        Returns:
        the createBatch
      • close

        void close()
        Close the prepared query and release its resources.
      • close

        void close(io.vertx.core.Handler<io.vertx.core.AsyncResult<Void>> completionHandler)
        Like close() but notifies the completionHandler when it's closed.

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/PgResult.html ================================================ PgResult (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient

Interface PgResult<T>

  • Type Parameters:
    T -
    All Known Subinterfaces:
    PgRowSet


    public interface PgResult<T>
    Represents the result of an operation on database.
    • Method Summary

      All Methods Instance Methods Abstract Methods 
      Modifier and Type Method and Description
      List<String> columnsNames()
      Get the names of columns in the PgResult.
      PgResult<T> next()
      Return the next available result or null, e.g for a simple query that executed multiple queries or for a batch result.
      int rowCount()
      Get the number of the affected rows in the operation to this PgResult.
      int size()
      Get the number of rows in the PgResult.
      T value()
      Get the result value.
    • Method Detail

      • rowCount

        int rowCount()
        Get the number of the affected rows in the operation to this PgResult.

        The meaning depends on the executed statement:

        • INSERT: the number of rows inserted
        • DELETE: the number of rows deleted
        • UPDATE: the number of rows updated
        • SELECT: the number of rows retrieved
        Returns:
        the count of affected rows.
      • columnsNames

        List<String> columnsNames()
        Get the names of columns in the PgResult.
        Returns:
        the list of names of columns.
      • size

        int size()
        Get the number of rows in the PgResult.
        Returns:
        the count of rows.
      • value

        T value()
        Get the result value.
        Returns:
        the result
      • next

        PgResult<T> next()
        Return the next available result or null, e.g for a simple query that executed multiple queries or for a batch result.
        Returns:
        the next available result or null if none is available

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/PgRowSet.html ================================================ PgRowSet (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient

Interface PgRowSet

    • Method Detail

      • next

        PgRowSet next()
        Description copied from interface: PgResult
        Return the next available result or null, e.g for a simple query that executed multiple queries or for a batch result.
        Specified by:
        next in interface PgResult<PgRowSet>
        Returns:
        the next available result or null if none is available

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/PgStream.html ================================================ PgStream (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient

Interface PgStream<T>

  • All Superinterfaces:
    io.vertx.core.streams.ReadStream<T>, io.vertx.core.streams.StreamBase


    public interface PgStream<T>
    extends io.vertx.core.streams.ReadStream<T>
    A row oriented stream.
    • Method Detail

      • exceptionHandler

        PgStream<T> exceptionHandler(io.vertx.core.Handler<Throwable> handler)
        Specified by:
        exceptionHandler in interface io.vertx.core.streams.ReadStream<T>
        Specified by:
        exceptionHandler in interface io.vertx.core.streams.StreamBase
      • handler

        PgStream<T> handler(io.vertx.core.Handler<T> handler)
        Specified by:
        handler in interface io.vertx.core.streams.ReadStream<T>
      • pause

        PgStream<T> pause()
        Specified by:
        pause in interface io.vertx.core.streams.ReadStream<T>
      • resume

        PgStream<T> resume()
        Specified by:
        resume in interface io.vertx.core.streams.ReadStream<T>
      • endHandler

        PgStream<T> endHandler(io.vertx.core.Handler<Void> endHandler)
        Specified by:
        endHandler in interface io.vertx.core.streams.ReadStream<T>
      • close

        void close()
        Close the stream and release the resources.
      • close

        void close(io.vertx.core.Handler<io.vertx.core.AsyncResult<Void>> completionHandler)
        Close the stream and release the resources.
        Parameters:
        completionHandler - the completion handler for this operation

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/PgTransaction.html ================================================ PgTransaction (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient

Interface PgTransaction

  • All Superinterfaces:
    PgClient


    public interface PgTransaction
    extends PgClient
    A transaction that allows to control the transaction and receive events.
    • Method Detail

      • prepare

        PgTransaction prepare(String sql,
                              io.vertx.core.Handler<io.vertx.core.AsyncResult<PgPreparedQuery>> handler)
        Create a prepared query.
        Parameters:
        sql - the sql
        handler - the handler notified with the prepared query asynchronously
      • commit

        void commit()
        Commit the current transaction.
      • commit

        void commit(io.vertx.core.Handler<io.vertx.core.AsyncResult<Void>> handler)
        Like commit() with an handler to be notified when the transaction commit has completed
      • rollback

        void rollback()
        Rollback the current transaction.
      • rollback

        void rollback(io.vertx.core.Handler<io.vertx.core.AsyncResult<Void>> handler)
        Like rollback() with an handler to be notified when the transaction rollback has completed
      • abortHandler

        PgTransaction abortHandler(io.vertx.core.Handler<Void> handler)
        Set an handler to be called when the transaction is aborted.
        Parameters:
        handler - the handler
      • query

        PgTransaction query(String sql,
                            io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from interface: PgClient
        Execute a simple query.
        Specified by:
        query in interface PgClient
        Parameters:
        sql - the query SQL
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • query

        <R> PgTransaction query(String sql,
                                Collector<Row,?,R> collector,
                                io.vertx.core.Handler<io.vertx.core.AsyncResult<PgResult<R>>> handler)
        Description copied from interface: PgClient
        Execute a simple query.
        Specified by:
        query in interface PgClient
        Parameters:
        sql - the query SQL
        collector - the collector
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • preparedQuery

        PgTransaction preparedQuery(String sql,
                                    io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from interface: PgClient
        Prepare and execute a query.
        Specified by:
        preparedQuery in interface PgClient
        Parameters:
        sql - the prepared query SQL
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • preparedQuery

        <R> PgTransaction preparedQuery(String sql,
                                        Collector<Row,?,R> collector,
                                        io.vertx.core.Handler<io.vertx.core.AsyncResult<PgResult<R>>> handler)
        Description copied from interface: PgClient
        Prepare and execute a query.
        Specified by:
        preparedQuery in interface PgClient
        Parameters:
        sql - the prepared query SQL
        collector - the collector
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • preparedQuery

        PgTransaction preparedQuery(String sql,
                                    Tuple arguments,
                                    io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from interface: PgClient
        Prepare and execute a query.
        Specified by:
        preparedQuery in interface PgClient
        Parameters:
        sql - the prepared query SQL
        arguments - the list of arguments
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • preparedQuery

        <R> PgTransaction preparedQuery(String sql,
                                        Tuple arguments,
                                        Collector<Row,?,R> collector,
                                        io.vertx.core.Handler<io.vertx.core.AsyncResult<PgResult<R>>> handler)
        Description copied from interface: PgClient
        Prepare and execute a query.
        Specified by:
        preparedQuery in interface PgClient
        Parameters:
        sql - the prepared query SQL
        arguments - the list of arguments
        collector - the collector
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • preparedBatch

        PgTransaction preparedBatch(String sql,
                                    List<Tuple> batch,
                                    io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from interface: PgClient
        Prepare and execute a createBatch.
        Specified by:
        preparedBatch in interface PgClient
        Parameters:
        sql - the prepared query SQL
        batch - the batch of tuples
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • preparedBatch

        <R> PgTransaction preparedBatch(String sql,
                                        List<Tuple> batch,
                                        Collector<Row,?,R> collector,
                                        io.vertx.core.Handler<io.vertx.core.AsyncResult<PgResult<R>>> handler)
        Description copied from interface: PgClient
        Prepare and execute a createBatch.
        Specified by:
        preparedBatch in interface PgClient
        Parameters:
        sql - the prepared query SQL
        batch - the batch of tuples
        collector - the collector
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/Row.html ================================================ Row (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient

Interface Row

  • All Superinterfaces:
    Tuple


    public interface Row
    extends Tuple
    • Method Detail

      • getColumnName

        String getColumnName(int pos)
        Get a column name at pos.
        Parameters:
        pos - the position
        Returns:
        the column name or null
      • getBoolean

        Boolean getBoolean(String name)
        Get a boolean value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getValue

        Object getValue(String name)
        Get an object value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getShort

        Short getShort(String name)
        Get a short value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getInteger

        Integer getInteger(String name)
        Get an integer value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLong

        Long getLong(String name)
        Get a long value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getFloat

        Float getFloat(String name)
        Get a float value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getDouble

        Double getDouble(String name)
        Get a double value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getString

        String getString(String name)
        Get a string value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getJson

        Json getJson(String name)
        Get a json value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getBuffer

        io.vertx.core.buffer.Buffer getBuffer(String name)
        Get a buffer value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getTemporal

        Temporal getTemporal(String name)
        Get a temporal value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLocalDate

        LocalDate getLocalDate(String name)
        Get LocalDate value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLocalTime

        LocalTime getLocalTime(String name)
        Get LocalTime value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getOffsetTime

        OffsetTime getOffsetTime(String name)
        Get OffsetTime value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getUUID

        UUID getUUID(String name)
        Get UUID value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getBigDecimal

        BigDecimal getBigDecimal(String name)
        Get BigDecimal value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getNumeric

        Numeric getNumeric(String name)
        Get Numeric value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getPoint

        Point getPoint(String name)
        Get Point value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLine

        Line getLine(String name)
        Get Line value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLineSegment

        LineSegment getLineSegment(String name)
        Get LineSegment value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getBox

        Box getBox(String name)
        Get Box value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getPath

        Path getPath(String name)
        Get Path value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getPolygon

        Polygon getPolygon(String name)
        Get Polygon value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getCircle

        Circle getCircle(String name)
        Get Circle value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getInterval

        Interval getInterval(String name)
        Get Interval value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getIntegerArray

        Integer[] getIntegerArray(String name)
        Get an array of Integer value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getBooleanArray

        Boolean[] getBooleanArray(String name)
        Get an array of Boolean value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getShortArray

        Short[] getShortArray(String name)
        Get an array of Short value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLongArray

        Long[] getLongArray(String name)
        Get an array of Long value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getFloatArray

        Float[] getFloatArray(String name)
        Get an array of Float value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getDoubleArray

        Double[] getDoubleArray(String name)
        Get an array of Double value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getStringArray

        String[] getStringArray(String name)
        Get an array of String value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLocalDateArray

        LocalDate[] getLocalDateArray(String name)
        Get an array of LocalDate value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLocalTimeArray

        LocalTime[] getLocalTimeArray(String name)
        Get an array of LocalTime value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getOffsetTimeArray

        OffsetTime[] getOffsetTimeArray(String name)
        Get an array of OffsetTime value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLocalDateTimeArray

        LocalDateTime[] getLocalDateTimeArray(String name)
        Get an array of LocalDateTime value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getOffsetDateTimeArray

        OffsetDateTime[] getOffsetDateTimeArray(String name)
        Get an array of OffsetDateTime value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getBufferArray

        io.vertx.core.buffer.Buffer[] getBufferArray(String name)
        Get an array of Buffer value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getUUIDArray

        UUID[] getUUIDArray(String name)
        Get an array of UUID value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getJsonArray

        Json[] getJsonArray(String name)
        Get an array of Json value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getNumericArray

        Numeric[] getNumericArray(String name)
        Get an array of Numeric value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getPointArray

        Point[] getPointArray(String name)
        Get an array of Point value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLineArray

        Line[] getLineArray(String name)
        Get an array of Line value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLineSegmentArray

        LineSegment[] getLineSegmentArray(String name)
        Get an array of LineSegment value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getBoxArray

        Box[] getBoxArray(String name)
        Get an array of Box value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getPathArray

        Path[] getPathArray(String name)
        Get an array of Path value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getPolygonArray

        Polygon[] getPolygonArray(String name)
        Get an array of Polygon value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getCircleArray

        Circle[] getCircleArray(String name)
        Get an array of Circle value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getIntervalArray

        Interval[] getIntervalArray(String name)
        Get an array of Interval value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/SslMode.html ================================================ SslMode (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient

Enum SslMode

    • Enum Constant Detail

      • DISABLE

        public static final SslMode DISABLE
        only try a non-SSL connection.
      • ALLOW

        public static final SslMode ALLOW
        first try a non-SSL connection; if that fails, try an SSL connection.
      • PREFER

        public static final SslMode PREFER
        first try an SSL connection; if that fails, try a non-SSL connection.
      • REQUIRE

        public static final SslMode REQUIRE
        only try an SSL connection. If a root CA file is present, verify the certificate in the same way as if verify-ca was specified.
      • VERIFY_CA

        public static final SslMode VERIFY_CA
        only try an SSL connection, and verify that the server certificate is issued by a trusted certificate authority (CA).
      • VERIFY_FULL

        public static final SslMode VERIFY_FULL
        only try an SSL connection, verify that the server certificate is issued by a trusted CA and that the requested server host name matches that in the certificate.
    • Field Detail

      • VALUES

        public static final SslMode[] VALUES
      • value

        public final String value
    • Method Detail

      • values

        public static SslMode[] values()
        Returns an array containing the constants of this enum type, in the order they are declared. This method may be used to iterate over the constants as follows:
        for (SslMode c : SslMode.values())
            System.out.println(c);
        
        Returns:
        an array containing the constants of this enum type, in the order they are declared
      • valueOf

        public static SslMode valueOf(String name)
        Returns the enum constant of this type with the specified name. The string must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)
        Parameters:
        name - the name of the enum constant to be returned.
        Returns:
        the enum constant with the specified name
        Throws:
        IllegalArgumentException - if this enum type has no constant with the specified name
        NullPointerException - if the argument is null

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/Tuple.html ================================================ Tuple (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient

Interface Tuple

  • All Known Subinterfaces:
    Row


    public interface Tuple
    A general purpose tuple.
    • Method Detail

      • tuple

        static Tuple tuple()
        Returns:
        a new empty tuple
      • of

        static Tuple of(Object elt1)
        Create a tuple of one element.
        Parameters:
        elt1 - the first value
        Returns:
        the tuple
      • of

        static Tuple of(Object elt1,
                        Object elt2)
        Create a tuple of two elements.
        Parameters:
        elt1 - the first value
        elt2 - the second value
        Returns:
        the tuple
      • of

        static Tuple of(Object elt1,
                        Object elt2,
                        Object elt3)
        Create a tuple of three elements.
        Parameters:
        elt1 - the first value
        elt2 - the second value
        elt3 - the third value
        Returns:
        the tuple
      • of

        static Tuple of(Object elt1,
                        Object elt2,
                        Object elt3,
                        Object elt4)
        Create a tuple of four elements.
        Parameters:
        elt1 - the first value
        elt2 - the second value
        elt3 - the third value
        elt4 - the fourth value
        Returns:
        the tuple
      • of

        static Tuple of(Object elt1,
                        Object elt2,
                        Object elt3,
                        Object elt4,
                        Object elt5)
        Create a tuple of five elements.
        Parameters:
        elt1 - the first value
        elt2 - the second value
        elt3 - the third value
        elt4 - the fourth value
        elt5 - the fifth value
        Returns:
        the tuple
      • of

        static Tuple of(Object elt1,
                        Object elt2,
                        Object elt3,
                        Object elt4,
                        Object elt5,
                        Object elt6)
        Create a tuple of six elements.
        Parameters:
        elt1 - the first value
        elt2 - the second valueg
        elt3 - the third value
        elt4 - the fourth value
        elt5 - the fifth value
        elt6 - the sixth value
        Returns:
        the tuple
      • of

        static Tuple of(Object elt1,
                        Object... elts)
        Create a tuple of an arbitrary number of elements.
        Parameters:
        elt1 - the first element
        elts - the remaining elements
        Returns:
        the tuple
      • getBoolean

        Boolean getBoolean(int pos)
        Get a boolean value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getValue

        Object getValue(int pos)
        Get an object value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getShort

        Short getShort(int pos)
        Get a short value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getInteger

        Integer getInteger(int pos)
        Get an integer value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLong

        Long getLong(int pos)
        Get a long value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getFloat

        Float getFloat(int pos)
        Get a float value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getDouble

        Double getDouble(int pos)
        Get a double value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getString

        String getString(int pos)
        Get a string value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getJson

        Json getJson(int pos)
        Get a json value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getTemporal

        Temporal getTemporal(int pos)
        Get a Temporal value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLocalDate

        LocalDate getLocalDate(int pos)
        Get LocalDate value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLocalTime

        LocalTime getLocalTime(int pos)
        Get LocalTime value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLocalDateTime

        LocalDateTime getLocalDateTime(int pos)
        Get LocalDateTime value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getOffsetTime

        OffsetTime getOffsetTime(int pos)
        Get OffsetTime value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getOffsetDateTime

        OffsetDateTime getOffsetDateTime(int pos)
        Get OffsetDateTime value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getUUID

        UUID getUUID(int pos)
        Get UUID value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getBigDecimal

        BigDecimal getBigDecimal(int pos)
        Get BigDecimal value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getIntegerArray

        Integer[] getIntegerArray(int pos)
        Get an array of Integer value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getBooleanArray

        Boolean[] getBooleanArray(int pos)
        Get an array of Boolean value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getShortArray

        Short[] getShortArray(int pos)
        Get an array of Short value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLongArray

        Long[] getLongArray(int pos)
        Get an array of Long value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getFloatArray

        Float[] getFloatArray(int pos)
        Get an array of Float value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getDoubleArray

        Double[] getDoubleArray(int pos)
        Get an array of Double value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getStringArray

        String[] getStringArray(int pos)
        Get an array of String value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLocalDateArray

        LocalDate[] getLocalDateArray(int pos)
        Get an array of LocalDate value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLocalTimeArray

        LocalTime[] getLocalTimeArray(int pos)
        Get an array of LocalTime value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getOffsetTimeArray

        OffsetTime[] getOffsetTimeArray(int pos)
        Get an array of OffsetTime value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLocalDateTimeArray

        LocalDateTime[] getLocalDateTimeArray(int pos)
        Get an array of LocalDateTime value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getOffsetDateTimeArray

        OffsetDateTime[] getOffsetDateTimeArray(int pos)
        Get an array of OffsetDateTime value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getBufferArray

        io.vertx.core.buffer.Buffer[] getBufferArray(int pos)
        Get an array of Buffer value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getUUIDArray

        UUID[] getUUIDArray(int pos)
        Get an array of UUID value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getJsonArray

        Json[] getJsonArray(int pos)
        Get an array of Json value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getNumericArray

        Numeric[] getNumericArray(int pos)
        Get an array of Numeric value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getPointArray

        Point[] getPointArray(int pos)
        Get an array of Point value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getLineArray

        Line[] getLineArray(int pos)
        Get an array of Line value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getLineSegmentArray

        LineSegment[] getLineSegmentArray(int pos)
        Get an array of LineSegment value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getBoxArray

        Box[] getBoxArray(int pos)
        Get an array of Box value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getPathArray

        Path[] getPathArray(int pos)
        Get an array of Path value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getPolygonArray

        Polygon[] getPolygonArray(int pos)
        Get an array of Polygon value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getCircleArray

        Circle[] getCircleArray(int pos)
        Get an array of Circle value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getIntervalArray

        Interval[] getIntervalArray(int pos)
        Get an array of Interval value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getNumeric

        Numeric getNumeric(int pos)
        Get Numeric value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getPoint

        Point getPoint(int pos)
        Get Point value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLine

        Line getLine(int pos)
        Get Line value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLineSegment

        LineSegment getLineSegment(int pos)
        Get LineSegment value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getBox

        Box getBox(int pos)
        Get Box value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getPath

        Path getPath(int pos)
        Get Path value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getPolygon

        Polygon getPolygon(int pos)
        Get Polygon value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getCircle

        Circle getCircle(int pos)
        Get Circle value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getInterval

        Interval getInterval(int pos)
        Get Interval value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getBuffer

        io.vertx.core.buffer.Buffer getBuffer(int pos)
        Get a buffer value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • addBoolean

        Tuple addBoolean(Boolean value)
        Add a boolean value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addValue

        Tuple addValue(Object value)
        Add an object value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addShort

        Tuple addShort(Short value)
        Add a short value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addInteger

        Tuple addInteger(Integer value)
        Add an integer value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLong

        Tuple addLong(Long value)
        Add a long value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addFloat

        Tuple addFloat(Float value)
        Add a float value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addDouble

        Tuple addDouble(Double value)
        Add a double value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addString

        Tuple addString(String value)
        Add a string value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addJson

        Tuple addJson(Json value)
        Add a json value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addBuffer

        Tuple addBuffer(io.vertx.core.buffer.Buffer value)
        Add a buffer value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addTemporal

        Tuple addTemporal(Temporal value)
        Add a Temporal value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLocalDate

        Tuple addLocalDate(LocalDate value)
        Add a LocalDate value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLocalTime

        Tuple addLocalTime(LocalTime value)
        Add a LocalTime value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLocalDateTime

        Tuple addLocalDateTime(LocalDateTime value)
        Add a LocalDateTime value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addOffsetTime

        Tuple addOffsetTime(OffsetTime value)
        Add a OffsetTime value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addOffsetDateTime

        Tuple addOffsetDateTime(OffsetDateTime value)
        Add a OffsetDateTime value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addUUID

        Tuple addUUID(UUID value)
        Add a UUID value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addNumeric

        Tuple addNumeric(Numeric value)
        Add a Numeric value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addBigDecimal

        Tuple addBigDecimal(BigDecimal value)
        Add a BigDecimal value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addPoint

        Tuple addPoint(Point value)
        Add a Point value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLine

        Tuple addLine(Line value)
        Add a Line value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLineSegment

        Tuple addLineSegment(LineSegment value)
        Add a LineSegment value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addBox

        Tuple addBox(Box value)
        Add a Box value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addPath

        Tuple addPath(Path value)
        Add a Path value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addPolygon

        Tuple addPolygon(Polygon value)
        Add a Polygon value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addCircle

        Tuple addCircle(Circle value)
        Add a Circle value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addInterval

        Tuple addInterval(Interval value)
        Add a Point value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addIntegerArray

        Tuple addIntegerArray(Integer[] value)
        Add an array of Integer value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addBooleanArray

        Tuple addBooleanArray(Boolean[] value)
        Add an array of Boolean value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addShortArray

        Tuple addShortArray(Short[] value)
        Add an array of Short value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLongArray

        Tuple addLongArray(Long[] value)
        Add an array of Long value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addFloatArray

        Tuple addFloatArray(Float[] value)
        Add an array of Float value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addDoubleArray

        Tuple addDoubleArray(Double[] value)
        Add an array of Double value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addStringArray

        Tuple addStringArray(String[] value)
        Add an array of String value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLocalDateArray

        Tuple addLocalDateArray(LocalDate[] value)
        Add an array of LocalDate value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLocalTimeArray

        Tuple addLocalTimeArray(LocalTime[] value)
        Add an array of LocalTime value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addOffsetTimeArray

        Tuple addOffsetTimeArray(OffsetTime[] value)
        Add an array of OffsetTime value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLocalDateTimeArray

        Tuple addLocalDateTimeArray(LocalDateTime[] value)
        Add an array of LocalDateTime value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addOffsetDateTimeArray

        Tuple addOffsetDateTimeArray(OffsetDateTime[] value)
        Add an array of OffsetDateTime value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addBufferArray

        Tuple addBufferArray(io.vertx.core.buffer.Buffer[] value)
        Add an array of Buffer value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addUUIDArray

        Tuple addUUIDArray(UUID[] value)
        Add an array of UUID value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addJsonArray

        Tuple addJsonArray(Json[] value)
        Add an array of Json value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addNumericArray

        Tuple addNumericArray(Numeric[] value)
        Add an array of Numeric value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addPointArray

        Tuple addPointArray(Point[] value)
        Add an array of Point value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLineArray

        Tuple addLineArray(Line[] value)
        Add an array of Line value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLineSegmentArray

        Tuple addLineSegmentArray(LineSegment[] value)
        Add an array of LineSegment value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addBoxArray

        Tuple addBoxArray(Box[] value)
        Add an array of Box value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addPathArray

        Tuple addPathArray(Path[] value)
        Add an array of Path value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addPolygonArray

        Tuple addPolygonArray(Polygon[] value)
        Add an array of Polygon value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addCircleArray

        Tuple addCircleArray(Circle[] value)
        Add an array of Circle value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addIntervalArray

        Tuple addIntervalArray(Interval[] value)
        Add an array of Interval value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • size

        int size()
        Returns:
        the tuple size
      • clear

        void clear()

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/class-use/Json.html ================================================ Uses of Interface io.reactiverse.pgclient.data.Json (Reactive Postgres Client 0.9.0 API)

Uses of Interface
io.reactiverse.pgclient.Json

Copyright © 2018 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/class-use/JsonImpl.html ================================================ Uses of Class io.reactiverse.pgclient.impl.data.JsonImpl (Reactive Postgres Client 0.7.1-SNAPSHOT API)

Uses of Class
io.reactiverse.pgclient.JsonImpl

Copyright © 2018 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/class-use/Numeric.html ================================================ Uses of Class io.reactiverse.pgclient.data.Numeric (Reactive Postgres Client 0.9.0 API)

Uses of Class
io.reactiverse.pgclient.Numeric

Copyright © 2018 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/class-use/PgClient.html ================================================ Uses of Interface io.reactiverse.pgclient.PgClient (Reactive Postgres Client 0.11.2 API)

Uses of Interface
io.reactiverse.pgclient.PgClient

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/class-use/PgConnectOptions.html ================================================ Uses of Class io.reactiverse.pgclient.PgConnectOptions (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.pgclient.PgConnectOptions

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/class-use/PgConnectOptionsConverter.html ================================================ Uses of Class io.reactiverse.pgclient.PgConnectOptionsConverter (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.pgclient.PgConnectOptionsConverter

No usage of io.reactiverse.pgclient.PgConnectOptionsConverter

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/class-use/PgConnection.html ================================================ Uses of Interface io.reactiverse.pgclient.PgConnection (Reactive Postgres Client 0.11.2 API)

Uses of Interface
io.reactiverse.pgclient.PgConnection

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/class-use/PgCursor.html ================================================ Uses of Interface io.reactiverse.pgclient.PgCursor (Reactive Postgres Client 0.11.2 API)

Uses of Interface
io.reactiverse.pgclient.PgCursor

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/class-use/PgException.html ================================================ Uses of Class io.reactiverse.pgclient.PgException (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.pgclient.PgException

No usage of io.reactiverse.pgclient.PgException

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/class-use/PgIterator.html ================================================ Uses of Interface io.reactiverse.pgclient.PgIterator (Reactive Postgres Client 0.11.2 API)

Uses of Interface
io.reactiverse.pgclient.PgIterator

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/class-use/PgNotification.html ================================================ Uses of Class io.reactiverse.pgclient.PgNotification (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.pgclient.PgNotification

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/class-use/PgNotificationConverter.html ================================================ Uses of Class io.reactiverse.pgclient.PgNotificationConverter (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.pgclient.PgNotificationConverter

No usage of io.reactiverse.pgclient.PgNotificationConverter

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/class-use/PgPool.html ================================================ Uses of Interface io.reactiverse.pgclient.PgPool (Reactive Postgres Client 0.11.2 API)

Uses of Interface
io.reactiverse.pgclient.PgPool

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/class-use/PgPoolOptions.html ================================================ Uses of Class io.reactiverse.pgclient.PgPoolOptions (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.pgclient.PgPoolOptions

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/class-use/PgPoolOptionsConverter.html ================================================ Uses of Class io.reactiverse.pgclient.PgPoolOptionsConverter (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.pgclient.PgPoolOptionsConverter

No usage of io.reactiverse.pgclient.PgPoolOptionsConverter

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/class-use/PgPreparedQuery.html ================================================ Uses of Interface io.reactiverse.pgclient.PgPreparedQuery (Reactive Postgres Client 0.11.2 API)

Uses of Interface
io.reactiverse.pgclient.PgPreparedQuery

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/class-use/PgResult.html ================================================ Uses of Interface io.reactiverse.pgclient.PgResult (Reactive Postgres Client 0.11.2 API)

Uses of Interface
io.reactiverse.pgclient.PgResult

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/class-use/PgRowSet.html ================================================ Uses of Interface io.reactiverse.pgclient.PgRowSet (Reactive Postgres Client 0.11.2 API)

Uses of Interface
io.reactiverse.pgclient.PgRowSet

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/class-use/PgStream.html ================================================ Uses of Interface io.reactiverse.pgclient.PgStream (Reactive Postgres Client 0.11.2 API)

Uses of Interface
io.reactiverse.pgclient.PgStream

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/class-use/PgTransaction.html ================================================ Uses of Interface io.reactiverse.pgclient.PgTransaction (Reactive Postgres Client 0.11.2 API)

Uses of Interface
io.reactiverse.pgclient.PgTransaction

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/class-use/Row.html ================================================ Uses of Interface io.reactiverse.pgclient.Row (Reactive Postgres Client 0.11.2 API)

Uses of Interface
io.reactiverse.pgclient.Row

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/class-use/SslMode.html ================================================ Uses of Class io.reactiverse.pgclient.SslMode (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.pgclient.SslMode

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/class-use/Tuple.html ================================================ Uses of Interface io.reactiverse.pgclient.Tuple (Reactive Postgres Client 0.11.2 API)

Uses of Interface
io.reactiverse.pgclient.Tuple

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/Box.html ================================================ Box (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient.data

Class Box



  • public class Box
    extends Object
    Rectangular box data type in Postgres represented by pairs of Points that are opposite corners of the box.
    • Constructor Detail

      • Box

        public Box()
      • Box

        public Box(Point upperRightCorner,
                   Point lowerLeftCorner)
      • Box

        public Box(io.vertx.core.json.JsonObject json)
    • Method Detail

      • getUpperRightCorner

        public Point getUpperRightCorner()
      • setUpperRightCorner

        public void setUpperRightCorner(Point upperRightCorner)
      • getLowerLeftCorner

        public Point getLowerLeftCorner()
      • setLowerLeftCorner

        public void setLowerLeftCorner(Point lowerLeftCorner)
      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Object
      • toJson

        public io.vertx.core.json.JsonObject toJson()

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/BoxConverter.html ================================================ BoxConverter (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient.data

Class BoxConverter



  • public class BoxConverter
    extends Object
    Converter for Box. NOTE: This class has been automatically generated from the Box original class using Vert.x codegen.
    • Constructor Detail

      • BoxConverter

        public BoxConverter()

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/Circle.html ================================================ Circle (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient.data

Class Circle



  • public class Circle
    extends Object
    Circle data type in Postgres represented by a center Point and radius.
    • Constructor Detail

      • Circle

        public Circle()
      • Circle

        public Circle(Point centerPoint,
                      double radius)
      • Circle

        public Circle(io.vertx.core.json.JsonObject json)
    • Method Detail

      • getCenterPoint

        public Point getCenterPoint()
      • setCenterPoint

        public void setCenterPoint(Point centerPoint)
      • getRadius

        public double getRadius()
      • setRadius

        public void setRadius(double radius)
      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Object
      • toJson

        public io.vertx.core.json.JsonObject toJson()

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/CircleConverter.html ================================================ CircleConverter (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient.data

Class CircleConverter



  • public class CircleConverter
    extends Object
    Converter for Circle. NOTE: This class has been automatically generated from the Circle original class using Vert.x codegen.

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/Interval.html ================================================ Interval (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient.data

Class Interval



  • public class Interval
    extends Object
    Postgres Interval is date and time based such as 120 years 3 months 332 days 20 hours 20 minutes 20.999999 seconds
    Author:
    Emad Alblueshi
    • Constructor Detail

      • Interval

        public Interval()
      • Interval

        public Interval(int years,
                        int months,
                        int days,
                        int hours,
                        int minutes,
                        int seconds,
                        int microseconds)
      • Interval

        public Interval(int years,
                        int months,
                        int days,
                        int hours,
                        int minutes,
                        int seconds)
      • Interval

        public Interval(int years,
                        int months,
                        int days,
                        int hours,
                        int minutes)
      • Interval

        public Interval(int years,
                        int months,
                        int days,
                        int hours)
      • Interval

        public Interval(int years,
                        int months,
                        int days)
      • Interval

        public Interval(int years,
                        int months)
      • Interval

        public Interval(int years)
      • Interval

        public Interval(io.vertx.core.json.JsonObject json)
    • Method Detail

      • of

        public static Interval of(int years,
                                  int months,
                                  int days,
                                  int hours,
                                  int minutes,
                                  int seconds,
                                  int microseconds)
      • of

        public static Interval of(int years,
                                  int months,
                                  int days,
                                  int hours,
                                  int minutes,
                                  int seconds)
      • of

        public static Interval of(int years,
                                  int months,
                                  int days,
                                  int hours,
                                  int minutes)
      • of

        public static Interval of(int years,
                                  int months,
                                  int days,
                                  int hours)
      • of

        public static Interval of(int years,
                                  int months,
                                  int days)
      • of

        public static Interval of(int years,
                                  int months)
      • of

        public static Interval of(int years)
      • years

        public Interval years(int years)
      • months

        public Interval months(int months)
      • days

        public Interval days(int days)
      • hours

        public Interval hours(int hours)
      • minutes

        public Interval minutes(int minutes)
      • seconds

        public Interval seconds(int seconds)
      • microseconds

        public Interval microseconds(int microseconds)
      • getYears

        public int getYears()
      • setYears

        public void setYears(int years)
      • getMonths

        public int getMonths()
      • setMonths

        public void setMonths(int months)
      • getDays

        public int getDays()
      • setDays

        public void setDays(int days)
      • getHours

        public int getHours()
      • setHours

        public void setHours(int hours)
      • getMinutes

        public int getMinutes()
      • setMinutes

        public void setMinutes(int minutes)
      • getSeconds

        public int getSeconds()
      • setSeconds

        public void setSeconds(int seconds)
      • getMicroseconds

        public int getMicroseconds()
      • setMicroseconds

        public void setMicroseconds(int microseconds)
      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Object
      • toJson

        public io.vertx.core.json.JsonObject toJson()

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/IntervalConverter.html ================================================ IntervalConverter (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient.data

Class IntervalConverter



  • public class IntervalConverter
    extends Object
    Converter for Interval. NOTE: This class has been automatically generated from the Interval original class using Vert.x codegen.

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/Json.html ================================================ Json (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient.data

Interface Json



  • public interface Json

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/Line.html ================================================ Line (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient.data

Class Line



  • public class Line
    extends Object
    Line data type in Postgres represented by the linear equation Ax + By + C = 0, where A and B are not both zero.
    • Constructor Detail

      • Line

        public Line()
      • Line

        public Line(double a,
                    double b,
                    double c)
      • Line

        public Line(io.vertx.core.json.JsonObject json)
    • Method Detail

      • getA

        public double getA()
      • setA

        public void setA(double a)
      • getB

        public double getB()
      • setB

        public void setB(double b)
      • getC

        public double getC()
      • setC

        public void setC(double c)
      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Object
      • toJson

        public io.vertx.core.json.JsonObject toJson()

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/LineConverter.html ================================================ LineConverter (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient.data

Class LineConverter



  • public class LineConverter
    extends Object
    Converter for Line. NOTE: This class has been automatically generated from the Line original class using Vert.x codegen.
    • Constructor Detail

      • LineConverter

        public LineConverter()

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/LineSegment.html ================================================ LineSegment (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient.data

Class LineSegment



  • public class LineSegment
    extends Object
    Finite line segment data type in Postgres represented by pairs of Points that are the endpoints of the segment.
    • Constructor Detail

      • LineSegment

        public LineSegment()
      • LineSegment

        public LineSegment(Point p1,
                           Point p2)
      • LineSegment

        public LineSegment(io.vertx.core.json.JsonObject json)
    • Method Detail

      • getP1

        public Point getP1()
      • setP1

        public void setP1(Point p1)
      • getP2

        public Point getP2()
      • setP2

        public void setP2(Point p2)
      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Object
      • toJson

        public io.vertx.core.json.JsonObject toJson()

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/LineSegmentConverter.html ================================================ LineSegmentConverter (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient.data

Class LineSegmentConverter



  • public class LineSegmentConverter
    extends Object
    Converter for LineSegment. NOTE: This class has been automatically generated from the LineSegment original class using Vert.x codegen.

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/Numeric.html ================================================ Numeric (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient.data

Class Numeric

    • Field Detail

      • NaN

        public static final Numeric NaN
        Constant for the NaN value.
    • Method Detail

      • create

        public static Numeric create(Number number)
        Return a Numeric instance for the given number.

        Null values or infinite Double or Float are rejected.

        Parameters:
        number - the number
        Returns:
        the Numeric value
        Throws:
        NumberFormatException - when the number is infinite
      • parse

        public static Numeric parse(String s)
        Parse and return a Numeric instance for the given s.

        The string "Nan" will return the NaN instance.

        Parameters:
        s - the string
        Returns:
        the Numeric value
      • shortValue

        public short shortValue()
        Overrides:
        shortValue in class Number
      • intValue

        public int intValue()
        Specified by:
        intValue in class Number
      • longValue

        public long longValue()
        Specified by:
        longValue in class Number
      • floatValue

        public float floatValue()
        Specified by:
        floatValue in class Number
      • doubleValue

        public double doubleValue()
        Specified by:
        doubleValue in class Number
      • isNaN

        public boolean isNaN()
        Returns:
        true when this number represents NaN
      • bigDecimalValue

        public BigDecimal bigDecimalValue()
        Returns:
        the numeric value represented by this object after conversion to type BigDecimal. It can be null when this instance represents the NaN value.
      • bigIntegerValue

        public BigInteger bigIntegerValue()
        Returns:
        the numeric value represented by this object after conversion to type BigInteger. It can be null when this instance represents the NaN value.
      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Object

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/Path.html ================================================ Path (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient.data

Class Path



  • public class Path
    extends Object
    Path data type in Postgres represented by lists of connected points. Paths can be open, where the first and last points in the list are considered not connected, or closed, where the first and last points are considered connected.
    • Constructor Detail

      • Path

        public Path()
      • Path

        public Path(boolean isOpen,
                    List<Point> points)
      • Path

        public Path(io.vertx.core.json.JsonObject json)
    • Method Detail

      • isOpen

        public boolean isOpen()
      • setOpen

        public void setOpen(boolean open)
      • setPoints

        public void setPoints(List<Point> points)
      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Object
      • toJson

        public io.vertx.core.json.JsonObject toJson()

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/PathConverter.html ================================================ PathConverter (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient.data

Class PathConverter



  • public class PathConverter
    extends Object
    Converter for Path. NOTE: This class has been automatically generated from the Path original class using Vert.x codegen.
    • Constructor Detail

      • PathConverter

        public PathConverter()

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/Point.html ================================================ Point (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient.data

Class Point



  • public class Point
    extends Object
    A Postgresql point.
    • Field Detail

      • x

        public double x
      • y

        public double y
    • Constructor Detail

      • Point

        public Point()
      • Point

        public Point(double x,
                     double y)
      • Point

        public Point(io.vertx.core.json.JsonObject json)
    • Method Detail

      • getX

        public double getX()
      • setX

        public Point setX(double x)
      • getY

        public double getY()
      • setY

        public Point setY(double y)
      • toJson

        public io.vertx.core.json.JsonObject toJson()

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/PointConverter.html ================================================ PointConverter (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient.data

Class PointConverter



  • public class PointConverter
    extends Object
    Converter for Point. NOTE: This class has been automatically generated from the Point original class using Vert.x codegen.

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/Polygon.html ================================================ Polygon (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient.data

Class Polygon



  • public class Polygon
    extends Object
    Polygon data type in Postgres represented by lists of points (the vertexes of the polygon). Polygons are very similar to closed paths, but are stored differently and have their own set of support routines.
    • Constructor Detail

      • Polygon

        public Polygon()
      • Polygon

        public Polygon(List<Point> points)
      • Polygon

        public Polygon(io.vertx.core.json.JsonObject json)
    • Method Detail

      • setPoints

        public void setPoints(List<Point> points)
      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Object
      • toJson

        public io.vertx.core.json.JsonObject toJson()

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/PolygonConverter.html ================================================ PolygonConverter (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient.data

Class PolygonConverter



  • public class PolygonConverter
    extends Object
    Converter for Polygon. NOTE: This class has been automatically generated from the Polygon original class using Vert.x codegen.

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/class-use/Box.html ================================================ Uses of Class io.reactiverse.pgclient.data.Box (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.pgclient.data.Box

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/class-use/BoxConverter.html ================================================ Uses of Class io.reactiverse.pgclient.data.BoxConverter (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.pgclient.data.BoxConverter

No usage of io.reactiverse.pgclient.data.BoxConverter

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/class-use/Circle.html ================================================ Uses of Class io.reactiverse.pgclient.data.Circle (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.pgclient.data.Circle

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/class-use/CircleConverter.html ================================================ Uses of Class io.reactiverse.pgclient.data.CircleConverter (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.pgclient.data.CircleConverter

No usage of io.reactiverse.pgclient.data.CircleConverter

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/class-use/Interval.html ================================================ Uses of Class io.reactiverse.pgclient.data.Interval (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.pgclient.data.Interval

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/class-use/IntervalConverter.html ================================================ Uses of Class io.reactiverse.pgclient.data.IntervalConverter (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.pgclient.data.IntervalConverter

No usage of io.reactiverse.pgclient.data.IntervalConverter

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/class-use/Json.html ================================================ Uses of Interface io.reactiverse.pgclient.data.Json (Reactive Postgres Client 0.11.2 API)

Uses of Interface
io.reactiverse.pgclient.data.Json

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/class-use/Line.html ================================================ Uses of Class io.reactiverse.pgclient.data.Line (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.pgclient.data.Line

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/class-use/LineConverter.html ================================================ Uses of Class io.reactiverse.pgclient.data.LineConverter (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.pgclient.data.LineConverter

No usage of io.reactiverse.pgclient.data.LineConverter

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/class-use/LineSegment.html ================================================ Uses of Class io.reactiverse.pgclient.data.LineSegment (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.pgclient.data.LineSegment

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/class-use/LineSegmentConverter.html ================================================ Uses of Class io.reactiverse.pgclient.data.LineSegmentConverter (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.pgclient.data.LineSegmentConverter

No usage of io.reactiverse.pgclient.data.LineSegmentConverter

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/class-use/Numeric.html ================================================ Uses of Class io.reactiverse.pgclient.data.Numeric (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.pgclient.data.Numeric

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/class-use/Path.html ================================================ Uses of Class io.reactiverse.pgclient.data.Path (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.pgclient.data.Path

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/class-use/PathConverter.html ================================================ Uses of Class io.reactiverse.pgclient.data.PathConverter (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.pgclient.data.PathConverter

No usage of io.reactiverse.pgclient.data.PathConverter

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/class-use/Point.html ================================================ Uses of Class io.reactiverse.pgclient.data.Point (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.pgclient.data.Point

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/class-use/PointConverter.html ================================================ Uses of Class io.reactiverse.pgclient.data.PointConverter (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.pgclient.data.PointConverter

No usage of io.reactiverse.pgclient.data.PointConverter

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/class-use/Polygon.html ================================================ Uses of Class io.reactiverse.pgclient.data.Polygon (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.pgclient.data.Polygon

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/class-use/PolygonConverter.html ================================================ Uses of Class io.reactiverse.pgclient.data.PolygonConverter (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.pgclient.data.PolygonConverter

No usage of io.reactiverse.pgclient.data.PolygonConverter

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/package-frame.html ================================================ io.reactiverse.pgclient.data (Reactive Postgres Client 0.11.2 API)

io.reactiverse.pgclient.data

Interfaces

Classes

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/package-summary.html ================================================ io.reactiverse.pgclient.data (Reactive Postgres Client 0.11.2 API)

Package io.reactiverse.pgclient.data

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/package-tree.html ================================================ io.reactiverse.pgclient.data Class Hierarchy (Reactive Postgres Client 0.11.2 API)

Hierarchy For Package io.reactiverse.pgclient.data

Package Hierarchies:

Class Hierarchy

Interface Hierarchy

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/data/package-use.html ================================================ Uses of Package io.reactiverse.pgclient.data (Reactive Postgres Client 0.11.2 API)

Uses of Package
io.reactiverse.pgclient.data

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/package-frame.html ================================================ io.reactiverse.pgclient (Reactive Postgres Client 0.11.2 API)

io.reactiverse.pgclient

Interfaces

Classes

Enums

Exceptions

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/package-summary.html ================================================ io.reactiverse.pgclient (Reactive Postgres Client 0.11.2 API)

Package io.reactiverse.pgclient

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/package-tree.html ================================================ io.reactiverse.pgclient Class Hierarchy (Reactive Postgres Client 0.11.2 API)

Hierarchy For Package io.reactiverse.pgclient

Package Hierarchies:

Class Hierarchy

Interface Hierarchy

Enum Hierarchy

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/package-use.html ================================================ Uses of Package io.reactiverse.pgclient (Reactive Postgres Client 0.11.2 API)

Uses of Package
io.reactiverse.pgclient

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/pubsub/PgChannel.html ================================================ PgChannel (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient.pubsub

Interface PgChannel

  • All Superinterfaces:
    io.vertx.core.streams.ReadStream<String>, io.vertx.core.streams.StreamBase


    public interface PgChannel
    extends io.vertx.core.streams.ReadStream<String>
    A channel to Postgres that tracks the subscription to a given Postgres channel using the LISTEN/UNLISTEN commands.

    When paused the channel discards the messages.

    • Method Detail

      • subscribeHandler

        PgChannel subscribeHandler(io.vertx.core.Handler<Void> handler)
        Set an handler called when the the channel get subscribed.
        Parameters:
        handler - the handler
        Returns:
        a reference to this, so the API can be used fluently
      • handler

        PgChannel handler(io.vertx.core.Handler<String> handler)
        Set or unset an handler to be called when a the channel is notified by Postgres.

        • when the handler is set, the subscriber sends a LISTEN command if needed
        • when the handler is unset, the subscriber sends a UNLISTEN command if needed
        Specified by:
        handler in interface io.vertx.core.streams.ReadStream<String>
        Parameters:
        handler - the handler
        Returns:
        a reference to this, so the API can be used fluently
      • pause

        PgChannel pause()
        Pause the channel, all notifications are discarded.
        Specified by:
        pause in interface io.vertx.core.streams.ReadStream<String>
        Returns:
        a reference to this, so the API can be used fluently
      • resume

        PgChannel resume()
        Resume the channel.
        Specified by:
        resume in interface io.vertx.core.streams.ReadStream<String>
        Returns:
        a reference to this, so the API can be used fluently
      • endHandler

        PgChannel endHandler(io.vertx.core.Handler<Void> endHandler)
        Set an handler to be called when no more notifications will be received.
        Specified by:
        endHandler in interface io.vertx.core.streams.ReadStream<String>
        Parameters:
        endHandler - the handler
        Returns:
        a reference to this, so the API can be used fluently
      • exceptionHandler

        PgChannel exceptionHandler(io.vertx.core.Handler<Throwable> handler)
        Specified by:
        exceptionHandler in interface io.vertx.core.streams.ReadStream<String>
        Specified by:
        exceptionHandler in interface io.vertx.core.streams.StreamBase

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/pubsub/PgSubscriber.html ================================================ PgSubscriber (Reactive Postgres Client 0.11.2 API)
io.reactiverse.pgclient.pubsub

Interface PgSubscriber



  • public interface PgSubscriber
    A class for managing subscriptions using LISTEN/UNLISTEN to Postgres channels.

    The subscriber manages a single connection to Postgres.

    • Method Detail

      • subscriber

        static PgSubscriber subscriber(io.vertx.core.Vertx vertx,
                                       PgConnectOptions options)
        Create a subscriber.
        Parameters:
        vertx - the vertx instance
        options - the connect options
        Returns:
        the subscriber
      • channel

        PgChannel channel(String name)
        Return a channel for the given name.
        Parameters:
        name - the channel name

        This will be the name of the channel exactly as held by Postgres for sending notifications. Internally this name will be truncated to the Postgres identifier maxiumum length of (NAMEDATALEN = 64) - 1 == 63 characters, and prepared as a quoted identifier without unicode escape sequence support for use in LISTEN/UNLISTEN commands. Examples of channel names and corresponding NOTIFY commands:

        • when name == "the_channel": NOTIFY the_channel, 'msg', NOTIFY The_Channel, 'msg', or NOTIFY "the_channel", 'msg' succeed in delivering a message to the created channel
        • when name == "The_Channel": NOTIFY "The_Channel", 'msg', succeeds in delivering a message to the created channel
        Returns:
        the channel
      • connect

        PgSubscriber connect(io.vertx.core.Handler<io.vertx.core.AsyncResult<Void>> handler)
        Connect the subscriber to Postgres.
        Parameters:
        handler - the handler notified of the connection success or failure
        Returns:
        a reference to this, so the API can be used fluently
      • reconnectPolicy

        PgSubscriber reconnectPolicy(Function<Integer,Long> policy)
        Set the reconnect policy that is executed when the subscriber is disconnected.

        When the subscriber is disconnected, the policy function is called with the actual number of retries and returns an amountOfTime value:

        • when amountOfTime < 0: the subscriber is closed and there is no retry
        • when amountOfTime == 0: the subscriber retries to connect immediately
        • when amountOfTime > 0: the subscriber retries after amountOfTime milliseconds

        The default policy does not perform any retries.

        Parameters:
        policy - the policy to set
        Returns:
        a reference to this, so the API can be used fluently
      • closeHandler

        PgSubscriber closeHandler(io.vertx.core.Handler<Void> handler)
        Set an handler called when the subscriber is closed.
        Parameters:
        handler - the handler
        Returns:
        a reference to this, so the API can be used fluently
      • actualConnection

        PgConnection actualConnection()
        Returns:
        the actual connection to Postgres, it might be null
      • closed

        boolean closed()
        Returns:
        whether the subscriber is closed
      • close

        void close()
        Close the subscriber, the retry policy will not be invoked.

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/pubsub/class-use/PgChannel.html ================================================ Uses of Interface io.reactiverse.pgclient.pubsub.PgChannel (Reactive Postgres Client 0.11.2 API)

Uses of Interface
io.reactiverse.pgclient.pubsub.PgChannel

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/pubsub/class-use/PgSubscriber.html ================================================ Uses of Interface io.reactiverse.pgclient.pubsub.PgSubscriber (Reactive Postgres Client 0.11.2 API)

Uses of Interface
io.reactiverse.pgclient.pubsub.PgSubscriber

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/pubsub/package-frame.html ================================================ io.reactiverse.pgclient.pubsub (Reactive Postgres Client 0.11.2 API)

io.reactiverse.pgclient.pubsub

Interfaces

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/pubsub/package-summary.html ================================================ io.reactiverse.pgclient.pubsub (Reactive Postgres Client 0.11.2 API)

Package io.reactiverse.pgclient.pubsub

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/pubsub/package-tree.html ================================================ io.reactiverse.pgclient.pubsub Class Hierarchy (Reactive Postgres Client 0.11.2 API)

Hierarchy For Package io.reactiverse.pgclient.pubsub

Package Hierarchies:

Interface Hierarchy

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/pgclient/pubsub/package-use.html ================================================ Uses of Package io.reactiverse.pgclient.pubsub (Reactive Postgres Client 0.11.2 API)

Uses of Package
io.reactiverse.pgclient.pubsub

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/Json.html ================================================ Json (Reactive Postgres Client 0.9.0 API)
io.reactiverse.reactivex.pgclient

Class Json



  • public class Json
    extends Object
    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.reactivex.TypeArg<Json> __TYPE_ARG
    • Constructor Detail

      • Json

        public Json(Json delegate)

Copyright © 2018 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/PgClient.html ================================================ PgClient (Reactive Postgres Client 0.11.2 API)
io.reactiverse.reactivex.pgclient

Class PgClient

  • Direct Known Subclasses:
    PgConnection, PgPool, PgTransaction


    public class PgClient
    extends Object
    Defines the client operations with a Postgres Database.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/PgConnection.html ================================================ PgConnection (Reactive Postgres Client 0.11.2 API)
io.reactiverse.reactivex.pgclient

Class PgConnection



  • public class PgConnection
    extends PgClient
    A connection to Postgres.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rx.TypeArg<PgConnection> __TYPE_ARG
    • Constructor Detail

    • Method Detail

      • prepare

        public PgConnection prepare(String sql,
                                    io.vertx.core.Handler<io.vertx.core.AsyncResult<PgPreparedQuery>> handler)
        Create a prepared query.
        Parameters:
        sql - the sql
        handler - the handler notified with the prepared query asynchronously
        Returns:
      • exceptionHandler

        public PgConnection exceptionHandler(io.vertx.core.Handler<Throwable> handler)
        Set an handler called with connection errors.
        Parameters:
        handler - the handler
        Returns:
        a reference to this, so the API can be used fluently
      • closeHandler

        public PgConnection closeHandler(io.vertx.core.Handler<Void> handler)
        Set an handler called when the connection is closed.
        Parameters:
        handler - the handler
        Returns:
        a reference to this, so the API can be used fluently
      • begin

        public PgTransaction begin()
        Begin a transaction and returns a PgTransaction for controlling and tracking this transaction.

        When the connection is explicitely closed, any inflight transaction is rollbacked.

        Returns:
        the transaction instance
      • notificationHandler

        public PgConnection notificationHandler(io.vertx.core.Handler<PgNotification> handler)
        Set an handler called when the connection receives notification on a channel.

        The handler is called with the PgNotification and has access to the channel name and the notification payload.

        Parameters:
        handler - the handler
        Returns:
        the transaction instance
      • processId

        public int processId()
        Returns:
        The process ID of the target backend
      • secretKey

        public int secretKey()
        Returns:
        The secret key for the target backend
      • cancelRequest

        public PgConnection cancelRequest(io.vertx.core.Handler<io.vertx.core.AsyncResult<Void>> handler)
        Send a request cancellation message to tell the server to cancel processing request in this connection.
        Note: Use this with caution because the cancellation signal may or may not have any effect.
        Parameters:
        handler - the handler notified if cancelling request is sent
        Returns:
        a reference to this, so the API can be used fluently
      • isSSL

        public boolean isSSL()
        Returns:
        whether the connection uses SSL
      • close

        public void close()
        Close the current connection after all the pending commands have been processed.
      • preparedQuery

        public PgConnection preparedQuery(String sql,
                                          io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from class: PgClient
        Prepare and execute a query.
        Overrides:
        preparedQuery in class PgClient
        Parameters:
        sql - the prepared query SQL
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • rxPreparedQuery

        public Single<PgRowSet> rxPreparedQuery(String sql)
        Description copied from class: PgClient
        Prepare and execute a query.
        Overrides:
        rxPreparedQuery in class PgClient
        Parameters:
        sql - the prepared query SQL
        Returns:
        a reference to this, so the API can be used fluently
      • query

        public PgConnection query(String sql,
                                  io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from class: PgClient
        Execute a simple query.
        Overrides:
        query in class PgClient
        Parameters:
        sql - the query SQL
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • rxQuery

        public Single<PgRowSet> rxQuery(String sql)
        Description copied from class: PgClient
        Execute a simple query.
        Overrides:
        rxQuery in class PgClient
        Parameters:
        sql - the query SQL
        Returns:
        a reference to this, so the API can be used fluently
      • preparedQuery

        public PgConnection preparedQuery(String sql,
                                          Tuple arguments,
                                          io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from class: PgClient
        Prepare and execute a query.
        Overrides:
        preparedQuery in class PgClient
        Parameters:
        sql - the prepared query SQL
        arguments - the list of arguments
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • rxPreparedQuery

        public Single<PgRowSet> rxPreparedQuery(String sql,
                                                Tuple arguments)
        Description copied from class: PgClient
        Prepare and execute a query.
        Overrides:
        rxPreparedQuery in class PgClient
        Parameters:
        sql - the prepared query SQL
        arguments - the list of arguments
        Returns:
        a reference to this, so the API can be used fluently
      • preparedBatch

        public PgConnection preparedBatch(String sql,
                                          List<Tuple> batch,
                                          io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from class: PgClient
        Prepare and execute a createBatch.
        Overrides:
        preparedBatch in class PgClient
        Parameters:
        sql - the prepared query SQL
        batch - the batch of tuples
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • rxPreparedBatch

        public Single<PgRowSet> rxPreparedBatch(String sql,
                                                List<Tuple> batch)
        Description copied from class: PgClient
        Prepare and execute a createBatch.
        Overrides:
        rxPreparedBatch in class PgClient
        Parameters:
        sql - the prepared query SQL
        batch - the batch of tuples
        Returns:
        a reference to this, so the API can be used fluently

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/PgCursor.html ================================================ PgCursor (Reactive Postgres Client 0.11.2 API)
io.reactiverse.reactivex.pgclient

Class PgCursor



  • public class PgCursor
    extends Object
    A cursor that reads progressively the rows from Postgres, it is usefull for reading very large result.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rx.TypeArg<PgCursor> __TYPE_ARG
    • Constructor Detail

      • PgCursor

        public PgCursor(PgCursor delegate)
    • Method Detail

      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Object
      • getDelegate

        public PgCursor getDelegate()
      • read

        public void read(int count,
                         io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Read rows from the cursor, the result is provided asynchronously to the handler.
        Parameters:
        count - the amount of rows to read
        handler - the handler for the result
      • rxRead

        public Single<PgRowSet> rxRead(int count)
        Read rows from the cursor, the result is provided asynchronously to the handler.
        Parameters:
        count - the amount of rows to read
        Returns:
      • hasMore

        public boolean hasMore()
        Returns true when the cursor has results in progress and the should be called to retrieve them.
        Returns:
        whether the cursor has more results,
      • close

        public void close()
        Release the cursor.

        It should be called for prepared queries executed with a fetch size.

      • close

        public void close(io.vertx.core.Handler<io.vertx.core.AsyncResult<Void>> completionHandler)
        Like close() but with a completionHandler called when the cursor has been released.
        Parameters:
        completionHandler -
      • rxClose

        public Completable rxClose()
        Like close() but with a completionHandler called when the cursor has been released.
        Returns:

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/PgIterator.html ================================================ PgIterator (Reactive Postgres Client 0.11.2 API)
io.reactiverse.reactivex.pgclient

Class PgIterator



  • public class PgIterator
    extends Object
    An iterator for processing postgres items synchronously.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/PgPool.html ================================================ PgPool (Reactive Postgres Client 0.11.2 API)
io.reactiverse.reactivex.pgclient

Class PgPool



  • public class PgPool
    extends PgClient
    A pool of connection.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rx.TypeArg<PgPool> __TYPE_ARG
    • Constructor Detail

      • PgPool

        public PgPool(PgPool delegate)
    • Method Detail

      • preparedQuery

        public PgPool preparedQuery(String sql,
                                    io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from class: PgClient
        Prepare and execute a query.
        Overrides:
        preparedQuery in class PgClient
        Parameters:
        sql - the prepared query SQL
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • rxPreparedQuery

        public Single<PgRowSet> rxPreparedQuery(String sql)
        Description copied from class: PgClient
        Prepare and execute a query.
        Overrides:
        rxPreparedQuery in class PgClient
        Parameters:
        sql - the prepared query SQL
        Returns:
        a reference to this, so the API can be used fluently
      • query

        public PgPool query(String sql,
                            io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from class: PgClient
        Execute a simple query.
        Overrides:
        query in class PgClient
        Parameters:
        sql - the query SQL
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • rxQuery

        public Single<PgRowSet> rxQuery(String sql)
        Description copied from class: PgClient
        Execute a simple query.
        Overrides:
        rxQuery in class PgClient
        Parameters:
        sql - the query SQL
        Returns:
        a reference to this, so the API can be used fluently
      • preparedQuery

        public PgPool preparedQuery(String sql,
                                    Tuple arguments,
                                    io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from class: PgClient
        Prepare and execute a query.
        Overrides:
        preparedQuery in class PgClient
        Parameters:
        sql - the prepared query SQL
        arguments - the list of arguments
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • rxPreparedQuery

        public Single<PgRowSet> rxPreparedQuery(String sql,
                                                Tuple arguments)
        Description copied from class: PgClient
        Prepare and execute a query.
        Overrides:
        rxPreparedQuery in class PgClient
        Parameters:
        sql - the prepared query SQL
        arguments - the list of arguments
        Returns:
        a reference to this, so the API can be used fluently
      • preparedBatch

        public PgPool preparedBatch(String sql,
                                    List<Tuple> batch,
                                    io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from class: PgClient
        Prepare and execute a createBatch.
        Overrides:
        preparedBatch in class PgClient
        Parameters:
        sql - the prepared query SQL
        batch - the batch of tuples
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • rxPreparedBatch

        public Single<PgRowSet> rxPreparedBatch(String sql,
                                                List<Tuple> batch)
        Description copied from class: PgClient
        Prepare and execute a createBatch.
        Overrides:
        rxPreparedBatch in class PgClient
        Parameters:
        sql - the prepared query SQL
        batch - the batch of tuples
        Returns:
        a reference to this, so the API can be used fluently
      • getConnection

        public void getConnection(io.vertx.core.Handler<io.vertx.core.AsyncResult<PgConnection>> handler)
        Get a connection from the pool.
        Parameters:
        handler - the handler that will get the connection result
      • rxGetConnection

        public Single<PgConnection> rxGetConnection()
        Get a connection from the pool.
        Returns:
      • begin

        public void begin(io.vertx.core.Handler<io.vertx.core.AsyncResult<PgTransaction>> handler)
        Borrow a connection from the pool and begin a transaction, the underlying connection will be returned to the pool when the transaction ends.
        Parameters:
        handler -
      • rxBegin

        public Single<PgTransaction> rxBegin()
        Borrow a connection from the pool and begin a transaction, the underlying connection will be returned to the pool when the transaction ends.
        Returns:
        the transaction
      • close

        public void close()
        Close the pool and release the associated resources.
      • newInstance

        public static PgPool newInstance(PgPool arg)

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/PgPreparedQuery.html ================================================ PgPreparedQuery (Reactive Postgres Client 0.11.2 API)
io.reactiverse.reactivex.pgclient

Class PgPreparedQuery



  • public class PgPreparedQuery
    extends Object
    A prepared query.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rx.TypeArg<PgPreparedQuery> __TYPE_ARG
    • Constructor Detail

    • Method Detail

      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Object
      • execute

        public PgPreparedQuery execute(Tuple args,
                                       io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Create a cursor with the provided arguments.
        Parameters:
        args - the list of arguments
        handler -
        Returns:
        the query
      • rxExecute

        public Single<PgRowSet> rxExecute(Tuple args)
        Create a cursor with the provided arguments.
        Parameters:
        args - the list of arguments
        Returns:
        the query
      • cursor

        public PgCursor cursor()
        Returns:
        create a query cursor with a fetch size and empty arguments
      • cursor

        public PgCursor cursor(Tuple args)
        Create a cursor with the provided arguments.
        Parameters:
        args - the list of arguments
        Returns:
        the query
      • createStream

        public PgStream<Row> createStream(int fetch,
                                          Tuple args)
        Execute the prepared query with a cursor and createStream the result. The createStream opens a cursor with a fetch size to fetch the results.

        Note: this requires to be in a transaction, since cursors require it.

        Parameters:
        fetch - the cursor fetch size
        args - the prepared query arguments
        Returns:
        the createStream
      • batch

        public PgPreparedQuery batch(List<Tuple> argsList,
                                     io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Execute a batch.
        Parameters:
        argsList - the list of tuple for the batch
        handler -
        Returns:
        the createBatch
      • rxBatch

        public Single<PgRowSet> rxBatch(List<Tuple> argsList)
        Execute a batch.
        Parameters:
        argsList - the list of tuple for the batch
        Returns:
        the createBatch
      • close

        public void close()
        Close the prepared query and release its resources.
      • close

        public void close(io.vertx.core.Handler<io.vertx.core.AsyncResult<Void>> completionHandler)
        Like close() but notifies the completionHandler when it's closed.
        Parameters:
        completionHandler -
      • rxClose

        public Completable rxClose()
        Like close() but notifies the completionHandler when it's closed.
        Returns:

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/PgResult.html ================================================ PgResult (Reactive Postgres Client 0.11.2 API)
io.reactiverse.reactivex.pgclient

Class PgResult<T>

  • Direct Known Subclasses:
    PgRowSet


    public class PgResult<T>
    extends Object
    Represents the result of an operation on database.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rx.TypeArg<PgResult> __TYPE_ARG
      • __typeArg_0

        public final io.vertx.lang.rx.TypeArg<T> __typeArg_0
    • Constructor Detail

      • PgResult

        public PgResult(PgResult delegate)
      • PgResult

        public PgResult(PgResult delegate,
                        io.vertx.lang.rx.TypeArg<T> typeArg_0)
    • Method Detail

      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Object
      • getDelegate

        public PgResult getDelegate()
      • rowCount

        public int rowCount()
        Get the number of the affected rows in the operation to this PgResult.

        The meaning depends on the executed statement:

        • INSERT: the number of rows inserted
        • DELETE: the number of rows deleted
        • UPDATE: the number of rows updated
        • SELECT: the number of rows retrieved
        Returns:
        the count of affected rows.
      • columnsNames

        public List<String> columnsNames()
        Get the names of columns in the PgResult.
        Returns:
        the list of names of columns.
      • size

        public int size()
        Get the number of rows in the PgResult.
        Returns:
        the count of rows.
      • value

        public T value()
        Get the result value.
        Returns:
        the result
      • next

        public PgResult<T> next()
        Return the next available result or null, e.g for a simple query that executed multiple queries or for a batch result.
        Returns:
        the next available result or null if none is available
      • newInstance

        public static <T> PgResult<T> newInstance(PgResult arg,
                                                  io.vertx.lang.rx.TypeArg<T> __typeArg_T)

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/PgRowSet.html ================================================ PgRowSet (Reactive Postgres Client 0.11.2 API)
io.reactiverse.reactivex.pgclient

Class PgRowSet



  • public class PgRowSet
    extends PgResult<PgRowSet>
    A set of rows.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/PgStream.html ================================================ PgStream (Reactive Postgres Client 0.11.2 API)
io.reactiverse.reactivex.pgclient

Class PgStream<T>

  • All Implemented Interfaces:
    io.vertx.reactivex.core.streams.ReadStream<T>, io.vertx.reactivex.core.streams.StreamBase


    public class PgStream<T>
    extends Object
    implements io.vertx.reactivex.core.streams.ReadStream<T>
    A row oriented stream.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rx.TypeArg<PgStream> __TYPE_ARG
      • __typeArg_0

        public final io.vertx.lang.rx.TypeArg<T> __typeArg_0
    • Constructor Detail

      • PgStream

        public PgStream(PgStream delegate)
      • PgStream

        public PgStream(PgStream delegate,
                        io.vertx.lang.rx.TypeArg<T> typeArg_0)
    • Method Detail

      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Object
      • getDelegate

        public PgStream getDelegate()
        Specified by:
        getDelegate in interface io.vertx.reactivex.core.streams.ReadStream<T>
        Specified by:
        getDelegate in interface io.vertx.reactivex.core.streams.StreamBase
      • toObservable

        public Observable<T> toObservable()
        Specified by:
        toObservable in interface io.vertx.reactivex.core.streams.ReadStream<T>
      • toFlowable

        public Flowable<T> toFlowable()
        Specified by:
        toFlowable in interface io.vertx.reactivex.core.streams.ReadStream<T>
      • fetch

        public io.vertx.reactivex.core.streams.ReadStream<T> fetch(long arg0)
        Specified by:
        fetch in interface io.vertx.reactivex.core.streams.ReadStream<T>
      • exceptionHandler

        public PgStream<T> exceptionHandler(io.vertx.core.Handler<Throwable> handler)
        Specified by:
        exceptionHandler in interface io.vertx.reactivex.core.streams.ReadStream<T>
        Specified by:
        exceptionHandler in interface io.vertx.reactivex.core.streams.StreamBase
      • handler

        public PgStream<T> handler(io.vertx.core.Handler<T> handler)
        Specified by:
        handler in interface io.vertx.reactivex.core.streams.ReadStream<T>
      • pause

        public PgStream<T> pause()
        Specified by:
        pause in interface io.vertx.reactivex.core.streams.ReadStream<T>
      • resume

        public PgStream<T> resume()
        Specified by:
        resume in interface io.vertx.reactivex.core.streams.ReadStream<T>
      • endHandler

        public PgStream<T> endHandler(io.vertx.core.Handler<Void> endHandler)
        Specified by:
        endHandler in interface io.vertx.reactivex.core.streams.ReadStream<T>
      • close

        public void close()
        Close the stream and release the resources.
      • close

        public void close(io.vertx.core.Handler<io.vertx.core.AsyncResult<Void>> completionHandler)
        Close the stream and release the resources.
        Parameters:
        completionHandler - the completion handler for this operation
      • rxClose

        public Completable rxClose()
        Close the stream and release the resources.
        Returns:
      • newInstance

        public static <T> PgStream<T> newInstance(PgStream arg,
                                                  io.vertx.lang.rx.TypeArg<T> __typeArg_T)

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/PgTransaction.html ================================================ PgTransaction (Reactive Postgres Client 0.11.2 API)
io.reactiverse.reactivex.pgclient

Class PgTransaction



  • public class PgTransaction
    extends PgClient
    A transaction that allows to control the transaction and receive events.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rx.TypeArg<PgTransaction> __TYPE_ARG
    • Constructor Detail

    • Method Detail

      • prepare

        public PgTransaction prepare(String sql,
                                     io.vertx.core.Handler<io.vertx.core.AsyncResult<PgPreparedQuery>> handler)
        Create a prepared query.
        Parameters:
        sql - the sql
        handler - the handler notified with the prepared query asynchronously
        Returns:
      • commit

        public void commit()
        Commit the current transaction.
      • commit

        public void commit(io.vertx.core.Handler<io.vertx.core.AsyncResult<Void>> handler)
        Like commit() with an handler to be notified when the transaction commit has completed
        Parameters:
        handler -
      • rxCommit

        public Completable rxCommit()
        Like commit() with an handler to be notified when the transaction commit has completed
        Returns:
      • rollback

        public void rollback()
        Rollback the current transaction.
      • rollback

        public void rollback(io.vertx.core.Handler<io.vertx.core.AsyncResult<Void>> handler)
        Like rollback() with an handler to be notified when the transaction rollback has completed
        Parameters:
        handler -
      • rxRollback

        public Completable rxRollback()
        Like rollback() with an handler to be notified when the transaction rollback has completed
        Returns:
      • abortHandler

        public PgTransaction abortHandler(io.vertx.core.Handler<Void> handler)
        Set an handler to be called when the transaction is aborted.
        Parameters:
        handler - the handler
        Returns:
      • query

        public PgTransaction query(String sql,
                                   io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from class: PgClient
        Execute a simple query.
        Overrides:
        query in class PgClient
        Parameters:
        sql - the query SQL
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • rxQuery

        public Single<PgRowSet> rxQuery(String sql)
        Description copied from class: PgClient
        Execute a simple query.
        Overrides:
        rxQuery in class PgClient
        Parameters:
        sql - the query SQL
        Returns:
        a reference to this, so the API can be used fluently
      • preparedQuery

        public PgTransaction preparedQuery(String sql,
                                           io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from class: PgClient
        Prepare and execute a query.
        Overrides:
        preparedQuery in class PgClient
        Parameters:
        sql - the prepared query SQL
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • rxPreparedQuery

        public Single<PgRowSet> rxPreparedQuery(String sql)
        Description copied from class: PgClient
        Prepare and execute a query.
        Overrides:
        rxPreparedQuery in class PgClient
        Parameters:
        sql - the prepared query SQL
        Returns:
        a reference to this, so the API can be used fluently
      • preparedQuery

        public PgTransaction preparedQuery(String sql,
                                           Tuple arguments,
                                           io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from class: PgClient
        Prepare and execute a query.
        Overrides:
        preparedQuery in class PgClient
        Parameters:
        sql - the prepared query SQL
        arguments - the list of arguments
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • rxPreparedQuery

        public Single<PgRowSet> rxPreparedQuery(String sql,
                                                Tuple arguments)
        Description copied from class: PgClient
        Prepare and execute a query.
        Overrides:
        rxPreparedQuery in class PgClient
        Parameters:
        sql - the prepared query SQL
        arguments - the list of arguments
        Returns:
        a reference to this, so the API can be used fluently
      • preparedBatch

        public PgTransaction preparedBatch(String sql,
                                           List<Tuple> batch,
                                           io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from class: PgClient
        Prepare and execute a createBatch.
        Overrides:
        preparedBatch in class PgClient
        Parameters:
        sql - the prepared query SQL
        batch - the batch of tuples
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • rxPreparedBatch

        public Single<PgRowSet> rxPreparedBatch(String sql,
                                                List<Tuple> batch)
        Description copied from class: PgClient
        Prepare and execute a createBatch.
        Overrides:
        rxPreparedBatch in class PgClient
        Parameters:
        sql - the prepared query SQL
        batch - the batch of tuples
        Returns:
        a reference to this, so the API can be used fluently

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/Row.html ================================================ Row (Reactive Postgres Client 0.11.2 API)
io.reactiverse.reactivex.pgclient

Class Row



  • public class Row
    extends Tuple
    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rx.TypeArg<Row> __TYPE_ARG
    • Constructor Detail

      • Row

        public Row(Row delegate)
    • Method Detail

      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Tuple
      • getColumnName

        public String getColumnName(int pos)
        Get a column name at pos.
        Parameters:
        pos - the position
        Returns:
        the column name or null
      • getBoolean

        public Boolean getBoolean(String name)
        Get a boolean value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getValue

        public Object getValue(String name)
        Get an object value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getShort

        public Short getShort(String name)
        Get a short value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getInteger

        public Integer getInteger(String name)
        Get an integer value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLong

        public Long getLong(String name)
        Get a long value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getFloat

        public Float getFloat(String name)
        Get a float value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getDouble

        public Double getDouble(String name)
        Get a double value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getString

        public String getString(String name)
        Get a string value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getJson

        public Json getJson(String name)
        Get a json value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getBuffer

        public io.vertx.reactivex.core.buffer.Buffer getBuffer(String name)
        Get a buffer value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getPoint

        public Point getPoint(String name)
        Get value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLine

        public Line getLine(String name)
        Get value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLineSegment

        public LineSegment getLineSegment(String name)
        Get value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getBox

        public Box getBox(String name)
        Get value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getPath

        public Path getPath(String name)
        Get value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getPolygon

        public Polygon getPolygon(String name)
        Get value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getCircle

        public Circle getCircle(String name)
        Get value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getInterval

        public Interval getInterval(String name)
        Get value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getTemporal

        public Temporal getTemporal(String name)
        Get a temporal value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLocalDate

        public LocalDate getLocalDate(String name)
        Get LocalDate value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLocalTime

        public LocalTime getLocalTime(String name)
        Get LocalTime value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLocalDateTime

        public LocalDateTime getLocalDateTime(String name)
        Get LocalDateTime value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getOffsetTime

        public OffsetTime getOffsetTime(String name)
        Get OffsetTime value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getUUID

        public UUID getUUID(String name)
        Get UUID value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getBigDecimal

        public BigDecimal getBigDecimal(String name)
        Get value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getNumeric

        public Numeric getNumeric(String name)
        Get value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getIntegerArray

        public Integer[] getIntegerArray(String name)
        Get an array of Integer value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getBooleanArray

        public Boolean[] getBooleanArray(String name)
        Get an array of Boolean value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getShortArray

        public Short[] getShortArray(String name)
        Get an array of Short value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLongArray

        public Long[] getLongArray(String name)
        Get an array of Long value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getFloatArray

        public Float[] getFloatArray(String name)
        Get an array of Float value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getDoubleArray

        public Double[] getDoubleArray(String name)
        Get an array of Double value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getStringArray

        public String[] getStringArray(String name)
        Get an array of String value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLocalDateArray

        public LocalDate[] getLocalDateArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLocalTimeArray

        public LocalTime[] getLocalTimeArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getOffsetTimeArray

        public OffsetTime[] getOffsetTimeArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLocalDateTimeArray

        public LocalDateTime[] getLocalDateTimeArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getOffsetDateTimeArray

        public OffsetDateTime[] getOffsetDateTimeArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getUUIDArray

        public UUID[] getUUIDArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getNumericArray

        public Numeric[] getNumericArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getPointArray

        public Point[] getPointArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLineArray

        public Line[] getLineArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLineSegmentArray

        public LineSegment[] getLineSegmentArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getBoxArray

        public Box[] getBoxArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getPathArray

        public Path[] getPathArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getPolygonArray

        public Polygon[] getPolygonArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getCircleArray

        public Circle[] getCircleArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getIntervalArray

        public Interval[] getIntervalArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • newInstance

        public static Row newInstance(Row arg)

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/Tuple.html ================================================ Tuple (Reactive Postgres Client 0.11.2 API)
io.reactiverse.reactivex.pgclient

Class Tuple

  • Direct Known Subclasses:
    Row


    public class Tuple
    extends Object
    A general purpose tuple.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rx.TypeArg<Tuple> __TYPE_ARG
    • Constructor Detail

      • Tuple

        public Tuple(Tuple delegate)
    • Method Detail

      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Object
      • getDelegate

        public Tuple getDelegate()
      • tuple

        public static Tuple tuple()
        Returns:
        a new empty tuple
      • of

        public static Tuple of(Object elt1)
        Create a tuple of one element.
        Parameters:
        elt1 - the first value
        Returns:
        the tuple
      • of

        public static Tuple of(Object elt1,
                               Object elt2)
        Create a tuple of two elements.
        Parameters:
        elt1 - the first value
        elt2 - the second value
        Returns:
        the tuple
      • of

        public static Tuple of(Object elt1,
                               Object elt2,
                               Object elt3)
        Create a tuple of three elements.
        Parameters:
        elt1 - the first value
        elt2 - the second value
        elt3 - the third value
        Returns:
        the tuple
      • of

        public static Tuple of(Object elt1,
                               Object elt2,
                               Object elt3,
                               Object elt4)
        Create a tuple of four elements.
        Parameters:
        elt1 - the first value
        elt2 - the second value
        elt3 - the third value
        elt4 - the fourth value
        Returns:
        the tuple
      • of

        public static Tuple of(Object elt1,
                               Object elt2,
                               Object elt3,
                               Object elt4,
                               Object elt5)
        Create a tuple of five elements.
        Parameters:
        elt1 - the first value
        elt2 - the second value
        elt3 - the third value
        elt4 - the fourth value
        elt5 - the fifth value
        Returns:
        the tuple
      • of

        public static Tuple of(Object elt1,
                               Object elt2,
                               Object elt3,
                               Object elt4,
                               Object elt5,
                               Object elt6)
        Create a tuple of six elements.
        Parameters:
        elt1 - the first value
        elt2 - the second valueg
        elt3 - the third value
        elt4 - the fourth value
        elt5 - the fifth value
        elt6 - the sixth value
        Returns:
        the tuple
      • getBoolean

        public Boolean getBoolean(int pos)
        Get a boolean value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getValue

        public Object getValue(int pos)
        Get an object value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getShort

        public Short getShort(int pos)
        Get a short value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getInteger

        public Integer getInteger(int pos)
        Get an integer value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLong

        public Long getLong(int pos)
        Get a long value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getFloat

        public Float getFloat(int pos)
        Get a float value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getDouble

        public Double getDouble(int pos)
        Get a double value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getString

        public String getString(int pos)
        Get a string value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getJson

        public Json getJson(int pos)
        Get a json value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getPoint

        public Point getPoint(int pos)
        Get value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLine

        public Line getLine(int pos)
        Get value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLineSegment

        public LineSegment getLineSegment(int pos)
        Get value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getBox

        public Box getBox(int pos)
        Get value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getPath

        public Path getPath(int pos)
        Get value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getPolygon

        public Polygon getPolygon(int pos)
        Get value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getCircle

        public Circle getCircle(int pos)
        Get value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getInterval

        public Interval getInterval(int pos)
        Get value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getBuffer

        public io.vertx.reactivex.core.buffer.Buffer getBuffer(int pos)
        Get a buffer value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • addBoolean

        public Tuple addBoolean(Boolean value)
        Add a boolean value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addValue

        public Tuple addValue(Object value)
        Add an object value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addShort

        public Tuple addShort(Short value)
        Add a short value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addInteger

        public Tuple addInteger(Integer value)
        Add an integer value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLong

        public Tuple addLong(Long value)
        Add a long value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addFloat

        public Tuple addFloat(Float value)
        Add a float value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addDouble

        public Tuple addDouble(Double value)
        Add a double value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addString

        public Tuple addString(String value)
        Add a string value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addJson

        public Tuple addJson(Json value)
        Add a json value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addBuffer

        public Tuple addBuffer(io.vertx.reactivex.core.buffer.Buffer value)
        Add a buffer value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addPoint

        public Tuple addPoint(Point value)
        Add a value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLine

        public Tuple addLine(Line value)
        Add a value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLineSegment

        public Tuple addLineSegment(LineSegment value)
        Add a value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addBox

        public Tuple addBox(Box value)
        Add a value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addPath

        public Tuple addPath(Path value)
        Add a value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addPolygon

        public Tuple addPolygon(Polygon value)
        Add a value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addCircle

        public Tuple addCircle(Circle value)
        Add a value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addInterval

        public Tuple addInterval(Interval value)
        Add a value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • size

        public int size()
        Returns:
        the tuple size
      • clear

        public void clear()
      • getTemporal

        public Temporal getTemporal(int pos)
        Get a Temporal value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLocalDate

        public LocalDate getLocalDate(int pos)
        Get LocalDate value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLocalTime

        public LocalTime getLocalTime(int pos)
        Get LocalTime value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLocalDateTime

        public LocalDateTime getLocalDateTime(int pos)
        Get LocalDateTime value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getOffsetTime

        public OffsetTime getOffsetTime(int pos)
        Get OffsetTime value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getOffsetDateTime

        public OffsetDateTime getOffsetDateTime(int pos)
        Get OffsetDateTime value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getUUID

        public UUID getUUID(int pos)
        Get UUID value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getBigDecimal

        public BigDecimal getBigDecimal(int pos)
        Get value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getIntegerArray

        public Integer[] getIntegerArray(int pos)
        Get an array of Integer value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getBooleanArray

        public Boolean[] getBooleanArray(int pos)
        Get an array of Boolean value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getShortArray

        public Short[] getShortArray(int pos)
        Get an array of Short value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLongArray

        public Long[] getLongArray(int pos)
        Get an array of Long value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getFloatArray

        public Float[] getFloatArray(int pos)
        Get an array of Float value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getDoubleArray

        public Double[] getDoubleArray(int pos)
        Get an array of Double value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getStringArray

        public String[] getStringArray(int pos)
        Get an array of String value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLocalDateArray

        public LocalDate[] getLocalDateArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLocalTimeArray

        public LocalTime[] getLocalTimeArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getOffsetTimeArray

        public OffsetTime[] getOffsetTimeArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLocalDateTimeArray

        public LocalDateTime[] getLocalDateTimeArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getOffsetDateTimeArray

        public OffsetDateTime[] getOffsetDateTimeArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getUUIDArray

        public UUID[] getUUIDArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getNumericArray

        public Numeric[] getNumericArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getPointArray

        public Point[] getPointArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getLineArray

        public Line[] getLineArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getLineSegmentArray

        public LineSegment[] getLineSegmentArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getBoxArray

        public Box[] getBoxArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getPathArray

        public Path[] getPathArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getPolygonArray

        public Polygon[] getPolygonArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getCircleArray

        public Circle[] getCircleArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getIntervalArray

        public Interval[] getIntervalArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getNumeric

        public Numeric getNumeric(int pos)
        Get value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • addTemporal

        public Tuple addTemporal(Temporal value)
        Add a Temporal value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLocalDate

        public Tuple addLocalDate(LocalDate value)
        Add a LocalDate value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLocalTime

        public Tuple addLocalTime(LocalTime value)
        Add a LocalTime value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLocalDateTime

        public Tuple addLocalDateTime(LocalDateTime value)
        Add a LocalDateTime value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addOffsetTime

        public Tuple addOffsetTime(OffsetTime value)
        Add a OffsetTime value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addOffsetDateTime

        public Tuple addOffsetDateTime(OffsetDateTime value)
        Add a OffsetDateTime value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addUUID

        public Tuple addUUID(UUID value)
        Add a UUID value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addNumeric

        public Tuple addNumeric(Numeric value)
        Add a value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addBigDecimal

        public Tuple addBigDecimal(BigDecimal value)
        Add a value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addIntegerArray

        public Tuple addIntegerArray(Integer[] value)
        Add an array of Integer value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addBooleanArray

        public Tuple addBooleanArray(Boolean[] value)
        Add an array of Boolean value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addShortArray

        public Tuple addShortArray(Short[] value)
        Add an array of Short value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLongArray

        public Tuple addLongArray(Long[] value)
        Add an array of Long value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addFloatArray

        public Tuple addFloatArray(Float[] value)
        Add an array of Float value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addDoubleArray

        public Tuple addDoubleArray(Double[] value)
        Add an array of Double value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addStringArray

        public Tuple addStringArray(String[] value)
        Add an array of String value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLocalDateArray

        public Tuple addLocalDateArray(LocalDate[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLocalTimeArray

        public Tuple addLocalTimeArray(LocalTime[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addOffsetTimeArray

        public Tuple addOffsetTimeArray(OffsetTime[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLocalDateTimeArray

        public Tuple addLocalDateTimeArray(LocalDateTime[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addOffsetDateTimeArray

        public Tuple addOffsetDateTimeArray(OffsetDateTime[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addUUIDArray

        public Tuple addUUIDArray(UUID[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addNumericArray

        public Tuple addNumericArray(Numeric[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addPointArray

        public Tuple addPointArray(Point[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLineArray

        public Tuple addLineArray(Line[] value)
        Add an array of Line value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLineSegmentArray

        public Tuple addLineSegmentArray(LineSegment[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addBoxArray

        public Tuple addBoxArray(Box[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addPathArray

        public Tuple addPathArray(Path[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addPolygonArray

        public Tuple addPolygonArray(Polygon[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addCircleArray

        public Tuple addCircleArray(Circle[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addIntervalArray

        public Tuple addIntervalArray(Interval[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • newInstance

        public static Tuple newInstance(Tuple arg)

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/class-use/Json.html ================================================ Uses of Class io.reactiverse.reactivex.pgclient.Json (Reactive Postgres Client 0.9.0 API)

Uses of Class
io.reactiverse.reactivex.pgclient.Json

Copyright © 2018 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/class-use/PgClient.html ================================================ Uses of Class io.reactiverse.reactivex.pgclient.PgClient (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.reactivex.pgclient.PgClient

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/class-use/PgConnection.html ================================================ Uses of Class io.reactiverse.reactivex.pgclient.PgConnection (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.reactivex.pgclient.PgConnection

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/class-use/PgCursor.html ================================================ Uses of Class io.reactiverse.reactivex.pgclient.PgCursor (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.reactivex.pgclient.PgCursor

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/class-use/PgIterator.html ================================================ Uses of Class io.reactiverse.reactivex.pgclient.PgIterator (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.reactivex.pgclient.PgIterator

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/class-use/PgPool.html ================================================ Uses of Class io.reactiverse.reactivex.pgclient.PgPool (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.reactivex.pgclient.PgPool

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/class-use/PgPreparedQuery.html ================================================ Uses of Class io.reactiverse.reactivex.pgclient.PgPreparedQuery (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.reactivex.pgclient.PgPreparedQuery

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/class-use/PgResult.html ================================================ Uses of Class io.reactiverse.reactivex.pgclient.PgResult (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.reactivex.pgclient.PgResult

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/class-use/PgRowSet.html ================================================ Uses of Class io.reactiverse.reactivex.pgclient.PgRowSet (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.reactivex.pgclient.PgRowSet

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/class-use/PgStream.html ================================================ Uses of Class io.reactiverse.reactivex.pgclient.PgStream (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.reactivex.pgclient.PgStream

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/class-use/PgTransaction.html ================================================ Uses of Class io.reactiverse.reactivex.pgclient.PgTransaction (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.reactivex.pgclient.PgTransaction

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/class-use/Row.html ================================================ Uses of Class io.reactiverse.reactivex.pgclient.Row (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.reactivex.pgclient.Row

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/class-use/Tuple.html ================================================ Uses of Class io.reactiverse.reactivex.pgclient.Tuple (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.reactivex.pgclient.Tuple

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/data/Json.html ================================================ Json (Reactive Postgres Client 0.11.2 API)
io.reactiverse.reactivex.pgclient.data

Class Json



  • public class Json
    extends Object
    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rx.TypeArg<Json> __TYPE_ARG
    • Constructor Detail

      • Json

        public Json(Json delegate)

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/data/class-use/Json.html ================================================ Uses of Class io.reactiverse.reactivex.pgclient.data.Json (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.reactivex.pgclient.data.Json

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/data/package-frame.html ================================================ io.reactiverse.reactivex.pgclient.data (Reactive Postgres Client 0.11.2 API)

io.reactiverse.reactivex.pgclient.data

Classes

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/data/package-summary.html ================================================ io.reactiverse.reactivex.pgclient.data (Reactive Postgres Client 0.11.2 API)

Package io.reactiverse.reactivex.pgclient.data

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/data/package-tree.html ================================================ io.reactiverse.reactivex.pgclient.data Class Hierarchy (Reactive Postgres Client 0.11.2 API)

Hierarchy For Package io.reactiverse.reactivex.pgclient.data

Package Hierarchies:

Class Hierarchy

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/data/package-use.html ================================================ Uses of Package io.reactiverse.reactivex.pgclient.data (Reactive Postgres Client 0.11.2 API)

Uses of Package
io.reactiverse.reactivex.pgclient.data

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/package-frame.html ================================================ io.reactiverse.reactivex.pgclient (Reactive Postgres Client 0.11.2 API)

io.reactiverse.reactivex.pgclient

Classes

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/package-summary.html ================================================ io.reactiverse.reactivex.pgclient (Reactive Postgres Client 0.11.2 API)

Package io.reactiverse.reactivex.pgclient

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/package-tree.html ================================================ io.reactiverse.reactivex.pgclient Class Hierarchy (Reactive Postgres Client 0.11.2 API)

Hierarchy For Package io.reactiverse.reactivex.pgclient

Package Hierarchies:

Class Hierarchy

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/package-use.html ================================================ Uses of Package io.reactiverse.reactivex.pgclient (Reactive Postgres Client 0.11.2 API)

Uses of Package
io.reactiverse.reactivex.pgclient

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/pubsub/PgChannel.html ================================================ PgChannel (Reactive Postgres Client 0.11.2 API)
io.reactiverse.reactivex.pgclient.pubsub

Class PgChannel

  • All Implemented Interfaces:
    io.vertx.reactivex.core.streams.ReadStream<String>, io.vertx.reactivex.core.streams.StreamBase


    public class PgChannel
    extends Object
    implements io.vertx.reactivex.core.streams.ReadStream<String>
    A channel to Postgres that tracks the subscription to a given Postgres channel using the LISTEN/UNLISTEN commands.

    When paused the channel discards the messages.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rx.TypeArg<PgChannel> __TYPE_ARG
    • Constructor Detail

      • PgChannel

        public PgChannel(PgChannel delegate)
    • Method Detail

      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Object
      • getDelegate

        public PgChannel getDelegate()
        Specified by:
        getDelegate in interface io.vertx.reactivex.core.streams.ReadStream<String>
        Specified by:
        getDelegate in interface io.vertx.reactivex.core.streams.StreamBase
      • toObservable

        public Observable<String> toObservable()
        Specified by:
        toObservable in interface io.vertx.reactivex.core.streams.ReadStream<String>
      • toFlowable

        public Flowable<String> toFlowable()
        Specified by:
        toFlowable in interface io.vertx.reactivex.core.streams.ReadStream<String>
      • fetch

        public io.vertx.reactivex.core.streams.ReadStream<String> fetch(long arg0)
        Specified by:
        fetch in interface io.vertx.reactivex.core.streams.ReadStream<String>
      • subscribeHandler

        public PgChannel subscribeHandler(io.vertx.core.Handler<Void> handler)
        Set an handler called when the the channel get subscribed.
        Parameters:
        handler - the handler
        Returns:
        a reference to this, so the API can be used fluently
      • handler

        public PgChannel handler(io.vertx.core.Handler<String> handler)
        Set or unset an handler to be called when a the channel is notified by Postgres.

        • when the handler is set, the subscriber sends a LISTEN command if needed
        • when the handler is unset, the subscriber sends a UNLISTEN command if needed
        Specified by:
        handler in interface io.vertx.reactivex.core.streams.ReadStream<String>
        Parameters:
        handler - the handler
        Returns:
        a reference to this, so the API can be used fluently
      • pause

        public PgChannel pause()
        Pause the channel, all notifications are discarded.
        Specified by:
        pause in interface io.vertx.reactivex.core.streams.ReadStream<String>
        Returns:
        a reference to this, so the API can be used fluently
      • resume

        public PgChannel resume()
        Resume the channel.
        Specified by:
        resume in interface io.vertx.reactivex.core.streams.ReadStream<String>
        Returns:
        a reference to this, so the API can be used fluently
      • endHandler

        public PgChannel endHandler(io.vertx.core.Handler<Void> endHandler)
        Set an handler to be called when no more notifications will be received.
        Specified by:
        endHandler in interface io.vertx.reactivex.core.streams.ReadStream<String>
        Parameters:
        endHandler - the handler
        Returns:
        a reference to this, so the API can be used fluently
      • exceptionHandler

        public PgChannel exceptionHandler(io.vertx.core.Handler<Throwable> handler)
        Specified by:
        exceptionHandler in interface io.vertx.reactivex.core.streams.ReadStream<String>
        Specified by:
        exceptionHandler in interface io.vertx.reactivex.core.streams.StreamBase

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/pubsub/PgSubscriber.html ================================================ PgSubscriber (Reactive Postgres Client 0.11.2 API)
io.reactiverse.reactivex.pgclient.pubsub

Class PgSubscriber



  • public class PgSubscriber
    extends Object
    A class for managing subscriptions using LISTEN/UNLISTEN to Postgres channels.

    The subscriber manages a single connection to Postgres.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rx.TypeArg<PgSubscriber> __TYPE_ARG
    • Constructor Detail

    • Method Detail

      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Object
      • subscriber

        public static PgSubscriber subscriber(io.vertx.reactivex.core.Vertx vertx,
                                              PgConnectOptions options)
        Create a subscriber.
        Parameters:
        vertx - the vertx instance
        options - the connect options
        Returns:
        the subscriber
      • channel

        public PgChannel channel(String name)
        Return a channel for the given name.
        Parameters:
        name - the channel name

        This will be the name of the channel exactly as held by Postgres for sending notifications. Internally this name will be truncated to the Postgres identifier maxiumum length of (NAMEDATALEN = 64) - 1 == 63 characters, and prepared as a quoted identifier without unicode escape sequence support for use in LISTEN/UNLISTEN commands. Examples of channel names and corresponding NOTIFY commands:

        • when name == "the_channel": NOTIFY the_channel, 'msg', NOTIFY The_Channel, 'msg', or NOTIFY "the_channel", 'msg' succeed in delivering a message to the created channel
        • when name == "The_Channel": NOTIFY "The_Channel", 'msg', succeeds in delivering a message to the created channel
        Returns:
        the channel
      • connect

        public PgSubscriber connect(io.vertx.core.Handler<io.vertx.core.AsyncResult<Void>> handler)
        Connect the subscriber to Postgres.
        Parameters:
        handler - the handler notified of the connection success or failure
        Returns:
        a reference to this, so the API can be used fluently
      • rxConnect

        public Completable rxConnect()
        Connect the subscriber to Postgres.
        Returns:
        a reference to this, so the API can be used fluently
      • reconnectPolicy

        public PgSubscriber reconnectPolicy(Function<Integer,Long> policy)
        Set the reconnect policy that is executed when the subscriber is disconnected.

        When the subscriber is disconnected, the policy function is called with the actual number of retries and returns an amountOfTime value:

        • when amountOfTime < 0: the subscriber is closed and there is no retry
        • when amountOfTime == 0: the subscriber retries to connect immediately
        • when amountOfTime > 0: the subscriber retries after amountOfTime milliseconds

        The default policy does not perform any retries.

        Parameters:
        policy - the policy to set
        Returns:
        a reference to this, so the API can be used fluently
      • closeHandler

        public PgSubscriber closeHandler(io.vertx.core.Handler<Void> handler)
        Set an handler called when the subscriber is closed.
        Parameters:
        handler - the handler
        Returns:
        a reference to this, so the API can be used fluently
      • actualConnection

        public PgConnection actualConnection()
        Returns:
        the actual connection to Postgres, it might be null
      • closed

        public boolean closed()
        Returns:
        whether the subscriber is closed
      • close

        public void close()
        Close the subscriber, the retry policy will not be invoked.

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/pubsub/class-use/PgChannel.html ================================================ Uses of Class io.reactiverse.reactivex.pgclient.pubsub.PgChannel (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.reactivex.pgclient.pubsub.PgChannel

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/pubsub/class-use/PgSubscriber.html ================================================ Uses of Class io.reactiverse.reactivex.pgclient.pubsub.PgSubscriber (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.reactivex.pgclient.pubsub.PgSubscriber

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/pubsub/package-frame.html ================================================ io.reactiverse.reactivex.pgclient.pubsub (Reactive Postgres Client 0.11.2 API)

io.reactiverse.reactivex.pgclient.pubsub

Classes

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/pubsub/package-summary.html ================================================ io.reactiverse.reactivex.pgclient.pubsub (Reactive Postgres Client 0.11.2 API)

Package io.reactiverse.reactivex.pgclient.pubsub

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/pubsub/package-tree.html ================================================ io.reactiverse.reactivex.pgclient.pubsub Class Hierarchy (Reactive Postgres Client 0.11.2 API)

Hierarchy For Package io.reactiverse.reactivex.pgclient.pubsub

Package Hierarchies:

Class Hierarchy

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/reactivex/pgclient/pubsub/package-use.html ================================================ Uses of Package io.reactiverse.reactivex.pgclient.pubsub (Reactive Postgres Client 0.11.2 API)

Uses of Package
io.reactiverse.reactivex.pgclient.pubsub

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/Json.html ================================================ Json (Reactive Postgres Client 0.9.0 API)
io.reactiverse.rxjava.pgclient

Class Json



  • public class Json
    extends Object
    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rxjava.TypeArg<Json> __TYPE_ARG
    • Constructor Detail

      • Json

        public Json(Json delegate)

Copyright © 2018 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/PgClient.html ================================================ PgClient (Reactive Postgres Client 0.11.2 API)
io.reactiverse.rxjava.pgclient

Class PgClient

  • Direct Known Subclasses:
    PgConnection, PgPool, PgTransaction


    public class PgClient
    extends Object
    Defines the client operations with a Postgres Database.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rx.TypeArg<PgClient> __TYPE_ARG
    • Constructor Detail

      • PgClient

        public PgClient(PgClient delegate)

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/PgConnection.html ================================================ PgConnection (Reactive Postgres Client 0.11.2 API)
io.reactiverse.rxjava.pgclient

Class PgConnection



  • public class PgConnection
    extends PgClient
    A connection to Postgres.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rx.TypeArg<PgConnection> __TYPE_ARG
    • Constructor Detail

    • Method Detail

      • prepare

        public PgConnection prepare(String sql,
                                    io.vertx.core.Handler<io.vertx.core.AsyncResult<PgPreparedQuery>> handler)
        Create a prepared query.
        Parameters:
        sql - the sql
        handler - the handler notified with the prepared query asynchronously
        Returns:
      • exceptionHandler

        public PgConnection exceptionHandler(io.vertx.core.Handler<Throwable> handler)
        Set an handler called with connection errors.
        Parameters:
        handler - the handler
        Returns:
        a reference to this, so the API can be used fluently
      • closeHandler

        public PgConnection closeHandler(io.vertx.core.Handler<Void> handler)
        Set an handler called when the connection is closed.
        Parameters:
        handler - the handler
        Returns:
        a reference to this, so the API can be used fluently
      • begin

        public PgTransaction begin()
        Begin a transaction and returns a PgTransaction for controlling and tracking this transaction.

        When the connection is explicitely closed, any inflight transaction is rollbacked.

        Returns:
        the transaction instance
      • notificationHandler

        public PgConnection notificationHandler(io.vertx.core.Handler<PgNotification> handler)
        Set an handler called when the connection receives notification on a channel.

        The handler is called with the PgNotification and has access to the channel name and the notification payload.

        Parameters:
        handler - the handler
        Returns:
        the transaction instance
      • processId

        public int processId()
        Returns:
        The process ID of the target backend
      • secretKey

        public int secretKey()
        Returns:
        The secret key for the target backend
      • cancelRequest

        public PgConnection cancelRequest(io.vertx.core.Handler<io.vertx.core.AsyncResult<Void>> handler)
        Send a request cancellation message to tell the server to cancel processing request in this connection.
        Note: Use this with caution because the cancellation signal may or may not have any effect.
        Parameters:
        handler - the handler notified if cancelling request is sent
        Returns:
        a reference to this, so the API can be used fluently
      • isSSL

        public boolean isSSL()
        Returns:
        whether the connection uses SSL
      • close

        public void close()
        Close the current connection after all the pending commands have been processed.
      • preparedQuery

        public PgConnection preparedQuery(String sql,
                                          io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from class: PgClient
        Prepare and execute a query.
        Overrides:
        preparedQuery in class PgClient
        Parameters:
        sql - the prepared query SQL
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • rxPreparedQuery

        public Single<PgRowSet> rxPreparedQuery(String sql)
        Description copied from class: PgClient
        Prepare and execute a query.
        Overrides:
        rxPreparedQuery in class PgClient
        Parameters:
        sql - the prepared query SQL
        Returns:
        a reference to this, so the API can be used fluently
      • query

        public PgConnection query(String sql,
                                  io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from class: PgClient
        Execute a simple query.
        Overrides:
        query in class PgClient
        Parameters:
        sql - the query SQL
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • rxQuery

        public Single<PgRowSet> rxQuery(String sql)
        Description copied from class: PgClient
        Execute a simple query.
        Overrides:
        rxQuery in class PgClient
        Parameters:
        sql - the query SQL
        Returns:
        a reference to this, so the API can be used fluently
      • preparedQuery

        public PgConnection preparedQuery(String sql,
                                          Tuple arguments,
                                          io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from class: PgClient
        Prepare and execute a query.
        Overrides:
        preparedQuery in class PgClient
        Parameters:
        sql - the prepared query SQL
        arguments - the list of arguments
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • rxPreparedQuery

        public Single<PgRowSet> rxPreparedQuery(String sql,
                                                Tuple arguments)
        Description copied from class: PgClient
        Prepare and execute a query.
        Overrides:
        rxPreparedQuery in class PgClient
        Parameters:
        sql - the prepared query SQL
        arguments - the list of arguments
        Returns:
        a reference to this, so the API can be used fluently
      • preparedBatch

        public PgConnection preparedBatch(String sql,
                                          List<Tuple> batch,
                                          io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from class: PgClient
        Prepare and execute a createBatch.
        Overrides:
        preparedBatch in class PgClient
        Parameters:
        sql - the prepared query SQL
        batch - the batch of tuples
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • rxPreparedBatch

        public Single<PgRowSet> rxPreparedBatch(String sql,
                                                List<Tuple> batch)
        Description copied from class: PgClient
        Prepare and execute a createBatch.
        Overrides:
        rxPreparedBatch in class PgClient
        Parameters:
        sql - the prepared query SQL
        batch - the batch of tuples
        Returns:
        a reference to this, so the API can be used fluently

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/PgCursor.html ================================================ PgCursor (Reactive Postgres Client 0.11.2 API)
io.reactiverse.rxjava.pgclient

Class PgCursor



  • public class PgCursor
    extends Object
    A cursor that reads progressively the rows from Postgres, it is usefull for reading very large result.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rx.TypeArg<PgCursor> __TYPE_ARG
    • Constructor Detail

      • PgCursor

        public PgCursor(PgCursor delegate)
    • Method Detail

      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Object
      • getDelegate

        public PgCursor getDelegate()
      • read

        public void read(int count,
                         io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Read rows from the cursor, the result is provided asynchronously to the handler.
        Parameters:
        count - the amount of rows to read
        handler - the handler for the result
      • rxRead

        public Single<PgRowSet> rxRead(int count)
        Read rows from the cursor, the result is provided asynchronously to the handler.
        Parameters:
        count - the amount of rows to read
        Returns:
      • hasMore

        public boolean hasMore()
        Returns true when the cursor has results in progress and the should be called to retrieve them.
        Returns:
        whether the cursor has more results,
      • close

        public void close()
        Release the cursor.

        It should be called for prepared queries executed with a fetch size.

      • close

        public void close(io.vertx.core.Handler<io.vertx.core.AsyncResult<Void>> completionHandler)
        Like close() but with a completionHandler called when the cursor has been released.
        Parameters:
        completionHandler -
      • rxClose

        public Single<Void> rxClose()
        Like close() but with a completionHandler called when the cursor has been released.
        Returns:

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/PgIterator.html ================================================ PgIterator (Reactive Postgres Client 0.11.2 API)
io.reactiverse.rxjava.pgclient

Class PgIterator



  • public class PgIterator
    extends Object
    An iterator for processing postgres items synchronously.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/PgPool.html ================================================ PgPool (Reactive Postgres Client 0.11.2 API)
io.reactiverse.rxjava.pgclient

Class PgPool



  • public class PgPool
    extends PgClient
    A pool of connection.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rx.TypeArg<PgPool> __TYPE_ARG
    • Constructor Detail

      • PgPool

        public PgPool(PgPool delegate)
    • Method Detail

      • preparedQuery

        public PgPool preparedQuery(String sql,
                                    io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from class: PgClient
        Prepare and execute a query.
        Overrides:
        preparedQuery in class PgClient
        Parameters:
        sql - the prepared query SQL
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • rxPreparedQuery

        public Single<PgRowSet> rxPreparedQuery(String sql)
        Description copied from class: PgClient
        Prepare and execute a query.
        Overrides:
        rxPreparedQuery in class PgClient
        Parameters:
        sql - the prepared query SQL
        Returns:
        a reference to this, so the API can be used fluently
      • query

        public PgPool query(String sql,
                            io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from class: PgClient
        Execute a simple query.
        Overrides:
        query in class PgClient
        Parameters:
        sql - the query SQL
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • rxQuery

        public Single<PgRowSet> rxQuery(String sql)
        Description copied from class: PgClient
        Execute a simple query.
        Overrides:
        rxQuery in class PgClient
        Parameters:
        sql - the query SQL
        Returns:
        a reference to this, so the API can be used fluently
      • preparedQuery

        public PgPool preparedQuery(String sql,
                                    Tuple arguments,
                                    io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from class: PgClient
        Prepare and execute a query.
        Overrides:
        preparedQuery in class PgClient
        Parameters:
        sql - the prepared query SQL
        arguments - the list of arguments
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • rxPreparedQuery

        public Single<PgRowSet> rxPreparedQuery(String sql,
                                                Tuple arguments)
        Description copied from class: PgClient
        Prepare and execute a query.
        Overrides:
        rxPreparedQuery in class PgClient
        Parameters:
        sql - the prepared query SQL
        arguments - the list of arguments
        Returns:
        a reference to this, so the API can be used fluently
      • preparedBatch

        public PgPool preparedBatch(String sql,
                                    List<Tuple> batch,
                                    io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from class: PgClient
        Prepare and execute a createBatch.
        Overrides:
        preparedBatch in class PgClient
        Parameters:
        sql - the prepared query SQL
        batch - the batch of tuples
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • rxPreparedBatch

        public Single<PgRowSet> rxPreparedBatch(String sql,
                                                List<Tuple> batch)
        Description copied from class: PgClient
        Prepare and execute a createBatch.
        Overrides:
        rxPreparedBatch in class PgClient
        Parameters:
        sql - the prepared query SQL
        batch - the batch of tuples
        Returns:
        a reference to this, so the API can be used fluently
      • getConnection

        public void getConnection(io.vertx.core.Handler<io.vertx.core.AsyncResult<PgConnection>> handler)
        Get a connection from the pool.
        Parameters:
        handler - the handler that will get the connection result
      • rxGetConnection

        public Single<PgConnection> rxGetConnection()
        Get a connection from the pool.
        Returns:
      • begin

        public void begin(io.vertx.core.Handler<io.vertx.core.AsyncResult<PgTransaction>> handler)
        Borrow a connection from the pool and begin a transaction, the underlying connection will be returned to the pool when the transaction ends.
        Parameters:
        handler -
      • rxBegin

        public Single<PgTransaction> rxBegin()
        Borrow a connection from the pool and begin a transaction, the underlying connection will be returned to the pool when the transaction ends.
        Returns:
        the transaction
      • close

        public void close()
        Close the pool and release the associated resources.
      • newInstance

        public static PgPool newInstance(PgPool arg)

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/PgPreparedQuery.html ================================================ PgPreparedQuery (Reactive Postgres Client 0.11.2 API)
io.reactiverse.rxjava.pgclient

Class PgPreparedQuery



  • public class PgPreparedQuery
    extends Object
    A prepared query.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rx.TypeArg<PgPreparedQuery> __TYPE_ARG
    • Constructor Detail

    • Method Detail

      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Object
      • execute

        public PgPreparedQuery execute(Tuple args,
                                       io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Create a cursor with the provided arguments.
        Parameters:
        args - the list of arguments
        handler -
        Returns:
        the query
      • rxExecute

        public Single<PgRowSet> rxExecute(Tuple args)
        Create a cursor with the provided arguments.
        Parameters:
        args - the list of arguments
        Returns:
        the query
      • cursor

        public PgCursor cursor()
        Returns:
        create a query cursor with a fetch size and empty arguments
      • cursor

        public PgCursor cursor(Tuple args)
        Create a cursor with the provided arguments.
        Parameters:
        args - the list of arguments
        Returns:
        the query
      • createStream

        public PgStream<Row> createStream(int fetch,
                                          Tuple args)
        Execute the prepared query with a cursor and createStream the result. The createStream opens a cursor with a fetch size to fetch the results.

        Note: this requires to be in a transaction, since cursors require it.

        Parameters:
        fetch - the cursor fetch size
        args - the prepared query arguments
        Returns:
        the createStream
      • batch

        public PgPreparedQuery batch(List<Tuple> argsList,
                                     io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Execute a batch.
        Parameters:
        argsList - the list of tuple for the batch
        handler -
        Returns:
        the createBatch
      • rxBatch

        public Single<PgRowSet> rxBatch(List<Tuple> argsList)
        Execute a batch.
        Parameters:
        argsList - the list of tuple for the batch
        Returns:
        the createBatch
      • close

        public void close()
        Close the prepared query and release its resources.
      • close

        public void close(io.vertx.core.Handler<io.vertx.core.AsyncResult<Void>> completionHandler)
        Like close() but notifies the completionHandler when it's closed.
        Parameters:
        completionHandler -
      • rxClose

        public Single<Void> rxClose()
        Like close() but notifies the completionHandler when it's closed.
        Returns:

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/PgResult.html ================================================ PgResult (Reactive Postgres Client 0.11.2 API)
io.reactiverse.rxjava.pgclient

Class PgResult<T>

  • Direct Known Subclasses:
    PgRowSet


    public class PgResult<T>
    extends Object
    Represents the result of an operation on database.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rx.TypeArg<PgResult> __TYPE_ARG
      • __typeArg_0

        public final io.vertx.lang.rx.TypeArg<T> __typeArg_0
    • Constructor Detail

      • PgResult

        public PgResult(PgResult delegate)
      • PgResult

        public PgResult(PgResult delegate,
                        io.vertx.lang.rx.TypeArg<T> typeArg_0)
    • Method Detail

      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Object
      • getDelegate

        public PgResult getDelegate()
      • rowCount

        public int rowCount()
        Get the number of the affected rows in the operation to this PgResult.

        The meaning depends on the executed statement:

        • INSERT: the number of rows inserted
        • DELETE: the number of rows deleted
        • UPDATE: the number of rows updated
        • SELECT: the number of rows retrieved
        Returns:
        the count of affected rows.
      • columnsNames

        public List<String> columnsNames()
        Get the names of columns in the PgResult.
        Returns:
        the list of names of columns.
      • size

        public int size()
        Get the number of rows in the PgResult.
        Returns:
        the count of rows.
      • value

        public T value()
        Get the result value.
        Returns:
        the result
      • next

        public PgResult<T> next()
        Return the next available result or null, e.g for a simple query that executed multiple queries or for a batch result.
        Returns:
        the next available result or null if none is available
      • newInstance

        public static <T> PgResult<T> newInstance(PgResult arg,
                                                  io.vertx.lang.rx.TypeArg<T> __typeArg_T)

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/PgRowSet.html ================================================ PgRowSet (Reactive Postgres Client 0.11.2 API)
io.reactiverse.rxjava.pgclient

Class PgRowSet



  • public class PgRowSet
    extends PgResult<PgRowSet>
    A set of rows.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/PgStream.html ================================================ PgStream (Reactive Postgres Client 0.11.2 API)
io.reactiverse.rxjava.pgclient

Class PgStream<T>

  • All Implemented Interfaces:
    io.vertx.rxjava.core.streams.ReadStream<T>, io.vertx.rxjava.core.streams.StreamBase


    public class PgStream<T>
    extends Object
    implements io.vertx.rxjava.core.streams.ReadStream<T>
    A row oriented stream.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rx.TypeArg<PgStream> __TYPE_ARG
      • __typeArg_0

        public final io.vertx.lang.rx.TypeArg<T> __typeArg_0
    • Constructor Detail

      • PgStream

        public PgStream(PgStream delegate)
      • PgStream

        public PgStream(PgStream delegate,
                        io.vertx.lang.rx.TypeArg<T> typeArg_0)
    • Method Detail

      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Object
      • getDelegate

        public PgStream getDelegate()
        Specified by:
        getDelegate in interface io.vertx.rxjava.core.streams.ReadStream<T>
        Specified by:
        getDelegate in interface io.vertx.rxjava.core.streams.StreamBase
      • toObservable

        public Observable<T> toObservable()
        Specified by:
        toObservable in interface io.vertx.rxjava.core.streams.ReadStream<T>
      • fetch

        public io.vertx.rxjava.core.streams.ReadStream<T> fetch(long arg0)
        Specified by:
        fetch in interface io.vertx.rxjava.core.streams.ReadStream<T>
      • exceptionHandler

        public PgStream<T> exceptionHandler(io.vertx.core.Handler<Throwable> handler)
        Specified by:
        exceptionHandler in interface io.vertx.rxjava.core.streams.ReadStream<T>
        Specified by:
        exceptionHandler in interface io.vertx.rxjava.core.streams.StreamBase
      • handler

        public PgStream<T> handler(io.vertx.core.Handler<T> handler)
        Specified by:
        handler in interface io.vertx.rxjava.core.streams.ReadStream<T>
      • pause

        public PgStream<T> pause()
        Specified by:
        pause in interface io.vertx.rxjava.core.streams.ReadStream<T>
      • resume

        public PgStream<T> resume()
        Specified by:
        resume in interface io.vertx.rxjava.core.streams.ReadStream<T>
      • endHandler

        public PgStream<T> endHandler(io.vertx.core.Handler<Void> endHandler)
        Specified by:
        endHandler in interface io.vertx.rxjava.core.streams.ReadStream<T>
      • close

        public void close()
        Close the stream and release the resources.
      • close

        public void close(io.vertx.core.Handler<io.vertx.core.AsyncResult<Void>> completionHandler)
        Close the stream and release the resources.
        Parameters:
        completionHandler - the completion handler for this operation
      • rxClose

        public Single<Void> rxClose()
        Close the stream and release the resources.
        Returns:
      • newInstance

        public static <T> PgStream<T> newInstance(PgStream arg,
                                                  io.vertx.lang.rx.TypeArg<T> __typeArg_T)

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/PgTransaction.html ================================================ PgTransaction (Reactive Postgres Client 0.11.2 API)
io.reactiverse.rxjava.pgclient

Class PgTransaction



  • public class PgTransaction
    extends PgClient
    A transaction that allows to control the transaction and receive events.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rx.TypeArg<PgTransaction> __TYPE_ARG
    • Constructor Detail

    • Method Detail

      • prepare

        public PgTransaction prepare(String sql,
                                     io.vertx.core.Handler<io.vertx.core.AsyncResult<PgPreparedQuery>> handler)
        Create a prepared query.
        Parameters:
        sql - the sql
        handler - the handler notified with the prepared query asynchronously
        Returns:
      • commit

        public void commit()
        Commit the current transaction.
      • commit

        public void commit(io.vertx.core.Handler<io.vertx.core.AsyncResult<Void>> handler)
        Like commit() with an handler to be notified when the transaction commit has completed
        Parameters:
        handler -
      • rxCommit

        public Single<Void> rxCommit()
        Like commit() with an handler to be notified when the transaction commit has completed
        Returns:
      • rollback

        public void rollback()
        Rollback the current transaction.
      • rollback

        public void rollback(io.vertx.core.Handler<io.vertx.core.AsyncResult<Void>> handler)
        Like rollback() with an handler to be notified when the transaction rollback has completed
        Parameters:
        handler -
      • rxRollback

        public Single<Void> rxRollback()
        Like rollback() with an handler to be notified when the transaction rollback has completed
        Returns:
      • abortHandler

        public PgTransaction abortHandler(io.vertx.core.Handler<Void> handler)
        Set an handler to be called when the transaction is aborted.
        Parameters:
        handler - the handler
        Returns:
      • query

        public PgTransaction query(String sql,
                                   io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from class: PgClient
        Execute a simple query.
        Overrides:
        query in class PgClient
        Parameters:
        sql - the query SQL
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • rxQuery

        public Single<PgRowSet> rxQuery(String sql)
        Description copied from class: PgClient
        Execute a simple query.
        Overrides:
        rxQuery in class PgClient
        Parameters:
        sql - the query SQL
        Returns:
        a reference to this, so the API can be used fluently
      • preparedQuery

        public PgTransaction preparedQuery(String sql,
                                           io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from class: PgClient
        Prepare and execute a query.
        Overrides:
        preparedQuery in class PgClient
        Parameters:
        sql - the prepared query SQL
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • rxPreparedQuery

        public Single<PgRowSet> rxPreparedQuery(String sql)
        Description copied from class: PgClient
        Prepare and execute a query.
        Overrides:
        rxPreparedQuery in class PgClient
        Parameters:
        sql - the prepared query SQL
        Returns:
        a reference to this, so the API can be used fluently
      • preparedQuery

        public PgTransaction preparedQuery(String sql,
                                           Tuple arguments,
                                           io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from class: PgClient
        Prepare and execute a query.
        Overrides:
        preparedQuery in class PgClient
        Parameters:
        sql - the prepared query SQL
        arguments - the list of arguments
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • rxPreparedQuery

        public Single<PgRowSet> rxPreparedQuery(String sql,
                                                Tuple arguments)
        Description copied from class: PgClient
        Prepare and execute a query.
        Overrides:
        rxPreparedQuery in class PgClient
        Parameters:
        sql - the prepared query SQL
        arguments - the list of arguments
        Returns:
        a reference to this, so the API can be used fluently
      • preparedBatch

        public PgTransaction preparedBatch(String sql,
                                           List<Tuple> batch,
                                           io.vertx.core.Handler<io.vertx.core.AsyncResult<PgRowSet>> handler)
        Description copied from class: PgClient
        Prepare and execute a createBatch.
        Overrides:
        preparedBatch in class PgClient
        Parameters:
        sql - the prepared query SQL
        batch - the batch of tuples
        handler - the handler notified with the execution result
        Returns:
        a reference to this, so the API can be used fluently
      • rxPreparedBatch

        public Single<PgRowSet> rxPreparedBatch(String sql,
                                                List<Tuple> batch)
        Description copied from class: PgClient
        Prepare and execute a createBatch.
        Overrides:
        rxPreparedBatch in class PgClient
        Parameters:
        sql - the prepared query SQL
        batch - the batch of tuples
        Returns:
        a reference to this, so the API can be used fluently

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/Row.html ================================================ Row (Reactive Postgres Client 0.11.2 API)
io.reactiverse.rxjava.pgclient

Class Row



  • public class Row
    extends Tuple
    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rx.TypeArg<Row> __TYPE_ARG
    • Constructor Detail

      • Row

        public Row(Row delegate)
    • Method Detail

      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Tuple
      • getColumnName

        public String getColumnName(int pos)
        Get a column name at pos.
        Parameters:
        pos - the position
        Returns:
        the column name or null
      • getBoolean

        public Boolean getBoolean(String name)
        Get a boolean value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getValue

        public Object getValue(String name)
        Get an object value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getShort

        public Short getShort(String name)
        Get a short value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getInteger

        public Integer getInteger(String name)
        Get an integer value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLong

        public Long getLong(String name)
        Get a long value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getFloat

        public Float getFloat(String name)
        Get a float value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getDouble

        public Double getDouble(String name)
        Get a double value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getString

        public String getString(String name)
        Get a string value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getJson

        public Json getJson(String name)
        Get a json value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getBuffer

        public io.vertx.rxjava.core.buffer.Buffer getBuffer(String name)
        Get a buffer value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getPoint

        public Point getPoint(String name)
        Get value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLine

        public Line getLine(String name)
        Get value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLineSegment

        public LineSegment getLineSegment(String name)
        Get value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getBox

        public Box getBox(String name)
        Get value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getPath

        public Path getPath(String name)
        Get value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getPolygon

        public Polygon getPolygon(String name)
        Get value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getCircle

        public Circle getCircle(String name)
        Get value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getInterval

        public Interval getInterval(String name)
        Get value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getTemporal

        public Temporal getTemporal(String name)
        Get a temporal value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLocalDate

        public LocalDate getLocalDate(String name)
        Get LocalDate value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLocalTime

        public LocalTime getLocalTime(String name)
        Get LocalTime value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLocalDateTime

        public LocalDateTime getLocalDateTime(String name)
        Get LocalDateTime value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getOffsetTime

        public OffsetTime getOffsetTime(String name)
        Get OffsetTime value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getUUID

        public UUID getUUID(String name)
        Get UUID value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getBigDecimal

        public BigDecimal getBigDecimal(String name)
        Get value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getNumeric

        public Numeric getNumeric(String name)
        Get value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getIntegerArray

        public Integer[] getIntegerArray(String name)
        Get an array of Integer value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getBooleanArray

        public Boolean[] getBooleanArray(String name)
        Get an array of Boolean value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getShortArray

        public Short[] getShortArray(String name)
        Get an array of Short value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLongArray

        public Long[] getLongArray(String name)
        Get an array of Long value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getFloatArray

        public Float[] getFloatArray(String name)
        Get an array of Float value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getDoubleArray

        public Double[] getDoubleArray(String name)
        Get an array of Double value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getStringArray

        public String[] getStringArray(String name)
        Get an array of String value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLocalDateArray

        public LocalDate[] getLocalDateArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLocalTimeArray

        public LocalTime[] getLocalTimeArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getOffsetTimeArray

        public OffsetTime[] getOffsetTimeArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLocalDateTimeArray

        public LocalDateTime[] getLocalDateTimeArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getOffsetDateTimeArray

        public OffsetDateTime[] getOffsetDateTimeArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getUUIDArray

        public UUID[] getUUIDArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getNumericArray

        public Numeric[] getNumericArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getPointArray

        public Point[] getPointArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLineArray

        public Line[] getLineArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getLineSegmentArray

        public LineSegment[] getLineSegmentArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getBoxArray

        public Box[] getBoxArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getPathArray

        public Path[] getPathArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getPolygonArray

        public Polygon[] getPolygonArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getCircleArray

        public Circle[] getCircleArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • getIntervalArray

        public Interval[] getIntervalArray(String name)
        Get an array of value at pos.
        Parameters:
        name - the column
        Returns:
        the value or null
      • newInstance

        public static Row newInstance(Row arg)

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/Tuple.html ================================================ Tuple (Reactive Postgres Client 0.11.2 API)
io.reactiverse.rxjava.pgclient

Class Tuple

  • Direct Known Subclasses:
    Row


    public class Tuple
    extends Object
    A general purpose tuple.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rx.TypeArg<Tuple> __TYPE_ARG
    • Constructor Detail

      • Tuple

        public Tuple(Tuple delegate)
    • Method Detail

      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Object
      • getDelegate

        public Tuple getDelegate()
      • tuple

        public static Tuple tuple()
        Returns:
        a new empty tuple
      • of

        public static Tuple of(Object elt1)
        Create a tuple of one element.
        Parameters:
        elt1 - the first value
        Returns:
        the tuple
      • of

        public static Tuple of(Object elt1,
                               Object elt2)
        Create a tuple of two elements.
        Parameters:
        elt1 - the first value
        elt2 - the second value
        Returns:
        the tuple
      • of

        public static Tuple of(Object elt1,
                               Object elt2,
                               Object elt3)
        Create a tuple of three elements.
        Parameters:
        elt1 - the first value
        elt2 - the second value
        elt3 - the third value
        Returns:
        the tuple
      • of

        public static Tuple of(Object elt1,
                               Object elt2,
                               Object elt3,
                               Object elt4)
        Create a tuple of four elements.
        Parameters:
        elt1 - the first value
        elt2 - the second value
        elt3 - the third value
        elt4 - the fourth value
        Returns:
        the tuple
      • of

        public static Tuple of(Object elt1,
                               Object elt2,
                               Object elt3,
                               Object elt4,
                               Object elt5)
        Create a tuple of five elements.
        Parameters:
        elt1 - the first value
        elt2 - the second value
        elt3 - the third value
        elt4 - the fourth value
        elt5 - the fifth value
        Returns:
        the tuple
      • of

        public static Tuple of(Object elt1,
                               Object elt2,
                               Object elt3,
                               Object elt4,
                               Object elt5,
                               Object elt6)
        Create a tuple of six elements.
        Parameters:
        elt1 - the first value
        elt2 - the second valueg
        elt3 - the third value
        elt4 - the fourth value
        elt5 - the fifth value
        elt6 - the sixth value
        Returns:
        the tuple
      • getBoolean

        public Boolean getBoolean(int pos)
        Get a boolean value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getValue

        public Object getValue(int pos)
        Get an object value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getShort

        public Short getShort(int pos)
        Get a short value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getInteger

        public Integer getInteger(int pos)
        Get an integer value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLong

        public Long getLong(int pos)
        Get a long value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getFloat

        public Float getFloat(int pos)
        Get a float value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getDouble

        public Double getDouble(int pos)
        Get a double value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getString

        public String getString(int pos)
        Get a string value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getJson

        public Json getJson(int pos)
        Get a json value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getPoint

        public Point getPoint(int pos)
        Get value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLine

        public Line getLine(int pos)
        Get value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLineSegment

        public LineSegment getLineSegment(int pos)
        Get value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getBox

        public Box getBox(int pos)
        Get value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getPath

        public Path getPath(int pos)
        Get value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getPolygon

        public Polygon getPolygon(int pos)
        Get value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getCircle

        public Circle getCircle(int pos)
        Get value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getInterval

        public Interval getInterval(int pos)
        Get value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getBuffer

        public io.vertx.rxjava.core.buffer.Buffer getBuffer(int pos)
        Get a buffer value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • addBoolean

        public Tuple addBoolean(Boolean value)
        Add a boolean value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addValue

        public Tuple addValue(Object value)
        Add an object value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addShort

        public Tuple addShort(Short value)
        Add a short value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addInteger

        public Tuple addInteger(Integer value)
        Add an integer value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLong

        public Tuple addLong(Long value)
        Add a long value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addFloat

        public Tuple addFloat(Float value)
        Add a float value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addDouble

        public Tuple addDouble(Double value)
        Add a double value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addString

        public Tuple addString(String value)
        Add a string value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addJson

        public Tuple addJson(Json value)
        Add a json value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addBuffer

        public Tuple addBuffer(io.vertx.rxjava.core.buffer.Buffer value)
        Add a buffer value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addPoint

        public Tuple addPoint(Point value)
        Add a value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLine

        public Tuple addLine(Line value)
        Add a value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLineSegment

        public Tuple addLineSegment(LineSegment value)
        Add a value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addBox

        public Tuple addBox(Box value)
        Add a value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addPath

        public Tuple addPath(Path value)
        Add a value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addPolygon

        public Tuple addPolygon(Polygon value)
        Add a value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addCircle

        public Tuple addCircle(Circle value)
        Add a value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addInterval

        public Tuple addInterval(Interval value)
        Add a value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • size

        public int size()
        Returns:
        the tuple size
      • clear

        public void clear()
      • getTemporal

        public Temporal getTemporal(int pos)
        Get a Temporal value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLocalDate

        public LocalDate getLocalDate(int pos)
        Get LocalDate value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLocalTime

        public LocalTime getLocalTime(int pos)
        Get LocalTime value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLocalDateTime

        public LocalDateTime getLocalDateTime(int pos)
        Get LocalDateTime value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getOffsetTime

        public OffsetTime getOffsetTime(int pos)
        Get OffsetTime value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getOffsetDateTime

        public OffsetDateTime getOffsetDateTime(int pos)
        Get OffsetDateTime value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getUUID

        public UUID getUUID(int pos)
        Get UUID value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getBigDecimal

        public BigDecimal getBigDecimal(int pos)
        Get value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getIntegerArray

        public Integer[] getIntegerArray(int pos)
        Get an array of Integer value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getBooleanArray

        public Boolean[] getBooleanArray(int pos)
        Get an array of Boolean value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getShortArray

        public Short[] getShortArray(int pos)
        Get an array of Short value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLongArray

        public Long[] getLongArray(int pos)
        Get an array of Long value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getFloatArray

        public Float[] getFloatArray(int pos)
        Get an array of Float value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getDoubleArray

        public Double[] getDoubleArray(int pos)
        Get an array of Double value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getStringArray

        public String[] getStringArray(int pos)
        Get an array of String value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLocalDateArray

        public LocalDate[] getLocalDateArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLocalTimeArray

        public LocalTime[] getLocalTimeArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getOffsetTimeArray

        public OffsetTime[] getOffsetTimeArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getLocalDateTimeArray

        public LocalDateTime[] getLocalDateTimeArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getOffsetDateTimeArray

        public OffsetDateTime[] getOffsetDateTimeArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • getUUIDArray

        public UUID[] getUUIDArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getNumericArray

        public Numeric[] getNumericArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getPointArray

        public Point[] getPointArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getLineArray

        public Line[] getLineArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getLineSegmentArray

        public LineSegment[] getLineSegmentArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getBoxArray

        public Box[] getBoxArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getPathArray

        public Path[] getPathArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getPolygonArray

        public Polygon[] getPolygonArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getCircleArray

        public Circle[] getCircleArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getIntervalArray

        public Interval[] getIntervalArray(int pos)
        Get an array of value at pos.
        Parameters:
        pos - the column
        Returns:
        the value or null
      • getNumeric

        public Numeric getNumeric(int pos)
        Get value at pos.
        Parameters:
        pos - the position
        Returns:
        the value or null
      • addTemporal

        public Tuple addTemporal(Temporal value)
        Add a Temporal value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLocalDate

        public Tuple addLocalDate(LocalDate value)
        Add a LocalDate value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLocalTime

        public Tuple addLocalTime(LocalTime value)
        Add a LocalTime value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLocalDateTime

        public Tuple addLocalDateTime(LocalDateTime value)
        Add a LocalDateTime value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addOffsetTime

        public Tuple addOffsetTime(OffsetTime value)
        Add a OffsetTime value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addOffsetDateTime

        public Tuple addOffsetDateTime(OffsetDateTime value)
        Add a OffsetDateTime value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addUUID

        public Tuple addUUID(UUID value)
        Add a UUID value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addNumeric

        public Tuple addNumeric(Numeric value)
        Add a value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addBigDecimal

        public Tuple addBigDecimal(BigDecimal value)
        Add a value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addIntegerArray

        public Tuple addIntegerArray(Integer[] value)
        Add an array of Integer value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addBooleanArray

        public Tuple addBooleanArray(Boolean[] value)
        Add an array of Boolean value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addShortArray

        public Tuple addShortArray(Short[] value)
        Add an array of Short value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLongArray

        public Tuple addLongArray(Long[] value)
        Add an array of Long value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addFloatArray

        public Tuple addFloatArray(Float[] value)
        Add an array of Float value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addDoubleArray

        public Tuple addDoubleArray(Double[] value)
        Add an array of Double value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addStringArray

        public Tuple addStringArray(String[] value)
        Add an array of String value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLocalDateArray

        public Tuple addLocalDateArray(LocalDate[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLocalTimeArray

        public Tuple addLocalTimeArray(LocalTime[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addOffsetTimeArray

        public Tuple addOffsetTimeArray(OffsetTime[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLocalDateTimeArray

        public Tuple addLocalDateTimeArray(LocalDateTime[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addOffsetDateTimeArray

        public Tuple addOffsetDateTimeArray(OffsetDateTime[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addUUIDArray

        public Tuple addUUIDArray(UUID[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addNumericArray

        public Tuple addNumericArray(Numeric[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addPointArray

        public Tuple addPointArray(Point[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLineArray

        public Tuple addLineArray(Line[] value)
        Add an array of Line value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addLineSegmentArray

        public Tuple addLineSegmentArray(LineSegment[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addBoxArray

        public Tuple addBoxArray(Box[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addPathArray

        public Tuple addPathArray(Path[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addPolygonArray

        public Tuple addPolygonArray(Polygon[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addCircleArray

        public Tuple addCircleArray(Circle[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • addIntervalArray

        public Tuple addIntervalArray(Interval[] value)
        Add an array of value at the end of the tuple.
        Parameters:
        value - the value
        Returns:
        a reference to this, so the API can be used fluently
      • newInstance

        public static Tuple newInstance(Tuple arg)

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/class-use/Json.html ================================================ Uses of Class io.reactiverse.rxjava.pgclient.Json (Reactive Postgres Client 0.9.0 API)

Uses of Class
io.reactiverse.rxjava.pgclient.Json

Copyright © 2018 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/class-use/PgClient.html ================================================ Uses of Class io.reactiverse.rxjava.pgclient.PgClient (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.rxjava.pgclient.PgClient

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/class-use/PgConnection.html ================================================ Uses of Class io.reactiverse.rxjava.pgclient.PgConnection (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.rxjava.pgclient.PgConnection

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/class-use/PgCursor.html ================================================ Uses of Class io.reactiverse.rxjava.pgclient.PgCursor (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.rxjava.pgclient.PgCursor

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/class-use/PgIterator.html ================================================ Uses of Class io.reactiverse.rxjava.pgclient.PgIterator (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.rxjava.pgclient.PgIterator

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/class-use/PgPool.html ================================================ Uses of Class io.reactiverse.rxjava.pgclient.PgPool (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.rxjava.pgclient.PgPool

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/class-use/PgPreparedQuery.html ================================================ Uses of Class io.reactiverse.rxjava.pgclient.PgPreparedQuery (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.rxjava.pgclient.PgPreparedQuery

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/class-use/PgResult.html ================================================ Uses of Class io.reactiverse.rxjava.pgclient.PgResult (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.rxjava.pgclient.PgResult

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/class-use/PgRowSet.html ================================================ Uses of Class io.reactiverse.rxjava.pgclient.PgRowSet (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.rxjava.pgclient.PgRowSet

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/class-use/PgStream.html ================================================ Uses of Class io.reactiverse.rxjava.pgclient.PgStream (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.rxjava.pgclient.PgStream

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/class-use/PgTransaction.html ================================================ Uses of Class io.reactiverse.rxjava.pgclient.PgTransaction (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.rxjava.pgclient.PgTransaction

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/class-use/Row.html ================================================ Uses of Class io.reactiverse.rxjava.pgclient.Row (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.rxjava.pgclient.Row

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/class-use/Tuple.html ================================================ Uses of Class io.reactiverse.rxjava.pgclient.Tuple (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.rxjava.pgclient.Tuple

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/data/Json.html ================================================ Json (Reactive Postgres Client 0.11.2 API)
io.reactiverse.rxjava.pgclient.data

Class Json



  • public class Json
    extends Object
    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rx.TypeArg<Json> __TYPE_ARG
    • Constructor Detail

      • Json

        public Json(Json delegate)

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/data/class-use/Json.html ================================================ Uses of Class io.reactiverse.rxjava.pgclient.data.Json (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.rxjava.pgclient.data.Json

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/data/package-frame.html ================================================ io.reactiverse.rxjava.pgclient.data (Reactive Postgres Client 0.11.2 API)

io.reactiverse.rxjava.pgclient.data

Classes

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/data/package-summary.html ================================================ io.reactiverse.rxjava.pgclient.data (Reactive Postgres Client 0.11.2 API)

Package io.reactiverse.rxjava.pgclient.data

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/data/package-tree.html ================================================ io.reactiverse.rxjava.pgclient.data Class Hierarchy (Reactive Postgres Client 0.11.2 API)

Hierarchy For Package io.reactiverse.rxjava.pgclient.data

Package Hierarchies:

Class Hierarchy

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/data/package-use.html ================================================ Uses of Package io.reactiverse.rxjava.pgclient.data (Reactive Postgres Client 0.11.2 API)

Uses of Package
io.reactiverse.rxjava.pgclient.data

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/package-frame.html ================================================ io.reactiverse.rxjava.pgclient (Reactive Postgres Client 0.11.2 API)

io.reactiverse.rxjava.pgclient

Classes

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/package-summary.html ================================================ io.reactiverse.rxjava.pgclient (Reactive Postgres Client 0.11.2 API)

Package io.reactiverse.rxjava.pgclient

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/package-tree.html ================================================ io.reactiverse.rxjava.pgclient Class Hierarchy (Reactive Postgres Client 0.11.2 API)

Hierarchy For Package io.reactiverse.rxjava.pgclient

Package Hierarchies:

Class Hierarchy

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/package-use.html ================================================ Uses of Package io.reactiverse.rxjava.pgclient (Reactive Postgres Client 0.11.2 API)

Uses of Package
io.reactiverse.rxjava.pgclient

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/pubsub/PgChannel.html ================================================ PgChannel (Reactive Postgres Client 0.11.2 API)
io.reactiverse.rxjava.pgclient.pubsub

Class PgChannel

  • All Implemented Interfaces:
    io.vertx.rxjava.core.streams.ReadStream<String>, io.vertx.rxjava.core.streams.StreamBase


    public class PgChannel
    extends Object
    implements io.vertx.rxjava.core.streams.ReadStream<String>
    A channel to Postgres that tracks the subscription to a given Postgres channel using the LISTEN/UNLISTEN commands.

    When paused the channel discards the messages.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rx.TypeArg<PgChannel> __TYPE_ARG
    • Constructor Detail

      • PgChannel

        public PgChannel(PgChannel delegate)
    • Method Detail

      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Object
      • getDelegate

        public PgChannel getDelegate()
        Specified by:
        getDelegate in interface io.vertx.rxjava.core.streams.ReadStream<String>
        Specified by:
        getDelegate in interface io.vertx.rxjava.core.streams.StreamBase
      • toObservable

        public Observable<String> toObservable()
        Specified by:
        toObservable in interface io.vertx.rxjava.core.streams.ReadStream<String>
      • fetch

        public io.vertx.rxjava.core.streams.ReadStream<String> fetch(long arg0)
        Specified by:
        fetch in interface io.vertx.rxjava.core.streams.ReadStream<String>
      • subscribeHandler

        public PgChannel subscribeHandler(io.vertx.core.Handler<Void> handler)
        Set an handler called when the the channel get subscribed.
        Parameters:
        handler - the handler
        Returns:
        a reference to this, so the API can be used fluently
      • handler

        public PgChannel handler(io.vertx.core.Handler<String> handler)
        Set or unset an handler to be called when a the channel is notified by Postgres.

        • when the handler is set, the subscriber sends a LISTEN command if needed
        • when the handler is unset, the subscriber sends a UNLISTEN command if needed
        Specified by:
        handler in interface io.vertx.rxjava.core.streams.ReadStream<String>
        Parameters:
        handler - the handler
        Returns:
        a reference to this, so the API can be used fluently
      • pause

        public PgChannel pause()
        Pause the channel, all notifications are discarded.
        Specified by:
        pause in interface io.vertx.rxjava.core.streams.ReadStream<String>
        Returns:
        a reference to this, so the API can be used fluently
      • resume

        public PgChannel resume()
        Resume the channel.
        Specified by:
        resume in interface io.vertx.rxjava.core.streams.ReadStream<String>
        Returns:
        a reference to this, so the API can be used fluently
      • endHandler

        public PgChannel endHandler(io.vertx.core.Handler<Void> endHandler)
        Set an handler to be called when no more notifications will be received.
        Specified by:
        endHandler in interface io.vertx.rxjava.core.streams.ReadStream<String>
        Parameters:
        endHandler - the handler
        Returns:
        a reference to this, so the API can be used fluently
      • exceptionHandler

        public PgChannel exceptionHandler(io.vertx.core.Handler<Throwable> handler)
        Specified by:
        exceptionHandler in interface io.vertx.rxjava.core.streams.ReadStream<String>
        Specified by:
        exceptionHandler in interface io.vertx.rxjava.core.streams.StreamBase

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/pubsub/PgSubscriber.html ================================================ PgSubscriber (Reactive Postgres Client 0.11.2 API)
io.reactiverse.rxjava.pgclient.pubsub

Class PgSubscriber



  • public class PgSubscriber
    extends Object
    A class for managing subscriptions using LISTEN/UNLISTEN to Postgres channels.

    The subscriber manages a single connection to Postgres.

    NOTE: This class has been automatically generated from the original non RX-ified interface using Vert.x codegen.

    • Field Detail

      • __TYPE_ARG

        public static final io.vertx.lang.rx.TypeArg<PgSubscriber> __TYPE_ARG
    • Constructor Detail

    • Method Detail

      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Object
      • subscriber

        public static PgSubscriber subscriber(io.vertx.rxjava.core.Vertx vertx,
                                              PgConnectOptions options)
        Create a subscriber.
        Parameters:
        vertx - the vertx instance
        options - the connect options
        Returns:
        the subscriber
      • channel

        public PgChannel channel(String name)
        Return a channel for the given name.
        Parameters:
        name - the channel name

        This will be the name of the channel exactly as held by Postgres for sending notifications. Internally this name will be truncated to the Postgres identifier maxiumum length of (NAMEDATALEN = 64) - 1 == 63 characters, and prepared as a quoted identifier without unicode escape sequence support for use in LISTEN/UNLISTEN commands. Examples of channel names and corresponding NOTIFY commands:

        • when name == "the_channel": NOTIFY the_channel, 'msg', NOTIFY The_Channel, 'msg', or NOTIFY "the_channel", 'msg' succeed in delivering a message to the created channel
        • when name == "The_Channel": NOTIFY "The_Channel", 'msg', succeeds in delivering a message to the created channel
        Returns:
        the channel
      • connect

        public PgSubscriber connect(io.vertx.core.Handler<io.vertx.core.AsyncResult<Void>> handler)
        Connect the subscriber to Postgres.
        Parameters:
        handler - the handler notified of the connection success or failure
        Returns:
        a reference to this, so the API can be used fluently
      • rxConnect

        public Single<Void> rxConnect()
        Connect the subscriber to Postgres.
        Returns:
        a reference to this, so the API can be used fluently
      • reconnectPolicy

        public PgSubscriber reconnectPolicy(Function<Integer,Long> policy)
        Set the reconnect policy that is executed when the subscriber is disconnected.

        When the subscriber is disconnected, the policy function is called with the actual number of retries and returns an amountOfTime value:

        • when amountOfTime < 0: the subscriber is closed and there is no retry
        • when amountOfTime == 0: the subscriber retries to connect immediately
        • when amountOfTime > 0: the subscriber retries after amountOfTime milliseconds

        The default policy does not perform any retries.

        Parameters:
        policy - the policy to set
        Returns:
        a reference to this, so the API can be used fluently
      • closeHandler

        public PgSubscriber closeHandler(io.vertx.core.Handler<Void> handler)
        Set an handler called when the subscriber is closed.
        Parameters:
        handler - the handler
        Returns:
        a reference to this, so the API can be used fluently
      • actualConnection

        public PgConnection actualConnection()
        Returns:
        the actual connection to Postgres, it might be null
      • closed

        public boolean closed()
        Returns:
        whether the subscriber is closed
      • close

        public void close()
        Close the subscriber, the retry policy will not be invoked.

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/pubsub/class-use/PgChannel.html ================================================ Uses of Class io.reactiverse.rxjava.pgclient.pubsub.PgChannel (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.rxjava.pgclient.pubsub.PgChannel

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/pubsub/class-use/PgSubscriber.html ================================================ Uses of Class io.reactiverse.rxjava.pgclient.pubsub.PgSubscriber (Reactive Postgres Client 0.11.2 API)

Uses of Class
io.reactiverse.rxjava.pgclient.pubsub.PgSubscriber

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/pubsub/package-frame.html ================================================ io.reactiverse.rxjava.pgclient.pubsub (Reactive Postgres Client 0.11.2 API)

io.reactiverse.rxjava.pgclient.pubsub

Classes

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/pubsub/package-summary.html ================================================ io.reactiverse.rxjava.pgclient.pubsub (Reactive Postgres Client 0.11.2 API)

Package io.reactiverse.rxjava.pgclient.pubsub

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/pubsub/package-tree.html ================================================ io.reactiverse.rxjava.pgclient.pubsub Class Hierarchy (Reactive Postgres Client 0.11.2 API)

Hierarchy For Package io.reactiverse.rxjava.pgclient.pubsub

Package Hierarchies:

Class Hierarchy

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/io/reactiverse/rxjava/pgclient/pubsub/package-use.html ================================================ Uses of Package io.reactiverse.rxjava.pgclient.pubsub (Reactive Postgres Client 0.11.2 API)

Uses of Package
io.reactiverse.rxjava.pgclient.pubsub

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/overview-frame.html ================================================ Overview List (Reactive Postgres Client 0.11.2 API)
All Classes

Packages

 

================================================ FILE: docs/apidocs/overview-summary.html ================================================ Overview (Reactive Postgres Client 0.11.2 API)

Reactive Postgres Client 0.11.2 API

Packages 
Package Description
io.reactiverse.pgclient  
io.reactiverse.pgclient.data  
io.reactiverse.pgclient.pubsub  
io.reactiverse.reactivex.pgclient  
io.reactiverse.reactivex.pgclient.data  
io.reactiverse.reactivex.pgclient.pubsub  
io.reactiverse.rxjava.pgclient  
io.reactiverse.rxjava.pgclient.data  
io.reactiverse.rxjava.pgclient.pubsub  

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/overview-tree.html ================================================ Class Hierarchy (Reactive Postgres Client 0.11.2 API)

Hierarchy For All Packages

Package Hierarchies:

Class Hierarchy

Interface Hierarchy

Enum Hierarchy

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/package-list ================================================ io.reactiverse.pgclient io.reactiverse.pgclient.data io.reactiverse.pgclient.pubsub io.reactiverse.reactivex.pgclient io.reactiverse.reactivex.pgclient.data io.reactiverse.reactivex.pgclient.pubsub io.reactiverse.rxjava.pgclient io.reactiverse.rxjava.pgclient.data io.reactiverse.rxjava.pgclient.pubsub ================================================ FILE: docs/apidocs/script.js ================================================ function show(type) { count = 0; for (var key in methods) { var row = document.getElementById(key); if ((methods[key] & type) != 0) { row.style.display = ''; row.className = (count++ % 2) ? rowColor : altColor; } else row.style.display = 'none'; } updateTabs(type); } function updateTabs(type) { for (var value in tabs) { var sNode = document.getElementById(tabs[value][0]); var spanNode = sNode.firstChild; if (value == type) { sNode.className = activeTableTab; spanNode.innerHTML = tabs[value][1]; } else { sNode.className = tableTab; spanNode.innerHTML = "" + tabs[value][1] + ""; } } } ================================================ FILE: docs/apidocs/serialized-form.html ================================================ Serialized Form (Reactive Postgres Client 0.11.2 API)

Serialized Form

Copyright © 2019 Eclipse. All rights reserved.

================================================ FILE: docs/apidocs/stylesheet.css ================================================ /* Javadoc style sheet */ /* Overall document style */ @import url('resources/fonts/dejavu.css'); body { background-color:#ffffff; color:#353833; font-family:'DejaVu Sans', Arial, Helvetica, sans-serif; font-size:14px; margin:0; } a:link, a:visited { text-decoration:none; color:#4A6782; } a:hover, a:focus { text-decoration:none; color:#bb7a2a; } a:active { text-decoration:none; color:#4A6782; } a[name] { color:#353833; } a[name]:hover { text-decoration:none; color:#353833; } pre { font-family:'DejaVu Sans Mono', monospace; font-size:14px; } h1 { font-size:20px; } h2 { font-size:18px; } h3 { font-size:16px; font-style:italic; } h4 { font-size:13px; } h5 { font-size:12px; } h6 { font-size:11px; } ul { list-style-type:disc; } code, tt { font-family:'DejaVu Sans Mono', monospace; font-size:14px; padding-top:4px; margin-top:8px; line-height:1.4em; } dt code { font-family:'DejaVu Sans Mono', monospace; font-size:14px; padding-top:4px; } table tr td dt code { font-family:'DejaVu Sans Mono', monospace; font-size:14px; vertical-align:top; padding-top:4px; } sup { font-size:8px; } /* Document title and Copyright styles */ .clear { clear:both; height:0px; overflow:hidden; } .aboutLanguage { float:right; padding:0px 21px; font-size:11px; z-index:200; margin-top:-9px; } .legalCopy { margin-left:.5em; } .bar a, .bar a:link, .bar a:visited, .bar a:active { color:#FFFFFF; text-decoration:none; } .bar a:hover, .bar a:focus { color:#bb7a2a; } .tab { background-color:#0066FF; color:#ffffff; padding:8px; width:5em; font-weight:bold; } /* Navigation bar styles */ .bar { background-color:#4D7A97; color:#FFFFFF; padding:.8em .5em .4em .8em; height:auto;/*height:1.8em;*/ font-size:11px; margin:0; } .topNav { background-color:#4D7A97; color:#FFFFFF; float:left; padding:0; width:100%; clear:right; height:2.8em; padding-top:10px; overflow:hidden; font-size:12px; } .bottomNav { margin-top:10px; background-color:#4D7A97; color:#FFFFFF; float:left; padding:0; width:100%; clear:right; height:2.8em; padding-top:10px; overflow:hidden; font-size:12px; } .subNav { background-color:#dee3e9; float:left; width:100%; overflow:hidden; font-size:12px; } .subNav div { clear:left; float:left; padding:0 0 5px 6px; text-transform:uppercase; } ul.navList, ul.subNavList { float:left; margin:0 25px 0 0; padding:0; } ul.navList li{ list-style:none; float:left; padding: 5px 6px; text-transform:uppercase; } ul.subNavList li{ list-style:none; float:left; } .topNav a:link, .topNav a:active, .topNav a:visited, .bottomNav a:link, .bottomNav a:active, .bottomNav a:visited { color:#FFFFFF; text-decoration:none; text-transform:uppercase; } .topNav a:hover, .bottomNav a:hover { text-decoration:none; color:#bb7a2a; text-transform:uppercase; } .navBarCell1Rev { background-color:#F8981D; color:#253441; margin: auto 5px; } .skipNav { position:absolute; top:auto; left:-9999px; overflow:hidden; } /* Page header and footer styles */ .header, .footer { clear:both; margin:0 20px; padding:5px 0 0 0; } .indexHeader { margin:10px; position:relative; } .indexHeader span{ margin-right:15px; } .indexHeader h1 { font-size:13px; } .title { color:#2c4557; margin:10px 0; } .subTitle { margin:5px 0 0 0; } .header ul { margin:0 0 15px 0; padding:0; } .footer ul { margin:20px 0 5px 0; } .header ul li, .footer ul li { list-style:none; font-size:13px; } /* Heading styles */ div.details ul.blockList ul.blockList ul.blockList li.blockList h4, div.details ul.blockList ul.blockList ul.blockListLast li.blockList h4 { background-color:#dee3e9; border:1px solid #d0d9e0; margin:0 0 6px -8px; padding:7px 5px; } ul.blockList ul.blockList ul.blockList li.blockList h3 { background-color:#dee3e9; border:1px solid #d0d9e0; margin:0 0 6px -8px; padding:7px 5px; } ul.blockList ul.blockList li.blockList h3 { padding:0; margin:15px 0; } ul.blockList li.blockList h2 { padding:0px 0 20px 0; } /* Page layout container styles */ .contentContainer, .sourceContainer, .classUseContainer, .serializedFormContainer, .constantValuesContainer { clear:both; padding:10px 20px; position:relative; } .indexContainer { margin:10px; position:relative; font-size:12px; } .indexContainer h2 { font-size:13px; padding:0 0 3px 0; } .indexContainer ul { margin:0; padding:0; } .indexContainer ul li { list-style:none; padding-top:2px; } .contentContainer .description dl dt, .contentContainer .details dl dt, .serializedFormContainer dl dt { font-size:12px; font-weight:bold; margin:10px 0 0 0; color:#4E4E4E; } .contentContainer .description dl dd, .contentContainer .details dl dd, .serializedFormContainer dl dd { margin:5px 0 10px 0px; font-size:14px; font-family:'DejaVu Sans Mono',monospace; } .serializedFormContainer dl.nameValue dt { margin-left:1px; font-size:1.1em; display:inline; font-weight:bold; } .serializedFormContainer dl.nameValue dd { margin:0 0 0 1px; font-size:1.1em; display:inline; } /* List styles */ ul.horizontal li { display:inline; font-size:0.9em; } ul.inheritance { margin:0; padding:0; } ul.inheritance li { display:inline; list-style:none; } ul.inheritance li ul.inheritance { margin-left:15px; padding-left:15px; padding-top:1px; } ul.blockList, ul.blockListLast { margin:10px 0 10px 0; padding:0; } ul.blockList li.blockList, ul.blockListLast li.blockList { list-style:none; margin-bottom:15px; line-height:1.4; } ul.blockList ul.blockList li.blockList, ul.blockList ul.blockListLast li.blockList { padding:0px 20px 5px 10px; border:1px solid #ededed; background-color:#f8f8f8; } ul.blockList ul.blockList ul.blockList li.blockList, ul.blockList ul.blockList ul.blockListLast li.blockList { padding:0 0 5px 8px; background-color:#ffffff; border:none; } ul.blockList ul.blockList ul.blockList ul.blockList li.blockList { margin-left:0; padding-left:0; padding-bottom:15px; border:none; } ul.blockList ul.blockList ul.blockList ul.blockList li.blockListLast { list-style:none; border-bottom:none; padding-bottom:0; } table tr td dl, table tr td dl dt, table tr td dl dd { margin-top:0; margin-bottom:1px; } /* Table styles */ .overviewSummary, .memberSummary, .typeSummary, .useSummary, .constantsSummary, .deprecatedSummary { width:100%; border-left:1px solid #EEE; border-right:1px solid #EEE; border-bottom:1px solid #EEE; } .overviewSummary, .memberSummary { padding:0px; } .overviewSummary caption, .memberSummary caption, .typeSummary caption, .useSummary caption, .constantsSummary caption, .deprecatedSummary caption { position:relative; text-align:left; background-repeat:no-repeat; color:#253441; font-weight:bold; clear:none; overflow:hidden; padding:0px; padding-top:10px; padding-left:1px; margin:0px; white-space:pre; } .overviewSummary caption a:link, .memberSummary caption a:link, .typeSummary caption a:link, .useSummary caption a:link, .constantsSummary caption a:link, .deprecatedSummary caption a:link, .overviewSummary caption a:hover, .memberSummary caption a:hover, .typeSummary caption a:hover, .useSummary caption a:hover, .constantsSummary caption a:hover, .deprecatedSummary caption a:hover, .overviewSummary caption a:active, .memberSummary caption a:active, .typeSummary caption a:active, .useSummary caption a:active, .constantsSummary caption a:active, .deprecatedSummary caption a:active, .overviewSummary caption a:visited, .memberSummary caption a:visited, .typeSummary caption a:visited, .useSummary caption a:visited, .constantsSummary caption a:visited, .deprecatedSummary caption a:visited { color:#FFFFFF; } .overviewSummary caption span, .memberSummary caption span, .typeSummary caption span, .useSummary caption span, .constantsSummary caption span, .deprecatedSummary caption span { white-space:nowrap; padding-top:5px; padding-left:12px; padding-right:12px; padding-bottom:7px; display:inline-block; float:left; background-color:#F8981D; border: none; height:16px; } .memberSummary caption span.activeTableTab span { white-space:nowrap; padding-top:5px; padding-left:12px; padding-right:12px; margin-right:3px; display:inline-block; float:left; background-color:#F8981D; height:16px; } .memberSummary caption span.tableTab span { white-space:nowrap; padding-top:5px; padding-left:12px; padding-right:12px; margin-right:3px; display:inline-block; float:left; background-color:#4D7A97; height:16px; } .memberSummary caption span.tableTab, .memberSummary caption span.activeTableTab { padding-top:0px; padding-left:0px; padding-right:0px; background-image:none; float:none; display:inline; } .overviewSummary .tabEnd, .memberSummary .tabEnd, .typeSummary .tabEnd, .useSummary .tabEnd, .constantsSummary .tabEnd, .deprecatedSummary .tabEnd { display:none; width:5px; position:relative; float:left; background-color:#F8981D; } .memberSummary .activeTableTab .tabEnd { display:none; width:5px; margin-right:3px; position:relative; float:left; background-color:#F8981D; } .memberSummary .tableTab .tabEnd { display:none; width:5px; margin-right:3px; position:relative; background-color:#4D7A97; float:left; } .overviewSummary td, .memberSummary td, .typeSummary td, .useSummary td, .constantsSummary td, .deprecatedSummary td { text-align:left; padding:0px 0px 12px 10px; } th.colOne, th.colFirst, th.colLast, .useSummary th, .constantsSummary th, td.colOne, td.colFirst, td.colLast, .useSummary td, .constantsSummary td{ vertical-align:top; padding-right:0px; padding-top:8px; padding-bottom:3px; } th.colFirst, th.colLast, th.colOne, .constantsSummary th { background:#dee3e9; text-align:left; padding:8px 3px 3px 7px; } td.colFirst, th.colFirst { white-space:nowrap; font-size:13px; } td.colLast, th.colLast { font-size:13px; } td.colOne, th.colOne { font-size:13px; } .overviewSummary td.colFirst, .overviewSummary th.colFirst, .useSummary td.colFirst, .useSummary th.colFirst, .overviewSummary td.colOne, .overviewSummary th.colOne, .memberSummary td.colFirst, .memberSummary th.colFirst, .memberSummary td.colOne, .memberSummary th.colOne, .typeSummary td.colFirst{ width:25%; vertical-align:top; } td.colOne a:link, td.colOne a:active, td.colOne a:visited, td.colOne a:hover, td.colFirst a:link, td.colFirst a:active, td.colFirst a:visited, td.colFirst a:hover, td.colLast a:link, td.colLast a:active, td.colLast a:visited, td.colLast a:hover, .constantValuesContainer td a:link, .constantValuesContainer td a:active, .constantValuesContainer td a:visited, .constantValuesContainer td a:hover { font-weight:bold; } .tableSubHeadingColor { background-color:#EEEEFF; } .altColor { background-color:#FFFFFF; } .rowColor { background-color:#EEEEEF; } /* Content styles */ .description pre { margin-top:0; } .deprecatedContent { margin:0; padding:10px 0; } .docSummary { padding:0; } ul.blockList ul.blockList ul.blockList li.blockList h3 { font-style:normal; } div.block { font-size:14px; font-family:'DejaVu Serif', Georgia, "Times New Roman", Times, serif; } td.colLast div { padding-top:0px; } td.colLast a { padding-bottom:3px; } /* Formatting effect styles */ .sourceLineNo { color:green; padding:0 30px 0 0; } h1.hidden { visibility:hidden; overflow:hidden; font-size:10px; } .block { display:block; margin:3px 10px 2px 0px; color:#474747; } .deprecatedLabel, .descfrmTypeLabel, .memberNameLabel, .memberNameLink, .overrideSpecifyLabel, .packageHierarchyLabel, .paramLabel, .returnLabel, .seeLabel, .simpleTagLabel, .throwsLabel, .typeNameLabel, .typeNameLink { font-weight:bold; } .deprecationComment, .emphasizedPhrase, .interfaceName { font-style:italic; } div.block div.block span.deprecationComment, div.block div.block span.emphasizedPhrase, div.block div.block span.interfaceName { font-style:normal; } div.contentContainer ul.blockList li.blockList h2{ padding-bottom:0px; } ================================================ FILE: docs/guide/groovy/index.md ================================================ # Reactive Postgres Client The Reactive Postgres Client is a client for Postgres with a straightforward API focusing on scalability and low overhead. The client is reactive and non blocking, allowing to handle many database connections with a single thread. * Event driven * Lightweight * Built-in connection pooling * Prepared queries caching * Publish / subscribe using Postgres `NOTIFY/LISTEN` * Batch and cursor * Row streaming * Command pipeling * RxJava 1 and RxJava 2 * Direct memory to object without unnecessary copies * Java 8 Date and Time * SSL/TLS * Unix domain socket * HTTP/1.x CONNECT, SOCKS4a or SOCKS5 proxy support ## Usage To use the Reactive Postgres Client add the following dependency to the _dependencies_ section of your build descriptor: * Maven (in your `pom.xml`): ```xml io.reactiverse reactive-pg-client 0.11.4 ``` * Gradle (in your `build.gradle` file): ```groovy dependencies { compile 'io.reactiverse:reactive-pg-client:0.11.4' } ``` ## Getting started Here is the simplest way to connect, query and disconnect ```groovy // Pool options def options = [ port:5432, host:"the-host", database:"the-db", user:"user", password:"secret", maxSize:5 ] // Create the client pool def client = PgClient.pool(options) // A simple query client.query("SELECT * FROM users WHERE id='julien'", { ar -> if (ar.succeeded()) { def result = ar.result() println("Got ${result.size()} rows ") } else { println("Failure: ${ar.cause().getMessage()}") } // Now close the pool client.close() }) ``` ## Connecting to Postgres Most of the time you will use a pool to connect to Postgres: ```groovy // Pool options def options = [ port:5432, host:"the-host", database:"the-db", user:"user", password:"secret", maxSize:5 ] // Create the pooled client def client = PgClient.pool(options) ``` The pooled client uses a connection pool and any operation will borrow a connection from the pool to execute the operation and release it to the pool. If you are running with Vert.x you can pass it your Vertx instance: ```groovy // Pool options def options = [ port:5432, host:"the-host", database:"the-db", user:"user", password:"secret", maxSize:5 ] // Create the pooled client def client = PgClient.pool(vertx, options) ``` You need to release the pool when you don't need it anymore: ```groovy // Close the pool and all the associated resources pool.close() ``` When you need to execute several operations on the same connection, you need to use a client [`connection`](../../apidocs/io/reactiverse/pgclient/PgConnection.html). You can easily get one from the pool: ```groovy // Pool options def options = [ port:5432, host:"the-host", database:"the-db", user:"user", password:"secret", maxSize:5 ] // Create the pooled client def client = PgClient.pool(vertx, options) // Get a connection from the pool client.getConnection({ ar1 -> if (ar1.succeeded()) { println("Connected") // Obtain our connection def conn = ar1.result() // All operations execute on the same connection conn.query("SELECT * FROM users WHERE id='julien'", { ar2 -> if (ar2.succeeded()) { conn.query("SELECT * FROM users WHERE id='emad'", { ar3 -> // Release the connection to the pool conn.close() }) } else { // Release the connection to the pool conn.close() } }) } else { println("Could not connect: ${ar1.cause().getMessage()}") } }) ``` Once you are done with the connection you must close it to release it to the pool, so it can be reused. Sometimes you want to improve performance via Unix domain socket connection, we achieve this with Vert.x Native transports. Make sure you have added the required `netty-transport-native` dependency in your classpath and enabled the Unix domain socket option. ```groovy // Pool Options // Socket file name will be /var/run/postgresql/.s.PGSQL.5432 def options = [ host:"/var/run/postgresql", port:5432, database:"the-db" ] // Create the pooled client def client = PgClient.pool(options) // Create the pooled client with a vertx instance // Make sure the vertx instance has enabled native transports def client2 = PgClient.pool(vertx, options) ``` More information can be found in the [Vert.x documentation](https://vertx.io/docs/vertx-core/java/#_native_transports). ## Configuration There are several options for you to configure the client. Apart from configuring with a `PgPoolOptions` data object, We also provide you an alternative way to connect when you want to configure with a connection URI: ```groovy // Connection URI def connectionUri = "postgresql://dbuser:secretpassword@database.server.com:3211/mydb" // Create the pool from the connection URI def pool = PgClient.pool(connectionUri) // Create the connection from the connection URI PgClient.connect(vertx, connectionUri, { res -> // Handling your connection }) ``` More information about connection string formats can be found in the [PostgreSQL Manuals](https://www.postgresql.org/docs/9.6/static/libpq-connect.html#LIBPQ-CONNSTRING). You can also use environment variables to set default connection setting values, this is useful when you want to avoid hard-coding database connection information. You can refer to the [official documentation](https://www.postgresql.org/docs/9.6/static/libpq-envars.html) for more details. The following parameters are supported: * `PGHOST` * `PGHOSTADDR` * `PGPORT` * `PGDATABASE` * `PGUSER` * `PGPASSWORD` * `PGSSLMODE` If you don't specify a data object or a connection URI string to connect, environment variables will take precedence over them. ``` $ PGUSER=user \ PGHOST=the-host \ PGPASSWORD=secret \ PGDATABASE=the-db \ PGPORT=5432 \ PGSSLMODE=DISABLE ``` ```groovy // Create the pool from the environment variables def pool = PgClient.pool() // Create the connection from the environment variables PgClient.connect(vertx, { res -> // Handling your connection }) ``` ## Running queries When you don't need a transaction or run single queries, you can run queries directly on the pool; the pool will use one of its connection to run the query and return the result to you. Here is how to run simple queries: ```groovy client.query("SELECT * FROM users WHERE id='julien'", { ar -> if (ar.succeeded()) { def result = ar.result() println("Got ${result.size()} rows ") } else { println("Failure: ${ar.cause().getMessage()}") } }) ``` You can do the same with prepared queries. The SQL string can refer to parameters by position, using `$1`, `$2`, etc…​ ```groovy client.preparedQuery("SELECT * FROM users WHERE id=$1", Tuple.of("julien"), { ar -> if (ar.succeeded()) { def rows = ar.result() println("Got ${rows.size()} rows ") } else { println("Failure: ${ar.cause().getMessage()}") } }) ``` Query methods provides an asynchronous [`PgRowSet`](../../apidocs/io/reactiverse/pgclient/PgRowSet.html) instance that works for _SELECT_ queries ```groovy client.preparedQuery("SELECT first_name, last_name FROM users", { ar -> if (ar.succeeded()) { def rows = ar.result() rows.each { row -> println("User ${row.getString(0)} ${row.getString(1)}") } } else { println("Failure: ${ar.cause().getMessage()}") } }) ``` or _UPDATE_/_INSERT_ queries: ```groovy client.preparedQuery("INSERT INTO users (first_name, last_name) VALUES ($1, $2)", Tuple.of("Julien", "Viet"), { ar -> if (ar.succeeded()) { def rows = ar.result() println(rows.rowCount()) } else { println("Failure: ${ar.cause().getMessage()}") } }) ``` The [`Row`](../../apidocs/io/reactiverse/pgclient/Row.html) gives you access to your data by index ```groovy println("User ${row.getString(0)} ${row.getString(1)}") ``` or by name ```groovy println("User ${row.getString("first_name")} ${row.getString("last_name")}") ``` You can access a wide variety of of types ```groovy def firstName = row.getString("first_name") def male = row.getBoolean("male") def age = row.getInteger("age") // ... ``` You can execute prepared batch ```groovy // Add commands to the batch def batch = [] batch.add(Tuple.of("julien", "Julien Viet")) batch.add(Tuple.of("emad", "Emad Alblueshi")) // Execute the prepared batch client.preparedBatch("INSERT INTO USERS (id, name) VALUES ($1, $2)", batch, { res -> if (res.succeeded()) { // Process rows def rows = res.result() } else { println("Batch failed ${res.cause()}") } }) ``` You can cache prepared queries: ```groovy // Enable prepare statements options.cachePreparedStatements = true def client = PgClient.pool(vertx, options) ``` You can fetch generated keys with a 'RETURNING' clause in your query: ```groovy client.preparedQuery("INSERT INTO color (color_name) VALUES ($1), ($2), ($3) RETURNING color_id", Tuple.of("white", "red", "blue"), { ar -> if (ar.succeeded()) { def rows = ar.result() println(rows.rowCount()) rows.each { row -> println("generated key: ${row.getInteger("color_id")}") } } else { println("Failure: ${ar.cause().getMessage()}") } }) ``` ## Using connections When you need to execute sequential queries (without a transaction), you can create a new connection or borrow one from the pool: ```groovy Code not translatable ``` Prepared queries can be created: ```groovy connection.prepare("SELECT * FROM users WHERE first_name LIKE $1", { ar1 -> if (ar1.succeeded()) { def pq = ar1.result() pq.execute(Tuple.of("julien"), { ar2 -> if (ar2.succeeded()) { // All rows def rows = ar2.result() } }) } }) ``` NOTE: prepared query caching depends on the [`setCachePreparedStatements`](../../apidocs/io/reactiverse/pgclient/PgConnectOptions.html#setCachePreparedStatements-boolean-) and does not depend on whether you are creating prepared queries or use [`direct prepared queries`](../../apidocs/io/reactiverse/pgclient/PgClient.html#preparedQuery-java.lang.String-io.vertx.core.Handler-) [`PgPreparedQuery`](../../apidocs/io/reactiverse/pgclient/PgPreparedQuery.html)can perform efficient batching: ```groovy connection.prepare("INSERT INTO USERS (id, name) VALUES ($1, $2)", { ar1 -> if (ar1.succeeded()) { def prepared = ar1.result() // Create a query : bind parameters def batch = [] // Add commands to the createBatch batch.add(Tuple.of("julien", "Julien Viet")) batch.add(Tuple.of("emad", "Emad Alblueshi")) prepared.batch(batch, { res -> if (res.succeeded()) { // Process rows def rows = res.result() } else { println("Batch failed ${res.cause()}") } }) } }) ``` ## Using transactions ### Transactions with connections You can execute transaction using SQL `BEGIN`/`COMMIT`/`ROLLBACK`, if you do so you must use a [`PgConnection`](../../apidocs/io/reactiverse/pgclient/PgConnection.html) and manage it yourself. Or you can use the transaction API of [`PgConnection`](../../apidocs/io/reactiverse/pgclient/PgConnection.html): ```groovy Code not translatable ``` When Postgres reports the current transaction is failed (e.g the infamous _current transaction is aborted, commands ignored until end of transaction block_), the transaction is rollbacked and the [`abortHandler`](../../apidocs/io/reactiverse/pgclient/PgTransaction.html#abortHandler-io.vertx.core.Handler-) is called: ```groovy pool.getConnection({ res -> if (res.succeeded()) { // Transaction must use a connection def conn = res.result() // Begin the transaction def tx = conn.begin().abortHandler({ v -> println("Transaction failed => rollbacked") }) conn.query("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')", { ar -> // Works fine of course if (ar.succeeded()) { } else { tx.rollback() conn.close() } }) conn.query("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')", { ar -> // Fails and triggers transaction aborts }) // Attempt to commit the transaction tx.commit({ ar -> // But transaction abortion fails it // Return the connection to the pool conn.close() }) } }) ``` ### Simplified transaction API When you use a pool, you can start a transaction directly on the pool. It borrows a connection from the pool, begins the transaction and releases the connection to the pool when the transaction ends. ```groovy Code not translatable ``` ## Cursors and streaming By default prepared query execution fetches all rows, you can use a [`PgCursor`](../../apidocs/io/reactiverse/pgclient/PgCursor.html)to control the amount of rows you want to read: ```groovy connection.prepare("SELECT * FROM users WHERE first_name LIKE $1", { ar1 -> if (ar1.succeeded()) { def pq = ar1.result() // Cursors require to run within a transaction def tx = connection.begin() // Create a cursor def cursor = pq.cursor(Tuple.of("julien")) // Read 50 rows cursor.read(50, { ar2 -> if (ar2.succeeded()) { def rows = ar2.result() // Check for more ? if (cursor.hasMore()) { // Repeat the process... } else { // No more rows - commit the transaction tx.commit() } } }) } }) ``` PostreSQL destroys cursors at the end of a transaction, so the cursor API shall be used within a transaction, otherwise you will likely get the `34000` PostgreSQL error. Cursors shall be closed when they are released prematurely: ```groovy cursor.read(50, { ar2 -> if (ar2.succeeded()) { // Close the cursor cursor.close() } }) ``` A stream API is also available for cursors, which can be more convenient, specially with the Rxified version. ```groovy connection.prepare("SELECT * FROM users WHERE first_name LIKE $1", { ar1 -> if (ar1.succeeded()) { def pq = ar1.result() // Streams require to run within a transaction def tx = connection.begin() // Fetch 50 rows at a time def stream = pq.createStream(50, Tuple.of("julien")) // Use the stream stream.exceptionHandler({ err -> println("Error: ${err.getMessage()}") }) stream.endHandler({ v -> tx.commit() println("End of stream") }) stream.handler({ row -> println("User: ${row.getString("last_name")}") }) } }) ``` The stream read the rows by batch of `50` and stream them, when the rows have been passed to the handler, a new batch of `50` is read and so on. The stream can be resumed or paused, the loaded rows will remain in memory until they are delivered and the cursor will stop iterating. ## Postgres type mapping Currently the client supports the following Postgres types * BOOLEAN (`java.lang.Boolean`) * INT2 (`java.lang.Short`) * INT4 (`java.lang.Integer`) * INT8 (`java.lang.Long`) * FLOAT4 (`java.lang.Float`) * FLOAT8 (`java.lang.Double`) * CHAR (`java.lang.String`) * VARCHAR (`java.lang.String`) * TEXT (`java.lang.String`) * ENUM (`java.lang.String`) * NAME (`java.lang.String`) * SERIAL2 (`java.lang.Short`) * SERIAL4 (`java.lang.Integer`) * SERIAL8 (`java.lang.Long`) * NUMERIC (`io.reactiverse.pgclient.data.Numeric`) * UUID (`java.util.UUID`) * DATE (`java.time.LocalDate`) * TIME (`java.time.LocalTime`) * TIMETZ (`java.time.OffsetTime`) * TIMESTAMP (`java.time.LocalDateTime`) * TIMESTAMPTZ (`java.time.OffsetDateTime`) * INTERVAL (`io.reactiverse.pgclient.data.Interval`) * BYTEA (`io.vertx.core.buffer.Buffer`) * JSON (`io.reactiverse.pgclient.data.Json`) * JSONB (`io.reactiverse.pgclient.data.Json`) * POINT (`io.reactiverse.pgclient.data.Point`) * LINE (`io.reactiverse.pgclient.data.Line`) * LSEG (`io.reactiverse.pgclient.data.LineSegment`) * BOX (`io.reactiverse.pgclient.data.Box`) * PATH (`io.reactiverse.pgclient.data.Path`) * POLYGON (`io.reactiverse.pgclient.data.Polygon`) * CIRCLE (`io.reactiverse.pgclient.data.Circle`) Tuple decoding uses the above types when storing values, it also performs on the flu conversion the actual value when possible: ```groovy pool.query("SELECT 1::BIGINT \"VAL\"", { ar -> def rowSet = ar.result() def row = rowSet.iterator().next() // Stored as java.lang.Long def value = row.getValue(0) // Convert to java.lang.Integer def intValue = row.getInteger(0) }) ``` Tuple encoding uses the above type mapping for encoding, unless the type is numeric in which case `java.lang.Number` is used instead: ```groovy pool.query("SELECT 1::BIGINT \"VAL\"", { ar -> def rowSet = ar.result() def row = rowSet.iterator().next() // Stored as java.lang.Long def value = row.getValue(0) // Convert to java.lang.Integer def intValue = row.getInteger(0) }) ``` Arrays of these types are supported. ### Handling JSON The [`Json`](../../apidocs/io/reactiverse/pgclient/data/Json.html) Java type is used to represent the Postgres `JSON` and `JSONB` type. The main reason of this type is handling `null` JSON values. ```groovy // Create a tuple def tuple = Tuple.of(Json.create(Json.create(null)), Json.create(Json.create([ foo:"bar" ])), Json.create(Json.create(null))) // Retrieving json def value = tuple.getJson(0).value() // value = tuple.getJson(1).value() // value = tuple.getJson(3).value() ``` ### Handling NUMERIC The [`Numeric`](../../apidocs/io/reactiverse/pgclient/data/Numeric.html) Java type is used to represent the Postgres `NUMERIC` type. ```groovy def numeric = row.getNumeric("value") if (numeric.isNaN()) { // Handle NaN } else { def value = numeric.bigDecimalValue() } ``` ## Handling arrays Arrays are available on [`Tuple`](../../apidocs/io/reactiverse/pgclient/Tuple.html) and [`Row`](../../apidocs/io/reactiverse/pgclient/Row.html): ```groovy Code not translatable ``` ## Handling custom types Strings are used to represent custom types, both sent to and returned from Postgres. You can read from Postgres and get the custom type as a string ```groovy client.preparedQuery("SELECT address, (address).city FROM address_book WHERE id=$1", Tuple.of(3), { ar -> if (ar.succeeded()) { def rows = ar.result() rows.each { row -> println("Full Address ${row.getString(0)}, City ${row.getString(1)}") } } else { println("Failure: ${ar.cause().getMessage()}") } }) ``` You can also write to Postgres by providing a string ```groovy client.preparedQuery("INSERT INTO address_book (id, address) VALUES ($1, $2)", Tuple.of(3, "('Anytown', 'Second Ave', false)"), { ar -> if (ar.succeeded()) { def rows = ar.result() println(rows.rowCount()) } else { println("Failure: ${ar.cause().getMessage()}") } }) ``` ## Collector queries You can use Java collectors with the query API: ```groovy Code not translatable ``` The collector processing must not keep a reference on the [`Row`](../../apidocs/io/reactiverse/pgclient/Row.html) as there is a single row used for processing the entire set. The Java `Collectors` provides many interesting predefined collectors, for example you can create easily create a string directly from the row set: ```groovy Code not translatable ``` ## RxJava support The rxified API supports RxJava 1 and RxJava 2, the following examples use RxJava 2. Most asynchronous constructs are available as methods prefixed by `rx`: ```groovy Code not translatable ``` ### Streaming RxJava 2 supports `Observable` and `Flowable` types, these are exposed using the [`PgStream`](../../apidocs/io/reactiverse/reactivex/pgclient/PgStream.html) that you can get from a [`PgPreparedQuery`](../../apidocs/io/reactiverse/reactivex/pgclient/PgPreparedQuery.html): ```groovy Code not translatable ``` The same example using `Flowable`: ```groovy Code not translatable ``` ### Transaction The simplified transaction API allows to easily write transactional asynchronous flows: ```groovy Code not translatable ``` ## Pub/sub Postgres supports pub/sub communication channels. You can set a [`notificationHandler`](../../apidocs/io/reactiverse/pgclient/PgConnection.html#notificationHandler-io.vertx.core.Handler-) to receive Postgres notifications: ```groovy connection.notificationHandler({ notification -> println("Received ${notification.payload} on channel ${notification.channel}") }) connection.query("LISTEN some-channel", { ar -> println("Subscribed to channel") }) ``` The [`PgSubscriber`](../../apidocs/io/reactiverse/pgclient/pubsub/PgSubscriber.html) is a channel manager managing a single connection that provides per channel subscription: ```groovy def subscriber = PgSubscriber.subscriber(vertx, [ port:5432, host:"the-host", database:"the-db", user:"user", password:"secret" ]) // You can set the channel before connect subscriber.channel("channel1").handler({ payload -> println("Received ${payload}") }) subscriber.connect({ ar -> if (ar.succeeded()) { // Or you can set the channel after connect subscriber.channel("channel2").handler({ payload -> println("Received ${payload}") }) } }) ``` The channel name that is given to the channel method will be the exact name of the channel as held by Postgres for sending notifications. Note this is different than the representation of the channel name in SQL, and internally [`PgSubscriber`](../../apidocs/io/reactiverse/pgclient/pubsub/PgSubscriber.html) will prepare the submitted channel name as a quoted identifier: ```groovy def subscriber = PgSubscriber.subscriber(vertx, [ port:5432, host:"the-host", database:"the-db", user:"user", password:"secret" ]) subscriber.connect({ ar -> if (ar.succeeded()) { // Complex channel name - name in PostgreSQL requires a quoted ID subscriber.channel("Complex.Channel.Name").handler({ payload -> println("Received ${payload}") }) subscriber.channel("Complex.Channel.Name").subscribeHandler({ subscribed -> subscriber.actualConnection().query("NOTIFY \"Complex.Channel.Name\", 'msg'", { notified -> println("Notified \"Complex.Channel.Name\"") }) }) // PostgreSQL simple ID's are forced lower-case subscriber.channel("simple_channel").handler({ payload -> println("Received ${payload}") }) subscriber.channel("simple_channel").subscribeHandler({ subscribed -> // The following simple channel identifier is forced to lower case subscriber.actualConnection().query("NOTIFY Simple_CHANNEL, 'msg'", { notified -> println("Notified simple_channel") }) }) // The following channel name is longer than the current // (NAMEDATALEN = 64) - 1 == 63 character limit and will be truncated subscriber.channel("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbb").handler({ payload -> println("Received ${payload}") }) } }) ``` You can provide a reconnect policy as a function that takes the number of `retries` as argument and returns an `amountOfTime` value: * when `amountOfTime < 0`: the subscriber is closed and there is no retry * when `amountOfTime = 0`: the subscriber retries to connect immediately * when `amountOfTime > 0`: the subscriber retries after `amountOfTime` milliseconds ```groovy def subscriber = PgSubscriber.subscriber(vertx, [ port:5432, host:"the-host", database:"the-db", user:"user", password:"secret" ]) // Reconnect at most 10 times after 100 ms each subscriber.reconnectPolicy({ retries -> if (retries < 10) { return 100L } else { return -1L } }) ``` The default policy is to not reconnect. ## Cancelling Request Postgres supports cancellation of requests in progress. You can cancel inflight requests using [`cancelRequest`](../../apidocs/io/reactiverse/pgclient/PgConnection.html#cancelRequest-io.vertx.core.Handler-). Cancelling a request opens a new connection to the server and cancels the request and then close the connection. ```groovy connection.query("SELECT pg_sleep(20)", { ar -> if (ar.succeeded()) { // imagine this is a long query and is still running println("Query success") } else { // the server will abort the current query after cancelling request println("Failed to query due to ${ar.cause().getMessage()}") } }) connection.cancelRequest({ ar -> if (ar.succeeded()) { println("Cancelling request has been sent") } else { println("Failed to send cancelling request") } }) ``` > The cancellation signal might or might not have any effect — for example, if it arrives after the backend has finished processing the query, then it will have no effect. If the cancellation is effective, it results in the current command being terminated early with an error message. More information can be found in the [official documentation](https://www.postgresql.org/docs/11/protocol-flow.html#id-1.10.5.7.9). ## Using SSL/TLS To configure the client to use SSL connection, you can configure the [`PgConnectOptions`](../../apidocs/io/reactiverse/pgclient/PgConnectOptions.html) like a Vert.x `NetClient`. All [SSL modes](https://www.postgresql.org/docs/current/libpq-ssl.html#LIBPQ-SSL-PROTECTION) are supported and you are able to configure `sslmode`. The client is in `DISABLE` SSL mode by default. `ssl` parameter is kept as a mere shortcut for setting `sslmode`. `setSsl(true)` is equivalent to `setSslMode(VERIFY_CA)` and `setSsl(false)` is equivalent to `setSslMode(DISABLE)`. ```groovy def options = [ port:5432, host:"the-host", database:"the-db", user:"user", password:"secret", sslMode:"VERIFY_CA", pemTrustOptions:[ certPaths:[ "/path/to/cert.pem" ] ] ] PgClient.connect(vertx, options, { res -> if (res.succeeded()) { // Connected with SSL } else { println("Could not connect ${res.cause()}") } }) ``` More information can be found in the [Vert.x documentation](http://vertx.io/docs/vertx-core/java/#ssl). ## Using a proxy You can also configure the client to use an HTTP/1.x CONNECT, SOCKS4a or SOCKS5 proxy. More information can be found in the [Vert.x documentation](http://vertx.io/docs/vertx-core/java/#_using_a_proxy_for_client_connections). ================================================ FILE: docs/guide/java/index.md ================================================ # Reactive Postgres Client The Reactive Postgres Client is a client for Postgres with a straightforward API focusing on scalability and low overhead. The client is reactive and non blocking, allowing to handle many database connections with a single thread. * Event driven * Lightweight * Built-in connection pooling * Prepared queries caching * Publish / subscribe using Postgres `NOTIFY/LISTEN` * Batch and cursor * Row streaming * Command pipeling * RxJava 1 and RxJava 2 * Direct memory to object without unnecessary copies * Java 8 Date and Time * SSL/TLS * Unix domain socket * HTTP/1.x CONNECT, SOCKS4a or SOCKS5 proxy support ## Usage To use the Reactive Postgres Client add the following dependency to the _dependencies_ section of your build descriptor: * Maven (in your `pom.xml`): ```xml io.reactiverse reactive-pg-client 0.11.4 ``` * Gradle (in your `build.gradle` file): ```groovy dependencies { compile 'io.reactiverse:reactive-pg-client:0.11.4' } ``` ## Getting started Here is the simplest way to connect, query and disconnect ```java PgPoolOptions options = new PgPoolOptions() .setPort(5432) .setHost("the-host") .setDatabase("the-db") .setUser("user") .setPassword("secret") .setMaxSize(5); // Create the client pool PgPool client = PgClient.pool(options); // A simple query client.query("SELECT * FROM users WHERE id='julien'", ar -> { if (ar.succeeded()) { PgRowSet result = ar.result(); System.out.println("Got " + result.size() + " rows "); } else { System.out.println("Failure: " + ar.cause().getMessage()); } // Now close the pool client.close(); }); ``` ## Connecting to Postgres Most of the time you will use a pool to connect to Postgres: ```java PgPoolOptions options = new PgPoolOptions() .setPort(5432) .setHost("the-host") .setDatabase("the-db") .setUser("user") .setPassword("secret") .setMaxSize(5); // Create the pooled client PgPool client = PgClient.pool(options); ``` The pooled client uses a connection pool and any operation will borrow a connection from the pool to execute the operation and release it to the pool. If you are running with Vert.x you can pass it your Vertx instance: ```java PgPoolOptions options = new PgPoolOptions() .setPort(5432) .setHost("the-host") .setDatabase("the-db") .setUser("user") .setPassword("secret") .setMaxSize(5); // Create the pooled client PgPool client = PgClient.pool(vertx, options); ``` You need to release the pool when you don't need it anymore: ```java pool.close(); ``` When you need to execute several operations on the same connection, you need to use a client [`connection`](../../apidocs/io/reactiverse/pgclient/PgConnection.html). You can easily get one from the pool: ```java PgPoolOptions options = new PgPoolOptions() .setPort(5432) .setHost("the-host") .setDatabase("the-db") .setUser("user") .setPassword("secret") .setMaxSize(5); // Create the pooled client PgPool client = PgClient.pool(vertx, options); // Get a connection from the pool client.getConnection(ar1 -> { if (ar1.succeeded()) { System.out.println("Connected"); // Obtain our connection PgConnection conn = ar1.result(); // All operations execute on the same connection conn.query("SELECT * FROM users WHERE id='julien'", ar2 -> { if (ar2.succeeded()) { conn.query("SELECT * FROM users WHERE id='emad'", ar3 -> { // Release the connection to the pool conn.close(); }); } else { // Release the connection to the pool conn.close(); } }); } else { System.out.println("Could not connect: " + ar1.cause().getMessage()); } }); ``` Once you are done with the connection you must close it to release it to the pool, so it can be reused. Sometimes you want to improve performance via Unix domain socket connection, we achieve this with Vert.x Native transports. Make sure you have added the required `netty-transport-native` dependency in your classpath and enabled the Unix domain socket option. ```java PgPoolOptions options = new PgPoolOptions() .setHost("/var/run/postgresql") .setPort(5432) .setDatabase("the-db"); // Create the pooled client PgPool client = PgClient.pool(options); // Create the pooled client with a vertx instance // Make sure the vertx instance has enabled native transports PgPool client2 = PgClient.pool(vertx, options); ``` More information can be found in the [Vert.x documentation](https://vertx.io/docs/vertx-core/java/#_native_transports). ## Configuration There are several options for you to configure the client. Apart from configuring with a `PgPoolOptions` data object, We also provide you an alternative way to connect when you want to configure with a connection URI: ```java String connectionUri = "postgresql://dbuser:secretpassword@database.server.com:3211/mydb"; // Create the pool from the connection URI PgPool pool = PgClient.pool(connectionUri); // Create the connection from the connection URI PgClient.connect(vertx, connectionUri, res -> { // Handling your connection }); ``` More information about connection string formats can be found in the [PostgreSQL Manuals](https://www.postgresql.org/docs/9.6/static/libpq-connect.html#LIBPQ-CONNSTRING). You can also use environment variables to set default connection setting values, this is useful when you want to avoid hard-coding database connection information. You can refer to the [official documentation](https://www.postgresql.org/docs/9.6/static/libpq-envars.html) for more details. The following parameters are supported: * `PGHOST` * `PGHOSTADDR` * `PGPORT` * `PGDATABASE` * `PGUSER` * `PGPASSWORD` * `PGSSLMODE` If you don't specify a data object or a connection URI string to connect, environment variables will take precedence over them. ``` $ PGUSER=user \ PGHOST=the-host \ PGPASSWORD=secret \ PGDATABASE=the-db \ PGPORT=5432 \ PGSSLMODE=DISABLE ``` ```java PgPool pool = PgClient.pool(); // Create the connection from the environment variables PgClient.connect(vertx, res -> { // Handling your connection }); ``` ## Running queries When you don't need a transaction or run single queries, you can run queries directly on the pool; the pool will use one of its connection to run the query and return the result to you. Here is how to run simple queries: ```java client.query("SELECT * FROM users WHERE id='julien'", ar -> { if (ar.succeeded()) { PgRowSet result = ar.result(); System.out.println("Got " + result.size() + " rows "); } else { System.out.println("Failure: " + ar.cause().getMessage()); } }); ``` You can do the same with prepared queries. The SQL string can refer to parameters by position, using `$1`, `$2`, etc…​ ```java client.preparedQuery("SELECT * FROM users WHERE id=$1", Tuple.of("julien"), ar -> { if (ar.succeeded()) { PgRowSet rows = ar.result(); System.out.println("Got " + rows.size() + " rows "); } else { System.out.println("Failure: " + ar.cause().getMessage()); } }); ``` Query methods provides an asynchronous [`PgRowSet`](../../apidocs/io/reactiverse/pgclient/PgRowSet.html) instance that works for _SELECT_ queries ```java client.preparedQuery("SELECT first_name, last_name FROM users", ar -> { if (ar.succeeded()) { PgRowSet rows = ar.result(); for (Row row : rows) { System.out.println("User " + row.getString(0) + " " + row.getString(1)); } } else { System.out.println("Failure: " + ar.cause().getMessage()); } }); ``` or _UPDATE_/_INSERT_ queries: ```java client.preparedQuery("INSERT INTO users (first_name, last_name) VALUES ($1, $2)", Tuple.of("Julien", "Viet"), ar -> { if (ar.succeeded()) { PgRowSet rows = ar.result(); System.out.println(rows.rowCount()); } else { System.out.println("Failure: " + ar.cause().getMessage()); } }); ``` The [`Row`](../../apidocs/io/reactiverse/pgclient/Row.html) gives you access to your data by index ```java System.out.println("User " + row.getString(0) + " " + row.getString(1)); ``` or by name ```java System.out.println("User " + row.getString("first_name") + " " + row.getString("last_name")); ``` You can access a wide variety of of types ```java String firstName = row.getString("first_name"); Boolean male = row.getBoolean("male"); Integer age = row.getInteger("age"); ``` You can execute prepared batch ```java List batch = new ArrayList<>(); batch.add(Tuple.of("julien", "Julien Viet")); batch.add(Tuple.of("emad", "Emad Alblueshi")); // Execute the prepared batch client.preparedBatch("INSERT INTO USERS (id, name) VALUES ($1, $2)", batch, res -> { if (res.succeeded()) { // Process rows PgRowSet rows = res.result(); } else { System.out.println("Batch failed " + res.cause()); } }); ``` You can cache prepared queries: ```java options.setCachePreparedStatements(true); PgPool client = PgClient.pool(vertx, options); ``` You can fetch generated keys with a 'RETURNING' clause in your query: ```java client.preparedQuery("INSERT INTO color (color_name) VALUES ($1), ($2), ($3) RETURNING color_id", Tuple.of("white", "red", "blue"), ar -> { if (ar.succeeded()) { PgRowSet rows = ar.result(); System.out.println(rows.rowCount()); for (Row row : rows) { System.out.println("generated key: " + row.getInteger("color_id")); } } else { System.out.println("Failure: " + ar.cause().getMessage()); } }); ``` ## Using connections When you need to execute sequential queries (without a transaction), you can create a new connection or borrow one from the pool: ```java pool.getConnection(ar1 -> { if (ar1.succeeded()) { PgConnection connection = ar1.result(); connection.query("SELECT * FROM users WHERE id='julien'", ar2 -> { if (ar1.succeeded()) { connection.query("SELECT * FROM users WHERE id='paulo'", ar3 -> { // Do something with rows and return the connection to the pool connection.close(); }); } else { // Return the connection to the pool connection.close(); } }); } }); ``` Prepared queries can be created: ```java connection.prepare("SELECT * FROM users WHERE first_name LIKE $1", ar1 -> { if (ar1.succeeded()) { PgPreparedQuery pq = ar1.result(); pq.execute(Tuple.of("julien"), ar2 -> { if (ar2.succeeded()) { // All rows PgRowSet rows = ar2.result(); } }); } }); ``` NOTE: prepared query caching depends on the [`setCachePreparedStatements`](../../apidocs/io/reactiverse/pgclient/PgConnectOptions.html#setCachePreparedStatements-boolean-) and does not depend on whether you are creating prepared queries or use [`direct prepared queries`](../../apidocs/io/reactiverse/pgclient/PgClient.html#preparedQuery-java.lang.String-io.vertx.core.Handler-) [`PgPreparedQuery`](../../apidocs/io/reactiverse/pgclient/PgPreparedQuery.html)can perform efficient batching: ```java connection.prepare("INSERT INTO USERS (id, name) VALUES ($1, $2)", ar1 -> { if (ar1.succeeded()) { PgPreparedQuery prepared = ar1.result(); // Create a query : bind parameters List batch = new ArrayList(); // Add commands to the createBatch batch.add(Tuple.of("julien", "Julien Viet")); batch.add(Tuple.of("emad", "Emad Alblueshi")); prepared.batch(batch, res -> { if (res.succeeded()) { // Process rows PgRowSet rows = res.result(); } else { System.out.println("Batch failed " + res.cause()); } }); } }); ``` ## Using transactions ### Transactions with connections You can execute transaction using SQL `BEGIN`/`COMMIT`/`ROLLBACK`, if you do so you must use a [`PgConnection`](../../apidocs/io/reactiverse/pgclient/PgConnection.html) and manage it yourself. Or you can use the transaction API of [`PgConnection`](../../apidocs/io/reactiverse/pgclient/PgConnection.html): ```java pool.getConnection(res -> { if (res.succeeded()) { // Transaction must use a connection PgConnection conn = res.result(); // Begin the transaction PgTransaction tx = conn.begin(); // Various statements conn.query("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')", ar -> {}); conn.query("INSERT INTO Users (first_name,last_name) VALUES ('Emad','Alblueshi')", ar -> {}); // Commit the transaction tx.commit(ar -> { if (ar.succeeded()) { System.out.println("Transaction succeeded"); } else { System.out.println("Transaction failed " + ar.cause().getMessage()); } // Return the connection to the pool conn.close(); }); } }); ``` When Postgres reports the current transaction is failed (e.g the infamous _current transaction is aborted, commands ignored until end of transaction block_), the transaction is rollbacked and the [`abortHandler`](../../apidocs/io/reactiverse/pgclient/PgTransaction.html#abortHandler-io.vertx.core.Handler-) is called: ```java pool.getConnection(res -> { if (res.succeeded()) { // Transaction must use a connection PgConnection conn = res.result(); // Begin the transaction PgTransaction tx = conn .begin() .abortHandler(v -> { System.out.println("Transaction failed => rollbacked"); }); conn.query("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')", ar -> { // Works fine of course if (ar.succeeded()) { } else { tx.rollback(); conn.close(); } }); conn.query("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')", ar -> { // Fails and triggers transaction aborts }); // Attempt to commit the transaction tx.commit(ar -> { // But transaction abortion fails it // Return the connection to the pool conn.close(); }); } }); ``` ### Simplified transaction API When you use a pool, you can start a transaction directly on the pool. It borrows a connection from the pool, begins the transaction and releases the connection to the pool when the transaction ends. ```java pool.begin(res -> { if (res.succeeded()) { // Get the transaction PgTransaction tx = res.result(); // Various statements tx.query("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')", ar -> {}); tx.query("INSERT INTO Users (first_name,last_name) VALUES ('Emad','Alblueshi')", ar -> {}); // Commit the transaction and return the connection to the pool tx.commit(ar -> { if (ar.succeeded()) { System.out.println("Transaction succeeded"); } else { System.out.println("Transaction failed " + ar.cause().getMessage()); } }); } }); ``` ## Cursors and streaming By default prepared query execution fetches all rows, you can use a [`PgCursor`](../../apidocs/io/reactiverse/pgclient/PgCursor.html)to control the amount of rows you want to read: ```java connection.prepare("SELECT * FROM users WHERE first_name LIKE $1", ar1 -> { if (ar1.succeeded()) { PgPreparedQuery pq = ar1.result(); // Cursors require to run within a transaction PgTransaction tx = connection.begin(); // Create a cursor PgCursor cursor = pq.cursor(Tuple.of("julien")); // Read 50 rows cursor.read(50, ar2 -> { if (ar2.succeeded()) { PgRowSet rows = ar2.result(); // Check for more ? if (cursor.hasMore()) { // Repeat the process... } else { // No more rows - commit the transaction tx.commit(); } } }); } }); ``` PostreSQL destroys cursors at the end of a transaction, so the cursor API shall be used within a transaction, otherwise you will likely get the `34000` PostgreSQL error. Cursors shall be closed when they are released prematurely: ```java cursor.read(50, ar2 -> { if (ar2.succeeded()) { // Close the cursor cursor.close(); } }); ``` A stream API is also available for cursors, which can be more convenient, specially with the Rxified version. ```java connection.prepare("SELECT * FROM users WHERE first_name LIKE $1", ar1 -> { if (ar1.succeeded()) { PgPreparedQuery pq = ar1.result(); // Streams require to run within a transaction PgTransaction tx = connection.begin(); // Fetch 50 rows at a time PgStream stream = pq.createStream(50, Tuple.of("julien")); // Use the stream stream.exceptionHandler(err -> { System.out.println("Error: " + err.getMessage()); }); stream.endHandler(v -> { tx.commit(); System.out.println("End of stream"); }); stream.handler(row -> { System.out.println("User: " + row.getString("last_name")); }); } }); ``` The stream read the rows by batch of `50` and stream them, when the rows have been passed to the handler, a new batch of `50` is read and so on. The stream can be resumed or paused, the loaded rows will remain in memory until they are delivered and the cursor will stop iterating. ## Postgres type mapping Currently the client supports the following Postgres types * BOOLEAN (`java.lang.Boolean`) * INT2 (`java.lang.Short`) * INT4 (`java.lang.Integer`) * INT8 (`java.lang.Long`) * FLOAT4 (`java.lang.Float`) * FLOAT8 (`java.lang.Double`) * CHAR (`java.lang.String`) * VARCHAR (`java.lang.String`) * TEXT (`java.lang.String`) * ENUM (`java.lang.String`) * NAME (`java.lang.String`) * SERIAL2 (`java.lang.Short`) * SERIAL4 (`java.lang.Integer`) * SERIAL8 (`java.lang.Long`) * NUMERIC (`io.reactiverse.pgclient.data.Numeric`) * UUID (`java.util.UUID`) * DATE (`java.time.LocalDate`) * TIME (`java.time.LocalTime`) * TIMETZ (`java.time.OffsetTime`) * TIMESTAMP (`java.time.LocalDateTime`) * TIMESTAMPTZ (`java.time.OffsetDateTime`) * INTERVAL (`io.reactiverse.pgclient.data.Interval`) * BYTEA (`io.vertx.core.buffer.Buffer`) * JSON (`io.reactiverse.pgclient.data.Json`) * JSONB (`io.reactiverse.pgclient.data.Json`) * POINT (`io.reactiverse.pgclient.data.Point`) * LINE (`io.reactiverse.pgclient.data.Line`) * LSEG (`io.reactiverse.pgclient.data.LineSegment`) * BOX (`io.reactiverse.pgclient.data.Box`) * PATH (`io.reactiverse.pgclient.data.Path`) * POLYGON (`io.reactiverse.pgclient.data.Polygon`) * CIRCLE (`io.reactiverse.pgclient.data.Circle`) Tuple decoding uses the above types when storing values, it also performs on the flu conversion the actual value when possible: ```java pool.query("SELECT 1::BIGINT \"VAL\"", ar -> { PgRowSet rowSet = ar.result(); Row row = rowSet.iterator().next(); // Stored as java.lang.Long Object value = row.getValue(0); // Convert to java.lang.Integer Integer intValue = row.getInteger(0); }); ``` Tuple encoding uses the above type mapping for encoding, unless the type is numeric in which case `java.lang.Number` is used instead: ```java pool.query("SELECT 1::BIGINT \"VAL\"", ar -> { PgRowSet rowSet = ar.result(); Row row = rowSet.iterator().next(); // Stored as java.lang.Long Object value = row.getValue(0); // Convert to java.lang.Integer Integer intValue = row.getInteger(0); }); ``` Arrays of these types are supported. ### Handling JSON The [`Json`](../../apidocs/io/reactiverse/pgclient/data/Json.html) Java type is used to represent the Postgres `JSON` and `JSONB` type. The main reason of this type is handling `null` JSON values. ```java Tuple tuple = Tuple.of( Json.create(Json.create(null)), Json.create(Json.create(new JsonObject().put("foo", "bar"))), Json.create(Json.create(null))); // Retrieving json Object value = tuple.getJson(0).value(); // Expect null // value = tuple.getJson(1).value(); // Expect JSON object // value = tuple.getJson(3).value(); // Expect 3 ``` ### Handling NUMERIC The [`Numeric`](../../apidocs/io/reactiverse/pgclient/data/Numeric.html) Java type is used to represent the Postgres `NUMERIC` type. ```java Numeric numeric = row.getNumeric("value"); if (numeric.isNaN()) { // Handle NaN } else { BigDecimal value = numeric.bigDecimalValue(); } ``` ## Handling arrays Arrays are available on [`Tuple`](../../apidocs/io/reactiverse/pgclient/Tuple.html) and [`Row`](../../apidocs/io/reactiverse/pgclient/Row.html): ```java Tuple tuple = Tuple.of(new String[]{ "a", "tuple", "with", "arrays" }); // Add a string array to the tuple tuple.addStringArray(new String[]{"another", "array"}); // Get the first array of string String[] array = tuple.getStringArray(0); ``` ## Handling custom types Strings are used to represent custom types, both sent to and returned from Postgres. You can read from Postgres and get the custom type as a string ```java client.preparedQuery("SELECT address, (address).city FROM address_book WHERE id=$1", Tuple.of(3), ar -> { if (ar.succeeded()) { PgRowSet rows = ar.result(); for (Row row : rows) { System.out.println("Full Address " + row.getString(0) + ", City " + row.getString(1)); } } else { System.out.println("Failure: " + ar.cause().getMessage()); } }); ``` You can also write to Postgres by providing a string ```java client.preparedQuery("INSERT INTO address_book (id, address) VALUES ($1, $2)", Tuple.of(3, "('Anytown', 'Second Ave', false)"), ar -> { if (ar.succeeded()) { PgRowSet rows = ar.result(); System.out.println(rows.rowCount()); } else { System.out.println("Failure: " + ar.cause().getMessage()); } }); ``` ## Collector queries You can use Java collectors with the query API: ```java Collector> collector = Collectors.toMap( row -> row.getLong("id"), row -> row.getString("last_name")); // Run the query with the collector client.query("SELECT * FROM users", collector, ar -> { if (ar.succeeded()) { PgResult> result = ar.result(); // Get the map created by the collector Map map = result.value(); System.out.println("Got " + map); } else { System.out.println("Failure: " + ar.cause().getMessage()); } }); ``` The collector processing must not keep a reference on the [`Row`](../../apidocs/io/reactiverse/pgclient/Row.html) as there is a single row used for processing the entire set. The Java `Collectors` provides many interesting predefined collectors, for example you can create easily create a string directly from the row set: ```java Collector collector = Collectors.mapping( row -> row.getString("last_name"), Collectors.joining(",", "(", ")") ); // Run the query with the collector client.query("SELECT * FROM users", collector, ar -> { if (ar.succeeded()) { PgResult result = ar.result(); // Get the string created by the collector String list = result.value(); System.out.println("Got " + list); } else { System.out.println("Failure: " + ar.cause().getMessage()); } }); ``` ## RxJava support The rxified API supports RxJava 1 and RxJava 2, the following examples use RxJava 2. Most asynchronous constructs are available as methods prefixed by `rx`: ```java Single single = pool.rxQuery("SELECT * FROM users WHERE id='julien'"); // Execute the query single.subscribe(result -> { System.out.println("Got " + result.size() + " rows "); }, err -> { System.out.println("Failure: " + err.getMessage()); }); ``` ### Streaming RxJava 2 supports `Observable` and `Flowable` types, these are exposed using the [`PgStream`](../../apidocs/io/reactiverse/reactivex/pgclient/PgStream.html) that you can get from a [`PgPreparedQuery`](../../apidocs/io/reactiverse/reactivex/pgclient/PgPreparedQuery.html): ```java Observable observable = pool.rxBegin() // Cursors require a transaction .flatMapObservable(tx -> tx .rxPrepare("SELECT * FROM users WHERE first_name LIKE $1") .flatMapObservable(preparedQuery -> { // Fetch 50 rows at a time PgStream stream = preparedQuery.createStream(50, Tuple.of("julien")); return stream.toObservable(); }) // Commit the transaction after usage .doAfterTerminate(tx::commit)); // Then subscribe observable.subscribe(row -> { System.out.println("User: " + row.getString("last_name")); }, err -> { System.out.println("Error: " + err.getMessage()); }, () -> { System.out.println("End of stream"); }); ``` The same example using `Flowable`: ```java Flowable flowable = pool.rxBegin() // Cursors require a transaction .flatMapPublisher(tx -> tx.rxPrepare("SELECT * FROM users WHERE first_name LIKE $1") .flatMapPublisher(preparedQuery -> { // Fetch 50 rows at a time PgStream stream = preparedQuery.createStream(50, Tuple.of("julien")); return stream.toFlowable(); }) // Commit the transaction after usage .doAfterTerminate(tx::commit)); // Then subscribe flowable.subscribe(new Subscriber() { private Subscription sub; @Override public void onSubscribe(Subscription subscription) { sub = subscription; subscription.request(1); } @Override public void onNext(Row row) { sub.request(1); System.out.println("User: " + row.getString("last_name")); } @Override public void onError(Throwable err) { System.out.println("Error: " + err.getMessage()); } @Override public void onComplete() { System.out.println("End of stream"); } }); ``` ### Transaction The simplified transaction API allows to easily write transactional asynchronous flows: ```java Completable completable = pool .rxBegin() .flatMapCompletable(tx -> tx .rxQuery("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')") .flatMap(result -> tx.rxQuery("INSERT INTO Users (first_name,last_name) VALUES ('Emad','Alblueshi')")) .flatMapCompletable(result -> tx.rxCommit())); completable.subscribe(() -> { // Transaction succeeded }, err -> { // Transaction failed }); ``` ## Pub/sub Postgres supports pub/sub communication channels. You can set a [`notificationHandler`](../../apidocs/io/reactiverse/pgclient/PgConnection.html#notificationHandler-io.vertx.core.Handler-) to receive Postgres notifications: ```java connection.notificationHandler(notification -> { System.out.println("Received " + notification.getPayload() + " on channel " + notification.getChannel()); }); connection.query("LISTEN some-channel", ar -> { System.out.println("Subscribed to channel"); }); ``` The [`PgSubscriber`](../../apidocs/io/reactiverse/pgclient/pubsub/PgSubscriber.html) is a channel manager managing a single connection that provides per channel subscription: ```java PgSubscriber subscriber = PgSubscriber.subscriber(vertx, new PgConnectOptions() .setPort(5432) .setHost("the-host") .setDatabase("the-db") .setUser("user") .setPassword("secret") ); // You can set the channel before connect subscriber.channel("channel1").handler(payload -> { System.out.println("Received " + payload); }); subscriber.connect(ar -> { if (ar.succeeded()) { // Or you can set the channel after connect subscriber.channel("channel2").handler(payload -> { System.out.println("Received " + payload); }); } }); ``` The channel name that is given to the channel method will be the exact name of the channel as held by Postgres for sending notifications. Note this is different than the representation of the channel name in SQL, and internally [`PgSubscriber`](../../apidocs/io/reactiverse/pgclient/pubsub/PgSubscriber.html) will prepare the submitted channel name as a quoted identifier: ```java PgSubscriber subscriber = PgSubscriber.subscriber(vertx, new PgConnectOptions() .setPort(5432) .setHost("the-host") .setDatabase("the-db") .setUser("user") .setPassword("secret") ); subscriber.connect(ar -> { if (ar.succeeded()) { // Complex channel name - name in PostgreSQL requires a quoted ID subscriber.channel("Complex.Channel.Name").handler(payload -> { System.out.println("Received " + payload); }); subscriber.channel("Complex.Channel.Name").subscribeHandler(subscribed -> { subscriber.actualConnection().query( "NOTIFY \"Complex.Channel.Name\", 'msg'", notified -> { System.out.println("Notified \"Complex.Channel.Name\""); }); }); // PostgreSQL simple ID's are forced lower-case subscriber.channel("simple_channel").handler(payload -> { System.out.println("Received " + payload); }); subscriber.channel("simple_channel").subscribeHandler(subscribed -> { // The following simple channel identifier is forced to lower case subscriber.actualConnection().query( "NOTIFY Simple_CHANNEL, 'msg'", notified -> { System.out.println("Notified simple_channel"); }); }); // The following channel name is longer than the current // (NAMEDATALEN = 64) - 1 == 63 character limit and will be truncated subscriber.channel( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbb" ).handler(payload -> { System.out.println("Received " + payload); }); } }); ``` You can provide a reconnect policy as a function that takes the number of `retries` as argument and returns an `amountOfTime` value: * when `amountOfTime < 0`: the subscriber is closed and there is no retry * when `amountOfTime = 0`: the subscriber retries to connect immediately * when `amountOfTime > 0`: the subscriber retries after `amountOfTime` milliseconds ```java PgSubscriber subscriber = PgSubscriber.subscriber(vertx, new PgConnectOptions() .setPort(5432) .setHost("the-host") .setDatabase("the-db") .setUser("user") .setPassword("secret") ); // Reconnect at most 10 times after 100 ms each subscriber.reconnectPolicy(retries -> { if (retries < 10) { return 100L; } else { return -1L; } }); ``` The default policy is to not reconnect. ## Cancelling Request Postgres supports cancellation of requests in progress. You can cancel inflight requests using [`cancelRequest`](../../apidocs/io/reactiverse/pgclient/PgConnection.html#cancelRequest-io.vertx.core.Handler-). Cancelling a request opens a new connection to the server and cancels the request and then close the connection. ```java connection.query("SELECT pg_sleep(20)", ar -> { if (ar.succeeded()) { // imagine this is a long query and is still running System.out.println("Query success"); } else { // the server will abort the current query after cancelling request System.out.println("Failed to query due to " + ar.cause().getMessage()); } }); connection.cancelRequest(ar -> { if (ar.succeeded()) { System.out.println("Cancelling request has been sent"); } else { System.out.println("Failed to send cancelling request"); } }); ``` > The cancellation signal might or might not have any effect — for example, if it arrives after the backend has finished processing the query, then it will have no effect. If the cancellation is effective, it results in the current command being terminated early with an error message. More information can be found in the [official documentation](https://www.postgresql.org/docs/11/protocol-flow.html#id-1.10.5.7.9). ## Using SSL/TLS To configure the client to use SSL connection, you can configure the [`PgConnectOptions`](../../apidocs/io/reactiverse/pgclient/PgConnectOptions.html) like a Vert.x `NetClient`. All [SSL modes](https://www.postgresql.org/docs/current/libpq-ssl.html#LIBPQ-SSL-PROTECTION) are supported and you are able to configure `sslmode`. The client is in `DISABLE` SSL mode by default. `ssl` parameter is kept as a mere shortcut for setting `sslmode`. `setSsl(true)` is equivalent to `setSslMode(VERIFY_CA)` and `setSsl(false)` is equivalent to `setSslMode(DISABLE)`. ```java PgConnectOptions options = new PgConnectOptions() .setPort(5432) .setHost("the-host") .setDatabase("the-db") .setUser("user") .setPassword("secret") .setSslMode(SslMode.VERIFY_CA) .setPemTrustOptions(new PemTrustOptions().addCertPath("/path/to/cert.pem")); PgClient.connect(vertx, options, res -> { if (res.succeeded()) { // Connected with SSL } else { System.out.println("Could not connect " + res.cause()); } }); ``` More information can be found in the [Vert.x documentation](http://vertx.io/docs/vertx-core/java/#ssl). ## Using a proxy You can also configure the client to use an HTTP/1.x CONNECT, SOCKS4a or SOCKS5 proxy. More information can be found in the [Vert.x documentation](http://vertx.io/docs/vertx-core/java/#_using_a_proxy_for_client_connections). ================================================ FILE: docs/guide/js/index.md ================================================ # Reactive Postgres Client The Reactive Postgres Client is a client for Postgres with a straightforward API focusing on scalability and low overhead. The client is reactive and non blocking, allowing to handle many database connections with a single thread. * Event driven * Lightweight * Built-in connection pooling * Prepared queries caching * Publish / subscribe using Postgres `NOTIFY/LISTEN` * Batch and cursor * Row streaming * Command pipeling * RxJava 1 and RxJava 2 * Direct memory to object without unnecessary copies * Java 8 Date and Time * SSL/TLS * Unix domain socket * HTTP/1.x CONNECT, SOCKS4a or SOCKS5 proxy support ## Usage To use the Reactive Postgres Client add the following dependency to the _dependencies_ section of your build descriptor: * Maven (in your `pom.xml`): ```xml io.reactiverse reactive-pg-client 0.11.4 ``` * Gradle (in your `build.gradle` file): ```groovy dependencies { compile 'io.reactiverse:reactive-pg-client:0.11.4' } ``` ## Getting started Here is the simplest way to connect, query and disconnect ```js var PgClient = require("reactive-pg-client-js/pg_client"); // Pool options var options = { "port" : 5432, "host" : "the-host", "database" : "the-db", "user" : "user", "password" : "secret", "maxSize" : 5 }; // Create the client pool var client = PgClient.pool(options); // A simple query client.query("SELECT * FROM users WHERE id='julien'", function (ar, ar_err) { if (ar_err == null) { var result = ar; console.log("Got " + result.size() + " rows "); } else { console.log("Failure: " + ar_err.getMessage()); } // Now close the pool client.close(); }); ``` ## Connecting to Postgres Most of the time you will use a pool to connect to Postgres: ```js var PgClient = require("reactive-pg-client-js/pg_client"); // Pool options var options = { "port" : 5432, "host" : "the-host", "database" : "the-db", "user" : "user", "password" : "secret", "maxSize" : 5 }; // Create the pooled client var client = PgClient.pool(options); ``` The pooled client uses a connection pool and any operation will borrow a connection from the pool to execute the operation and release it to the pool. If you are running with Vert.x you can pass it your Vertx instance: ```js var PgClient = require("reactive-pg-client-js/pg_client"); // Pool options var options = { "port" : 5432, "host" : "the-host", "database" : "the-db", "user" : "user", "password" : "secret", "maxSize" : 5 }; // Create the pooled client var client = PgClient.pool(vertx, options); ``` You need to release the pool when you don't need it anymore: ```js // Close the pool and all the associated resources pool.close(); ``` When you need to execute several operations on the same connection, you need to use a client [`connection`](../../jsdoc/module-reactive-pg-client-js_pg_connection-PgConnection.html). You can easily get one from the pool: ```js var PgClient = require("reactive-pg-client-js/pg_client"); // Pool options var options = { "port" : 5432, "host" : "the-host", "database" : "the-db", "user" : "user", "password" : "secret", "maxSize" : 5 }; // Create the pooled client var client = PgClient.pool(vertx, options); // Get a connection from the pool client.getConnection(function (ar1, ar1_err) { if (ar1_err == null) { console.log("Connected"); // Obtain our connection var conn = ar1; // All operations execute on the same connection conn.query("SELECT * FROM users WHERE id='julien'", function (ar2, ar2_err) { if (ar2_err == null) { conn.query("SELECT * FROM users WHERE id='emad'", function (ar3, ar3_err) { // Release the connection to the pool conn.close(); }); } else { // Release the connection to the pool conn.close(); } }); } else { console.log("Could not connect: " + ar1_err.getMessage()); } }); ``` Once you are done with the connection you must close it to release it to the pool, so it can be reused. Sometimes you want to improve performance via Unix domain socket connection, we achieve this with Vert.x Native transports. Make sure you have added the required `netty-transport-native` dependency in your classpath and enabled the Unix domain socket option. ```js var PgClient = require("reactive-pg-client-js/pg_client"); // Pool Options // Socket file name will be /var/run/postgresql/.s.PGSQL.5432 var options = { "host" : "/var/run/postgresql", "port" : 5432, "database" : "the-db" }; // Create the pooled client var client = PgClient.pool(options); // Create the pooled client with a vertx instance // Make sure the vertx instance has enabled native transports var client2 = PgClient.pool(vertx, options); ``` More information can be found in the [Vert.x documentation](https://vertx.io/docs/vertx-core/java/#_native_transports). ## Configuration There are several options for you to configure the client. Apart from configuring with a `PgPoolOptions` data object, We also provide you an alternative way to connect when you want to configure with a connection URI: ```js var PgClient = require("reactive-pg-client-js/pg_client"); // Connection URI var connectionUri = "postgresql://dbuser:secretpassword@database.server.com:3211/mydb"; // Create the pool from the connection URI var pool = PgClient.pool(connectionUri); // Create the connection from the connection URI PgClient.connect(vertx, connectionUri, function (res, res_err) { // Handling your connection }); ``` More information about connection string formats can be found in the [PostgreSQL Manuals](https://www.postgresql.org/docs/9.6/static/libpq-connect.html#LIBPQ-CONNSTRING). You can also use environment variables to set default connection setting values, this is useful when you want to avoid hard-coding database connection information. You can refer to the [official documentation](https://www.postgresql.org/docs/9.6/static/libpq-envars.html) for more details. The following parameters are supported: * `PGHOST` * `PGHOSTADDR` * `PGPORT` * `PGDATABASE` * `PGUSER` * `PGPASSWORD` * `PGSSLMODE` If you don't specify a data object or a connection URI string to connect, environment variables will take precedence over them. ``` $ PGUSER=user \ PGHOST=the-host \ PGPASSWORD=secret \ PGDATABASE=the-db \ PGPORT=5432 \ PGSSLMODE=DISABLE ``` ```js var PgClient = require("reactive-pg-client-js/pg_client"); // Create the pool from the environment variables var pool = PgClient.pool(); // Create the connection from the environment variables PgClient.connect(vertx, function (res, res_err) { // Handling your connection }); ``` ## Running queries When you don't need a transaction or run single queries, you can run queries directly on the pool; the pool will use one of its connection to run the query and return the result to you. Here is how to run simple queries: ```js client.query("SELECT * FROM users WHERE id='julien'", function (ar, ar_err) { if (ar_err == null) { var result = ar; console.log("Got " + result.size() + " rows "); } else { console.log("Failure: " + ar_err.getMessage()); } }); ``` You can do the same with prepared queries. The SQL string can refer to parameters by position, using `$1`, `$2`, etc…​ ```js var Tuple = require("reactive-pg-client-js/tuple"); client.preparedQuery("SELECT * FROM users WHERE id=$1", Tuple.of("julien"), function (ar, ar_err) { if (ar_err == null) { var rows = ar; console.log("Got " + rows.size() + " rows "); } else { console.log("Failure: " + ar_err.getMessage()); } }); ``` Query methods provides an asynchronous [`PgRowSet`](../../jsdoc/module-reactive-pg-client-js_pg_row_set-PgRowSet.html) instance that works for _SELECT_ queries ```js client.preparedQuery("SELECT first_name, last_name FROM users", function (ar, ar_err) { if (ar_err == null) { var rows = ar; Array.prototype.forEach.call(rows, function(row) { console.log("User " + row.getString(0) + " " + row.getString(1)); }); } else { console.log("Failure: " + ar_err.getMessage()); } }); ``` or _UPDATE_/_INSERT_ queries: ```js var Tuple = require("reactive-pg-client-js/tuple"); client.preparedQuery("INSERT INTO users (first_name, last_name) VALUES ($1, $2)", Tuple.of("Julien", "Viet"), function (ar, ar_err) { if (ar_err == null) { var rows = ar; console.log(rows.rowCount()); } else { console.log("Failure: " + ar_err.getMessage()); } }); ``` The [`Row`](../../jsdoc/module-reactive-pg-client-js_row-Row.html) gives you access to your data by index ```js console.log("User " + row.getString(0) + " " + row.getString(1)); ``` or by name ```js console.log("User " + row.getString("first_name") + " " + row.getString("last_name")); ``` You can access a wide variety of of types ```js var firstName = row.getString("first_name"); var male = row.getBoolean("male"); var age = row.getInteger("age"); // ... ``` You can execute prepared batch ```js var Tuple = require("reactive-pg-client-js/tuple"); // Add commands to the batch var batch = []; batch.push(Tuple.of("julien", "Julien Viet")); batch.push(Tuple.of("emad", "Emad Alblueshi")); // Execute the prepared batch client.preparedBatch("INSERT INTO USERS (id, name) VALUES ($1, $2)", batch, function (res, res_err) { if (res_err == null) { // Process rows var rows = res; } else { console.log("Batch failed " + res_err); } }); ``` You can cache prepared queries: ```js var PgClient = require("reactive-pg-client-js/pg_client"); // Enable prepare statements options.cachePreparedStatements = true; var client = PgClient.pool(vertx, options); ``` You can fetch generated keys with a 'RETURNING' clause in your query: ```js var Tuple = require("reactive-pg-client-js/tuple"); client.preparedQuery("INSERT INTO color (color_name) VALUES ($1), ($2), ($3) RETURNING color_id", Tuple.of("white", "red", "blue"), function (ar, ar_err) { if (ar_err == null) { var rows = ar; console.log(rows.rowCount()); Array.prototype.forEach.call(rows, function(row) { console.log("generated key: " + row.getInteger("color_id")); }); } else { console.log("Failure: " + ar_err.getMessage()); } }); ``` ## Using connections When you need to execute sequential queries (without a transaction), you can create a new connection or borrow one from the pool: ```js Code not translatable ``` Prepared queries can be created: ```js var Tuple = require("reactive-pg-client-js/tuple"); connection.prepare("SELECT * FROM users WHERE first_name LIKE $1", function (ar1, ar1_err) { if (ar1_err == null) { var pq = ar1; pq.execute(Tuple.of("julien"), function (ar2, ar2_err) { if (ar2_err == null) { // All rows var rows = ar2; } }); } }); ``` NOTE: prepared query caching depends on the [`cachePreparedStatements`](../dataobjects.html#PgConnectOptions#setCachePreparedStatements) and does not depend on whether you are creating prepared queries or use [`direct prepared queries`](../../jsdoc/module-reactive-pg-client-js_pg_client-PgClient.html#preparedQuery) [`PgPreparedQuery`](../../jsdoc/module-reactive-pg-client-js_pg_prepared_query-PgPreparedQuery.html)can perform efficient batching: ```js var Tuple = require("reactive-pg-client-js/tuple"); connection.prepare("INSERT INTO USERS (id, name) VALUES ($1, $2)", function (ar1, ar1_err) { if (ar1_err == null) { var prepared = ar1; // Create a query : bind parameters var batch = []; // Add commands to the createBatch batch.push(Tuple.of("julien", "Julien Viet")); batch.push(Tuple.of("emad", "Emad Alblueshi")); prepared.batch(batch, function (res, res_err) { if (res_err == null) { // Process rows var rows = res; } else { console.log("Batch failed " + res_err); } }); } }); ``` ## Using transactions ### Transactions with connections You can execute transaction using SQL `BEGIN`/`COMMIT`/`ROLLBACK`, if you do so you must use a [`PgConnection`](../../jsdoc/module-reactive-pg-client-js_pg_connection-PgConnection.html) and manage it yourself. Or you can use the transaction API of [`PgConnection`](../../jsdoc/module-reactive-pg-client-js_pg_connection-PgConnection.html): ```js Code not translatable ``` When Postgres reports the current transaction is failed (e.g the infamous _current transaction is aborted, commands ignored until end of transaction block_), the transaction is rollbacked and the [`abortHandler`](../../jsdoc/module-reactive-pg-client-js_pg_transaction-PgTransaction.html#abortHandler) is called: ```js pool.getConnection(function (res, res_err) { if (res_err == null) { // Transaction must use a connection var conn = res; // Begin the transaction var tx = conn.begin().abortHandler(function (v) { console.log("Transaction failed => rollbacked"); }); conn.query("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')", function (ar, ar_err) { // Works fine of course if (ar_err == null) { } else { tx.rollback(); conn.close(); } }); conn.query("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')", function (ar, ar_err) { // Fails and triggers transaction aborts }); // Attempt to commit the transaction tx.commit(function (ar, ar_err) { // But transaction abortion fails it // Return the connection to the pool conn.close(); }); } }); ``` ### Simplified transaction API When you use a pool, you can start a transaction directly on the pool. It borrows a connection from the pool, begins the transaction and releases the connection to the pool when the transaction ends. ```js Code not translatable ``` ## Cursors and streaming By default prepared query execution fetches all rows, you can use a [`PgCursor`](../../jsdoc/module-reactive-pg-client-js_pg_cursor-PgCursor.html)to control the amount of rows you want to read: ```js var Tuple = require("reactive-pg-client-js/tuple"); connection.prepare("SELECT * FROM users WHERE first_name LIKE $1", function (ar1, ar1_err) { if (ar1_err == null) { var pq = ar1; // Cursors require to run within a transaction var tx = connection.begin(); // Create a cursor var cursor = pq.cursor(Tuple.of("julien")); // Read 50 rows cursor.read(50, function (ar2, ar2_err) { if (ar2_err == null) { var rows = ar2; // Check for more ? if (cursor.hasMore()) { // Repeat the process... } else { // No more rows - commit the transaction tx.commit(); } } }); } }); ``` PostreSQL destroys cursors at the end of a transaction, so the cursor API shall be used within a transaction, otherwise you will likely get the `34000` PostgreSQL error. Cursors shall be closed when they are released prematurely: ```js cursor.read(50, function (ar2, ar2_err) { if (ar2_err == null) { // Close the cursor cursor.close(); } }); ``` A stream API is also available for cursors, which can be more convenient, specially with the Rxified version. ```js var Tuple = require("reactive-pg-client-js/tuple"); connection.prepare("SELECT * FROM users WHERE first_name LIKE $1", function (ar1, ar1_err) { if (ar1_err == null) { var pq = ar1; // Streams require to run within a transaction var tx = connection.begin(); // Fetch 50 rows at a time var stream = pq.createStream(50, Tuple.of("julien")); // Use the stream stream.exceptionHandler(function (err) { console.log("Error: " + err.getMessage()); }); stream.endHandler(function (v) { tx.commit(); console.log("End of stream"); }); stream.handler(function (row) { console.log("User: " + row.getString("last_name")); }); } }); ``` The stream read the rows by batch of `50` and stream them, when the rows have been passed to the handler, a new batch of `50` is read and so on. The stream can be resumed or paused, the loaded rows will remain in memory until they are delivered and the cursor will stop iterating. ## Postgres type mapping Currently the client supports the following Postgres types * BOOLEAN (`java.lang.Boolean`) * INT2 (`java.lang.Short`) * INT4 (`java.lang.Integer`) * INT8 (`java.lang.Long`) * FLOAT4 (`java.lang.Float`) * FLOAT8 (`java.lang.Double`) * CHAR (`java.lang.String`) * VARCHAR (`java.lang.String`) * TEXT (`java.lang.String`) * ENUM (`java.lang.String`) * NAME (`java.lang.String`) * SERIAL2 (`java.lang.Short`) * SERIAL4 (`java.lang.Integer`) * SERIAL8 (`java.lang.Long`) * NUMERIC (`io.reactiverse.pgclient.data.Numeric`) * UUID (`java.util.UUID`) * DATE (`java.time.LocalDate`) * TIME (`java.time.LocalTime`) * TIMETZ (`java.time.OffsetTime`) * TIMESTAMP (`java.time.LocalDateTime`) * TIMESTAMPTZ (`java.time.OffsetDateTime`) * INTERVAL (`io.reactiverse.pgclient.data.Interval`) * BYTEA (`io.vertx.core.buffer.Buffer`) * JSON (`io.reactiverse.pgclient.data.Json`) * JSONB (`io.reactiverse.pgclient.data.Json`) * POINT (`io.reactiverse.pgclient.data.Point`) * LINE (`io.reactiverse.pgclient.data.Line`) * LSEG (`io.reactiverse.pgclient.data.LineSegment`) * BOX (`io.reactiverse.pgclient.data.Box`) * PATH (`io.reactiverse.pgclient.data.Path`) * POLYGON (`io.reactiverse.pgclient.data.Polygon`) * CIRCLE (`io.reactiverse.pgclient.data.Circle`) Tuple decoding uses the above types when storing values, it also performs on the flu conversion the actual value when possible: ```js pool.query("SELECT 1::BIGINT \"VAL\"", function (ar, ar_err) { var rowSet = ar; var row = rowSet.iterator().next(); // Stored as java.lang.Long var value = row.getValue(0); // Convert to java.lang.Integer var intValue = row.getInteger(0); }); ``` Tuple encoding uses the above type mapping for encoding, unless the type is numeric in which case `java.lang.Number` is used instead: ```js pool.query("SELECT 1::BIGINT \"VAL\"", function (ar, ar_err) { var rowSet = ar; var row = rowSet.iterator().next(); // Stored as java.lang.Long var value = row.getValue(0); // Convert to java.lang.Integer var intValue = row.getInteger(0); }); ``` Arrays of these types are supported. ### Handling JSON The [`Json`](../../jsdoc/module-reactive-pg-client-js_json-Json.html) Java type is used to represent the Postgres `JSON` and `JSONB` type. The main reason of this type is handling `null` JSON values. ```js var Json = require("reactive-pg-client-js/json"); var Tuple = require("reactive-pg-client-js/tuple"); // Create a tuple var tuple = Tuple.of(Json.create(Json.create(null)), Json.create(Json.create({ "foo" : "bar" })), Json.create(Json.create(null))); // Retrieving json var value = tuple.getJson(0).value(); // value = tuple.getJson(1).value(); // value = tuple.getJson(3).value(); ``` ### Handling NUMERIC The `Numeric` Java type is used to represent the Postgres `NUMERIC` type. ```js var numeric = row.getNumeric("value"); if (numeric.isNaN()) { // Handle NaN } else { var value = numeric.bigDecimalValue(); } ``` ## Handling arrays Arrays are available on [`Tuple`](../../jsdoc/module-reactive-pg-client-js_tuple-Tuple.html) and [`Row`](../../jsdoc/module-reactive-pg-client-js_row-Row.html): ```js Code not translatable ``` ## Handling custom types Strings are used to represent custom types, both sent to and returned from Postgres. You can read from Postgres and get the custom type as a string ```js var Tuple = require("reactive-pg-client-js/tuple"); client.preparedQuery("SELECT address, (address).city FROM address_book WHERE id=$1", Tuple.of(3), function (ar, ar_err) { if (ar_err == null) { var rows = ar; Array.prototype.forEach.call(rows, function(row) { console.log("Full Address " + row.getString(0) + ", City " + row.getString(1)); }); } else { console.log("Failure: " + ar_err.getMessage()); } }); ``` You can also write to Postgres by providing a string ```js var Tuple = require("reactive-pg-client-js/tuple"); client.preparedQuery("INSERT INTO address_book (id, address) VALUES ($1, $2)", Tuple.of(3, "('Anytown', 'Second Ave', false)"), function (ar, ar_err) { if (ar_err == null) { var rows = ar; console.log(rows.rowCount()); } else { console.log("Failure: " + ar_err.getMessage()); } }); ``` ## Collector queries You can use Java collectors with the query API: ```js Code not translatable ``` The collector processing must not keep a reference on the [`Row`](../../jsdoc/module-reactive-pg-client-js_row-Row.html) as there is a single row used for processing the entire set. The Java `Collectors` provides many interesting predefined collectors, for example you can create easily create a string directly from the row set: ```js Code not translatable ``` ## RxJava support The rxified API supports RxJava 1 and RxJava 2, the following examples use RxJava 2. Most asynchronous constructs are available as methods prefixed by `rx`: ```js Code not translatable ``` ### Streaming RxJava 2 supports `Observable` and `Flowable` types, these are exposed using the `PgStream` that you can get from a `PgPreparedQuery`: ```js Code not translatable ``` The same example using `Flowable`: ```js Code not translatable ``` ### Transaction The simplified transaction API allows to easily write transactional asynchronous flows: ```js Code not translatable ``` ## Pub/sub Postgres supports pub/sub communication channels. You can set a [`notificationHandler`](../../jsdoc/module-reactive-pg-client-js_pg_connection-PgConnection.html#notificationHandler) to receive Postgres notifications: ```js connection.notificationHandler(function (notification) { console.log("Received " + notification.payload + " on channel " + notification.channel); }); connection.query("LISTEN some-channel", function (ar, ar_err) { console.log("Subscribed to channel"); }); ``` The [`PgSubscriber`](../../jsdoc/module-reactive-pg-client-js_pg_subscriber-PgSubscriber.html) is a channel manager managing a single connection that provides per channel subscription: ```js var PgSubscriber = require("reactive-pg-client-js/pg_subscriber"); var subscriber = PgSubscriber.subscriber(vertx, { "port" : 5432, "host" : "the-host", "database" : "the-db", "user" : "user", "password" : "secret" }); // You can set the channel before connect subscriber.channel("channel1").handler(function (payload) { console.log("Received " + payload); }); subscriber.connect(function (ar, ar_err) { if (ar_err == null) { // Or you can set the channel after connect subscriber.channel("channel2").handler(function (payload) { console.log("Received " + payload); }); } }); ``` The channel name that is given to the channel method will be the exact name of the channel as held by Postgres for sending notifications. Note this is different than the representation of the channel name in SQL, and internally [`PgSubscriber`](../../jsdoc/module-reactive-pg-client-js_pg_subscriber-PgSubscriber.html) will prepare the submitted channel name as a quoted identifier: ```js var PgSubscriber = require("reactive-pg-client-js/pg_subscriber"); var subscriber = PgSubscriber.subscriber(vertx, { "port" : 5432, "host" : "the-host", "database" : "the-db", "user" : "user", "password" : "secret" }); subscriber.connect(function (ar, ar_err) { if (ar_err == null) { // Complex channel name - name in PostgreSQL requires a quoted ID subscriber.channel("Complex.Channel.Name").handler(function (payload) { console.log("Received " + payload); }); subscriber.channel("Complex.Channel.Name").subscribeHandler(function (subscribed) { subscriber.actualConnection().query("NOTIFY \"Complex.Channel.Name\", 'msg'", function (notified, notified_err) { console.log("Notified \"Complex.Channel.Name\""); }); }); // PostgreSQL simple ID's are forced lower-case subscriber.channel("simple_channel").handler(function (payload) { console.log("Received " + payload); }); subscriber.channel("simple_channel").subscribeHandler(function (subscribed) { // The following simple channel identifier is forced to lower case subscriber.actualConnection().query("NOTIFY Simple_CHANNEL, 'msg'", function (notified, notified_err) { console.log("Notified simple_channel"); }); }); // The following channel name is longer than the current // (NAMEDATALEN = 64) - 1 == 63 character limit and will be truncated subscriber.channel("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbb").handler(function (payload) { console.log("Received " + payload); }); } }); ``` You can provide a reconnect policy as a function that takes the number of `retries` as argument and returns an `amountOfTime` value: * when `amountOfTime < 0`: the subscriber is closed and there is no retry * when `amountOfTime = 0`: the subscriber retries to connect immediately * when `amountOfTime > 0`: the subscriber retries after `amountOfTime` milliseconds ```js var PgSubscriber = require("reactive-pg-client-js/pg_subscriber"); var subscriber = PgSubscriber.subscriber(vertx, { "port" : 5432, "host" : "the-host", "database" : "the-db", "user" : "user", "password" : "secret" }); // Reconnect at most 10 times after 100 ms each subscriber.reconnectPolicy(function (retries) { if (retries < 10) { return 100 } else { return -1 } }); ``` The default policy is to not reconnect. ## Cancelling Request Postgres supports cancellation of requests in progress. You can cancel inflight requests using [`cancelRequest`](../../jsdoc/module-reactive-pg-client-js_pg_connection-PgConnection.html#cancelRequest). Cancelling a request opens a new connection to the server and cancels the request and then close the connection. ```js connection.query("SELECT pg_sleep(20)", function (ar, ar_err) { if (ar_err == null) { // imagine this is a long query and is still running console.log("Query success"); } else { // the server will abort the current query after cancelling request console.log("Failed to query due to " + ar_err.getMessage()); } }); connection.cancelRequest(function (ar, ar_err) { if (ar_err == null) { console.log("Cancelling request has been sent"); } else { console.log("Failed to send cancelling request"); } }); ``` > The cancellation signal might or might not have any effect — for example, if it arrives after the backend has finished processing the query, then it will have no effect. If the cancellation is effective, it results in the current command being terminated early with an error message. More information can be found in the [official documentation](https://www.postgresql.org/docs/11/protocol-flow.html#id-1.10.5.7.9). ## Using SSL/TLS To configure the client to use SSL connection, you can configure the [`PgConnectOptions`](../dataobjects.html#PgConnectOptions) like a Vert.x `NetClient`. All [SSL modes](https://www.postgresql.org/docs/current/libpq-ssl.html#LIBPQ-SSL-PROTECTION) are supported and you are able to configure `sslmode`. The client is in `DISABLE` SSL mode by default. `ssl` parameter is kept as a mere shortcut for setting `sslmode`. `setSsl(true)` is equivalent to `setSslMode(VERIFY_CA)` and `setSsl(false)` is equivalent to `setSslMode(DISABLE)`. ```js var PgClient = require("reactive-pg-client-js/pg_client"); var options = { "port" : 5432, "host" : "the-host", "database" : "the-db", "user" : "user", "password" : "secret", "sslMode" : "VERIFY_CA", "pemTrustOptions" : { "certPaths" : [ "/path/to/cert.pem" ] } }; PgClient.connect(vertx, options, function (res, res_err) { if (res_err == null) { // Connected with SSL } else { console.log("Could not connect " + res_err); } }); ``` More information can be found in the [Vert.x documentation](http://vertx.io/docs/vertx-core/java/#ssl). ## Using a proxy You can also configure the client to use an HTTP/1.x CONNECT, SOCKS4a or SOCKS5 proxy. More information can be found in the [Vert.x documentation](http://vertx.io/docs/vertx-core/java/#_using_a_proxy_for_client_connections). ================================================ FILE: docs/guide/kotlin/index.md ================================================ # Reactive Postgres Client The Reactive Postgres Client is a client for Postgres with a straightforward API focusing on scalability and low overhead. The client is reactive and non blocking, allowing to handle many database connections with a single thread. * Event driven * Lightweight * Built-in connection pooling * Prepared queries caching * Publish / subscribe using Postgres `NOTIFY/LISTEN` * Batch and cursor * Row streaming * Command pipeling * RxJava 1 and RxJava 2 * Direct memory to object without unnecessary copies * Java 8 Date and Time * SSL/TLS * Unix domain socket * HTTP/1.x CONNECT, SOCKS4a or SOCKS5 proxy support ## Usage To use the Reactive Postgres Client add the following dependency to the _dependencies_ section of your build descriptor: * Maven (in your `pom.xml`): ```xml io.reactiverse reactive-pg-client 0.11.4 ``` * Gradle (in your `build.gradle` file): ```groovy dependencies { compile 'io.reactiverse:reactive-pg-client:0.11.4' } ``` ## Getting started Here is the simplest way to connect, query and disconnect ```kotlin // Pool options var options = PgPoolOptions( port = 5432, host = "the-host", database = "the-db", user = "user", password = "secret", maxSize = 5) // Create the client pool var client = PgClient.pool(options) // A simple query client.query("SELECT * FROM users WHERE id='julien'", { ar -> if (ar.succeeded()) { var result = ar.result() println("Got ${result.size()} rows ") } else { println("Failure: ${ar.cause().getMessage()}") } // Now close the pool client.close() }) ``` ## Connecting to Postgres Most of the time you will use a pool to connect to Postgres: ```kotlin // Pool options var options = PgPoolOptions( port = 5432, host = "the-host", database = "the-db", user = "user", password = "secret", maxSize = 5) // Create the pooled client var client = PgClient.pool(options) ``` The pooled client uses a connection pool and any operation will borrow a connection from the pool to execute the operation and release it to the pool. If you are running with Vert.x you can pass it your Vertx instance: ```kotlin // Pool options var options = PgPoolOptions( port = 5432, host = "the-host", database = "the-db", user = "user", password = "secret", maxSize = 5) // Create the pooled client var client = PgClient.pool(vertx, options) ``` You need to release the pool when you don't need it anymore: ```kotlin // Close the pool and all the associated resources pool.close() ``` When you need to execute several operations on the same connection, you need to use a client [`connection`](../../apidocs/io/reactiverse/pgclient/PgConnection.html). You can easily get one from the pool: ```kotlin // Pool options var options = PgPoolOptions( port = 5432, host = "the-host", database = "the-db", user = "user", password = "secret", maxSize = 5) // Create the pooled client var client = PgClient.pool(vertx, options) // Get a connection from the pool client.getConnection({ ar1 -> if (ar1.succeeded()) { println("Connected") // Obtain our connection var conn = ar1.result() // All operations execute on the same connection conn.query("SELECT * FROM users WHERE id='julien'", { ar2 -> if (ar2.succeeded()) { conn.query("SELECT * FROM users WHERE id='emad'", { ar3 -> // Release the connection to the pool conn.close() }) } else { // Release the connection to the pool conn.close() } }) } else { println("Could not connect: ${ar1.cause().getMessage()}") } }) ``` Once you are done with the connection you must close it to release it to the pool, so it can be reused. Sometimes you want to improve performance via Unix domain socket connection, we achieve this with Vert.x Native transports. Make sure you have added the required `netty-transport-native` dependency in your classpath and enabled the Unix domain socket option. ```kotlin // Pool Options // Socket file name will be /var/run/postgresql/.s.PGSQL.5432 var options = PgPoolOptions( host = "/var/run/postgresql", port = 5432, database = "the-db") // Create the pooled client var client = PgClient.pool(options) // Create the pooled client with a vertx instance // Make sure the vertx instance has enabled native transports var client2 = PgClient.pool(vertx, options) ``` More information can be found in the [Vert.x documentation](https://vertx.io/docs/vertx-core/java/#_native_transports). ## Configuration There are several options for you to configure the client. Apart from configuring with a `PgPoolOptions` data object, We also provide you an alternative way to connect when you want to configure with a connection URI: ```kotlin // Connection URI var connectionUri = "postgresql://dbuser:secretpassword@database.server.com:3211/mydb" // Create the pool from the connection URI var pool = PgClient.pool(connectionUri) // Create the connection from the connection URI PgClient.connect(vertx, connectionUri, { res -> // Handling your connection }) ``` More information about connection string formats can be found in the [PostgreSQL Manuals](https://www.postgresql.org/docs/9.6/static/libpq-connect.html#LIBPQ-CONNSTRING). You can also use environment variables to set default connection setting values, this is useful when you want to avoid hard-coding database connection information. You can refer to the [official documentation](https://www.postgresql.org/docs/9.6/static/libpq-envars.html) for more details. The following parameters are supported: * `PGHOST` * `PGHOSTADDR` * `PGPORT` * `PGDATABASE` * `PGUSER` * `PGPASSWORD` * `PGSSLMODE` If you don't specify a data object or a connection URI string to connect, environment variables will take precedence over them. ``` $ PGUSER=user \ PGHOST=the-host \ PGPASSWORD=secret \ PGDATABASE=the-db \ PGPORT=5432 \ PGSSLMODE=DISABLE ``` ```kotlin // Create the pool from the environment variables var pool = PgClient.pool() // Create the connection from the environment variables PgClient.connect(vertx, { res -> // Handling your connection }) ``` ## Running queries When you don't need a transaction or run single queries, you can run queries directly on the pool; the pool will use one of its connection to run the query and return the result to you. Here is how to run simple queries: ```kotlin client.query("SELECT * FROM users WHERE id='julien'", { ar -> if (ar.succeeded()) { var result = ar.result() println("Got ${result.size()} rows ") } else { println("Failure: ${ar.cause().getMessage()}") } }) ``` You can do the same with prepared queries. The SQL string can refer to parameters by position, using `$1`, `$2`, etc…​ ```kotlin client.preparedQuery("SELECT * FROM users WHERE id=\$$1", Tuple.of("julien"), { ar -> if (ar.succeeded()) { var rows = ar.result() println("Got ${rows.size()} rows ") } else { println("Failure: ${ar.cause().getMessage()}") } }) ``` Query methods provides an asynchronous [`PgRowSet`](../../apidocs/io/reactiverse/pgclient/PgRowSet.html) instance that works for _SELECT_ queries ```kotlin client.preparedQuery("SELECT first_name, last_name FROM users", { ar -> if (ar.succeeded()) { var rows = ar.result() for (row in rows) { println("User ${row.getString(0)} ${row.getString(1)}") } } else { println("Failure: ${ar.cause().getMessage()}") } }) ``` or _UPDATE_/_INSERT_ queries: ```kotlin client.preparedQuery("INSERT INTO users (first_name, last_name) VALUES (\$$1, \$$2)", Tuple.of("Julien", "Viet"), { ar -> if (ar.succeeded()) { var rows = ar.result() println(rows.rowCount()) } else { println("Failure: ${ar.cause().getMessage()}") } }) ``` The [`Row`](../../apidocs/io/reactiverse/pgclient/Row.html) gives you access to your data by index ```kotlin println("User ${row.getString(0)} ${row.getString(1)}") ``` or by name ```kotlin println("User ${row.getString("first_name")} ${row.getString("last_name")}") ``` You can access a wide variety of of types ```kotlin var firstName = row.getString("first_name") var male = row.getBoolean("male") var age = row.getInteger("age") // ... ``` You can execute prepared batch ```kotlin // Add commands to the batch var batch = mutableListOf() batch.add(Tuple.of("julien", "Julien Viet")) batch.add(Tuple.of("emad", "Emad Alblueshi")) // Execute the prepared batch client.preparedBatch("INSERT INTO USERS (id, name) VALUES (\$$1, \$$2)", batch, { res -> if (res.succeeded()) { // Process rows var rows = res.result() } else { println("Batch failed ${res.cause()}") } }) ``` You can cache prepared queries: ```kotlin // Enable prepare statements options.cachePreparedStatements = true var client = PgClient.pool(vertx, options) ``` You can fetch generated keys with a 'RETURNING' clause in your query: ```kotlin client.preparedQuery("INSERT INTO color (color_name) VALUES (\$$1), (\$$2), (\$$3) RETURNING color_id", Tuple.of("white", "red", "blue"), { ar -> if (ar.succeeded()) { var rows = ar.result() println(rows.rowCount()) for (row in rows) { println("generated key: ${row.getInteger("color_id")}") } } else { println("Failure: ${ar.cause().getMessage()}") } }) ``` ## Using connections When you need to execute sequential queries (without a transaction), you can create a new connection or borrow one from the pool: ```kotlin Code not translatable ``` Prepared queries can be created: ```kotlin connection.prepare("SELECT * FROM users WHERE first_name LIKE \$$1", { ar1 -> if (ar1.succeeded()) { var pq = ar1.result() pq.execute(Tuple.of("julien"), { ar2 -> if (ar2.succeeded()) { // All rows var rows = ar2.result() } }) } }) ``` NOTE: prepared query caching depends on the [`setCachePreparedStatements`](../../apidocs/io/reactiverse/pgclient/PgConnectOptions.html#setCachePreparedStatements-boolean-) and does not depend on whether you are creating prepared queries or use [`direct prepared queries`](../../apidocs/io/reactiverse/pgclient/PgClient.html#preparedQuery-java.lang.String-io.vertx.core.Handler-) [`PgPreparedQuery`](../../apidocs/io/reactiverse/pgclient/PgPreparedQuery.html)can perform efficient batching: ```kotlin connection.prepare("INSERT INTO USERS (id, name) VALUES (\$$1, \$$2)", { ar1 -> if (ar1.succeeded()) { var prepared = ar1.result() // Create a query : bind parameters var batch = mutableListOf() // Add commands to the createBatch batch.add(Tuple.of("julien", "Julien Viet")) batch.add(Tuple.of("emad", "Emad Alblueshi")) prepared.batch(batch, { res -> if (res.succeeded()) { // Process rows var rows = res.result() } else { println("Batch failed ${res.cause()}") } }) } }) ``` ## Using transactions ### Transactions with connections You can execute transaction using SQL `BEGIN`/`COMMIT`/`ROLLBACK`, if you do so you must use a [`PgConnection`](../../apidocs/io/reactiverse/pgclient/PgConnection.html) and manage it yourself. Or you can use the transaction API of [`PgConnection`](../../apidocs/io/reactiverse/pgclient/PgConnection.html): ```kotlin Code not translatable ``` When Postgres reports the current transaction is failed (e.g the infamous _current transaction is aborted, commands ignored until end of transaction block_), the transaction is rollbacked and the [`abortHandler`](../../apidocs/io/reactiverse/pgclient/PgTransaction.html#abortHandler-io.vertx.core.Handler-) is called: ```kotlin pool.getConnection({ res -> if (res.succeeded()) { // Transaction must use a connection var conn = res.result() // Begin the transaction var tx = conn.begin().abortHandler({ v -> println("Transaction failed => rollbacked") }) conn.query("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')", { ar -> // Works fine of course if (ar.succeeded()) { } else { tx.rollback() conn.close() } }) conn.query("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')", { ar -> // Fails and triggers transaction aborts }) // Attempt to commit the transaction tx.commit({ ar -> // But transaction abortion fails it // Return the connection to the pool conn.close() }) } }) ``` ### Simplified transaction API When you use a pool, you can start a transaction directly on the pool. It borrows a connection from the pool, begins the transaction and releases the connection to the pool when the transaction ends. ```kotlin Code not translatable ``` ## Cursors and streaming By default prepared query execution fetches all rows, you can use a [`PgCursor`](../../apidocs/io/reactiverse/pgclient/PgCursor.html)to control the amount of rows you want to read: ```kotlin connection.prepare("SELECT * FROM users WHERE first_name LIKE \$$1", { ar1 -> if (ar1.succeeded()) { var pq = ar1.result() // Cursors require to run within a transaction var tx = connection.begin() // Create a cursor var cursor = pq.cursor(Tuple.of("julien")) // Read 50 rows cursor.read(50, { ar2 -> if (ar2.succeeded()) { var rows = ar2.result() // Check for more ? if (cursor.hasMore()) { // Repeat the process... } else { // No more rows - commit the transaction tx.commit() } } }) } }) ``` PostreSQL destroys cursors at the end of a transaction, so the cursor API shall be used within a transaction, otherwise you will likely get the `34000` PostgreSQL error. Cursors shall be closed when they are released prematurely: ```kotlin cursor.read(50, { ar2 -> if (ar2.succeeded()) { // Close the cursor cursor.close() } }) ``` A stream API is also available for cursors, which can be more convenient, specially with the Rxified version. ```kotlin connection.prepare("SELECT * FROM users WHERE first_name LIKE \$$1", { ar1 -> if (ar1.succeeded()) { var pq = ar1.result() // Streams require to run within a transaction var tx = connection.begin() // Fetch 50 rows at a time var stream = pq.createStream(50, Tuple.of("julien")) // Use the stream stream.exceptionHandler({ err -> println("Error: ${err.getMessage()}") }) stream.endHandler({ v -> tx.commit() println("End of stream") }) stream.handler({ row -> println("User: ${row.getString("last_name")}") }) } }) ``` The stream read the rows by batch of `50` and stream them, when the rows have been passed to the handler, a new batch of `50` is read and so on. The stream can be resumed or paused, the loaded rows will remain in memory until they are delivered and the cursor will stop iterating. ## Postgres type mapping Currently the client supports the following Postgres types * BOOLEAN (`java.lang.Boolean`) * INT2 (`java.lang.Short`) * INT4 (`java.lang.Integer`) * INT8 (`java.lang.Long`) * FLOAT4 (`java.lang.Float`) * FLOAT8 (`java.lang.Double`) * CHAR (`java.lang.String`) * VARCHAR (`java.lang.String`) * TEXT (`java.lang.String`) * ENUM (`java.lang.String`) * NAME (`java.lang.String`) * SERIAL2 (`java.lang.Short`) * SERIAL4 (`java.lang.Integer`) * SERIAL8 (`java.lang.Long`) * NUMERIC (`io.reactiverse.pgclient.data.Numeric`) * UUID (`java.util.UUID`) * DATE (`java.time.LocalDate`) * TIME (`java.time.LocalTime`) * TIMETZ (`java.time.OffsetTime`) * TIMESTAMP (`java.time.LocalDateTime`) * TIMESTAMPTZ (`java.time.OffsetDateTime`) * INTERVAL (`io.reactiverse.pgclient.data.Interval`) * BYTEA (`io.vertx.core.buffer.Buffer`) * JSON (`io.reactiverse.pgclient.data.Json`) * JSONB (`io.reactiverse.pgclient.data.Json`) * POINT (`io.reactiverse.pgclient.data.Point`) * LINE (`io.reactiverse.pgclient.data.Line`) * LSEG (`io.reactiverse.pgclient.data.LineSegment`) * BOX (`io.reactiverse.pgclient.data.Box`) * PATH (`io.reactiverse.pgclient.data.Path`) * POLYGON (`io.reactiverse.pgclient.data.Polygon`) * CIRCLE (`io.reactiverse.pgclient.data.Circle`) Tuple decoding uses the above types when storing values, it also performs on the flu conversion the actual value when possible: ```kotlin pool.query("SELECT 1::BIGINT \"VAL\"", { ar -> var rowSet = ar.result() var row = rowSet.iterator().next() // Stored as java.lang.Long var value = row.getValue(0) // Convert to java.lang.Integer var intValue = row.getInteger(0) }) ``` Tuple encoding uses the above type mapping for encoding, unless the type is numeric in which case `java.lang.Number` is used instead: ```kotlin pool.query("SELECT 1::BIGINT \"VAL\"", { ar -> var rowSet = ar.result() var row = rowSet.iterator().next() // Stored as java.lang.Long var value = row.getValue(0) // Convert to java.lang.Integer var intValue = row.getInteger(0) }) ``` Arrays of these types are supported. ### Handling JSON The [`Json`](../../apidocs/io/reactiverse/pgclient/data/Json.html) Java type is used to represent the Postgres `JSON` and `JSONB` type. The main reason of this type is handling `null` JSON values. ```kotlin // Create a tuple var tuple = Tuple.of(Json.create(Json.create(null)), Json.create(Json.create(json { obj("foo" to "bar") })), Json.create(Json.create(null))) // Retrieving json var value = tuple.getJson(0).value() // value = tuple.getJson(1).value() // value = tuple.getJson(3).value() ``` ### Handling NUMERIC The [`Numeric`](../../apidocs/io/reactiverse/pgclient/data/Numeric.html) Java type is used to represent the Postgres `NUMERIC` type. ```kotlin var numeric = row.getNumeric("value") if (numeric.isNaN()) { // Handle NaN } else { var value = numeric.bigDecimalValue() } ``` ## Handling arrays Arrays are available on [`Tuple`](../../apidocs/io/reactiverse/pgclient/Tuple.html) and [`Row`](../../apidocs/io/reactiverse/pgclient/Row.html): ```kotlin Code not translatable ``` ## Handling custom types Strings are used to represent custom types, both sent to and returned from Postgres. You can read from Postgres and get the custom type as a string ```kotlin client.preparedQuery("SELECT address, (address).city FROM address_book WHERE id=\$$1", Tuple.of(3), { ar -> if (ar.succeeded()) { var rows = ar.result() for (row in rows) { println("Full Address ${row.getString(0)}, City ${row.getString(1)}") } } else { println("Failure: ${ar.cause().getMessage()}") } }) ``` You can also write to Postgres by providing a string ```kotlin client.preparedQuery("INSERT INTO address_book (id, address) VALUES (\$$1, \$$2)", Tuple.of(3, "('Anytown', 'Second Ave', false)"), { ar -> if (ar.succeeded()) { var rows = ar.result() println(rows.rowCount()) } else { println("Failure: ${ar.cause().getMessage()}") } }) ``` ## Collector queries You can use Java collectors with the query API: ```kotlin Code not translatable ``` The collector processing must not keep a reference on the [`Row`](../../apidocs/io/reactiverse/pgclient/Row.html) as there is a single row used for processing the entire set. The Java `Collectors` provides many interesting predefined collectors, for example you can create easily create a string directly from the row set: ```kotlin Code not translatable ``` ## RxJava support The rxified API supports RxJava 1 and RxJava 2, the following examples use RxJava 2. Most asynchronous constructs are available as methods prefixed by `rx`: ```kotlin Code not translatable ``` ### Streaming RxJava 2 supports `Observable` and `Flowable` types, these are exposed using the [`PgStream`](../../apidocs/io/reactiverse/reactivex/pgclient/PgStream.html) that you can get from a [`PgPreparedQuery`](../../apidocs/io/reactiverse/reactivex/pgclient/PgPreparedQuery.html): ```kotlin Code not translatable ``` The same example using `Flowable`: ```kotlin Code not translatable ``` ### Transaction The simplified transaction API allows to easily write transactional asynchronous flows: ```kotlin Code not translatable ``` ## Pub/sub Postgres supports pub/sub communication channels. You can set a [`notificationHandler`](../../apidocs/io/reactiverse/pgclient/PgConnection.html#notificationHandler-io.vertx.core.Handler-) to receive Postgres notifications: ```kotlin connection.notificationHandler({ notification -> println("Received ${notification.payload} on channel ${notification.channel}") }) connection.query("LISTEN some-channel", { ar -> println("Subscribed to channel") }) ``` The [`PgSubscriber`](../../apidocs/io/reactiverse/pgclient/pubsub/PgSubscriber.html) is a channel manager managing a single connection that provides per channel subscription: ```kotlin var subscriber = PgSubscriber.subscriber(vertx, PgConnectOptions( port = 5432, host = "the-host", database = "the-db", user = "user", password = "secret")) // You can set the channel before connect subscriber.channel("channel1").handler({ payload -> println("Received ${payload}") }) subscriber.connect({ ar -> if (ar.succeeded()) { // Or you can set the channel after connect subscriber.channel("channel2").handler({ payload -> println("Received ${payload}") }) } }) ``` The channel name that is given to the channel method will be the exact name of the channel as held by Postgres for sending notifications. Note this is different than the representation of the channel name in SQL, and internally [`PgSubscriber`](../../apidocs/io/reactiverse/pgclient/pubsub/PgSubscriber.html) will prepare the submitted channel name as a quoted identifier: ```kotlin var subscriber = PgSubscriber.subscriber(vertx, PgConnectOptions( port = 5432, host = "the-host", database = "the-db", user = "user", password = "secret")) subscriber.connect({ ar -> if (ar.succeeded()) { // Complex channel name - name in PostgreSQL requires a quoted ID subscriber.channel("Complex.Channel.Name").handler({ payload -> println("Received ${payload}") }) subscriber.channel("Complex.Channel.Name").subscribeHandler({ subscribed -> subscriber.actualConnection().query("NOTIFY \"Complex.Channel.Name\", 'msg'", { notified -> println("Notified \"Complex.Channel.Name\"") }) }) // PostgreSQL simple ID's are forced lower-case subscriber.channel("simple_channel").handler({ payload -> println("Received ${payload}") }) subscriber.channel("simple_channel").subscribeHandler({ subscribed -> // The following simple channel identifier is forced to lower case subscriber.actualConnection().query("NOTIFY Simple_CHANNEL, 'msg'", { notified -> println("Notified simple_channel") }) }) // The following channel name is longer than the current // (NAMEDATALEN = 64) - 1 == 63 character limit and will be truncated subscriber.channel("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbb").handler({ payload -> println("Received ${payload}") }) } }) ``` You can provide a reconnect policy as a function that takes the number of `retries` as argument and returns an `amountOfTime` value: * when `amountOfTime < 0`: the subscriber is closed and there is no retry * when `amountOfTime = 0`: the subscriber retries to connect immediately * when `amountOfTime > 0`: the subscriber retries after `amountOfTime` milliseconds ```kotlin var subscriber = PgSubscriber.subscriber(vertx, PgConnectOptions( port = 5432, host = "the-host", database = "the-db", user = "user", password = "secret")) // Reconnect at most 10 times after 100 ms each subscriber.reconnectPolicy({ retries -> if (retries < 10) { return 100L } else { return -1L } }) ``` The default policy is to not reconnect. ## Cancelling Request Postgres supports cancellation of requests in progress. You can cancel inflight requests using [`cancelRequest`](../../apidocs/io/reactiverse/pgclient/PgConnection.html#cancelRequest-io.vertx.core.Handler-). Cancelling a request opens a new connection to the server and cancels the request and then close the connection. ```kotlin connection.query("SELECT pg_sleep(20)", { ar -> if (ar.succeeded()) { // imagine this is a long query and is still running println("Query success") } else { // the server will abort the current query after cancelling request println("Failed to query due to ${ar.cause().getMessage()}") } }) connection.cancelRequest({ ar -> if (ar.succeeded()) { println("Cancelling request has been sent") } else { println("Failed to send cancelling request") } }) ``` > The cancellation signal might or might not have any effect — for example, if it arrives after the backend has finished processing the query, then it will have no effect. If the cancellation is effective, it results in the current command being terminated early with an error message. More information can be found in the [official documentation](https://www.postgresql.org/docs/11/protocol-flow.html#id-1.10.5.7.9). ## Using SSL/TLS To configure the client to use SSL connection, you can configure the [`PgConnectOptions`](../../apidocs/io/reactiverse/pgclient/PgConnectOptions.html) like a Vert.x `NetClient`. All [SSL modes](https://www.postgresql.org/docs/current/libpq-ssl.html#LIBPQ-SSL-PROTECTION) are supported and you are able to configure `sslmode`. The client is in `DISABLE` SSL mode by default. `ssl` parameter is kept as a mere shortcut for setting `sslmode`. `setSsl(true)` is equivalent to `setSslMode(VERIFY_CA)` and `setSsl(false)` is equivalent to `setSslMode(DISABLE)`. ```kotlin var options = PgConnectOptions( port = 5432, host = "the-host", database = "the-db", user = "user", password = "secret", sslMode = SslMode.VERIFY_CA, pemTrustOptions = PemTrustOptions( certPaths = listOf("/path/to/cert.pem"))) PgClient.connect(vertx, options, { res -> if (res.succeeded()) { // Connected with SSL } else { println("Could not connect ${res.cause()}") } }) ``` More information can be found in the [Vert.x documentation](http://vertx.io/docs/vertx-core/java/#ssl). ## Using a proxy You can also configure the client to use an HTTP/1.x CONNECT, SOCKS4a or SOCKS5 proxy. More information can be found in the [Vert.x documentation](http://vertx.io/docs/vertx-core/java/#_using_a_proxy_for_client_connections). ================================================ FILE: docs/guide/ruby/index.md ================================================ # Reactive Postgres Client The Reactive Postgres Client is a client for Postgres with a straightforward API focusing on scalability and low overhead. The client is reactive and non blocking, allowing to handle many database connections with a single thread. * Event driven * Lightweight * Built-in connection pooling * Prepared queries caching * Publish / subscribe using Postgres `NOTIFY/LISTEN` * Batch and cursor * Row streaming * Command pipeling * RxJava 1 and RxJava 2 * Direct memory to object without unnecessary copies * Java 8 Date and Time * SSL/TLS * Unix domain socket * HTTP/1.x CONNECT, SOCKS4a or SOCKS5 proxy support ## Usage To use the Reactive Postgres Client add the following dependency to the _dependencies_ section of your build descriptor: * Maven (in your `pom.xml`): ```xml io.reactiverse reactive-pg-client 0.11.4 ``` * Gradle (in your `build.gradle` file): ```groovy dependencies { compile 'io.reactiverse:reactive-pg-client:0.11.4' } ``` ## Getting started Here is the simplest way to connect, query and disconnect ```ruby require 'reactive-pg-client/pg_client' # Pool options options = { 'port' => 5432, 'host' => "the-host", 'database' => "the-db", 'user' => "user", 'password' => "secret", 'maxSize' => 5 } # Create the client pool client = ReactivePgClient::PgClient.pool(options) # A simple query client.query("SELECT * FROM users WHERE id='julien'") { |ar_err,ar| if (ar_err == nil) result = ar puts "Got #{result.size()} rows " else puts "Failure: #{ar_err.get_message()}" end # Now close the pool client.close() } ``` ## Connecting to Postgres Most of the time you will use a pool to connect to Postgres: ```ruby require 'reactive-pg-client/pg_client' # Pool options options = { 'port' => 5432, 'host' => "the-host", 'database' => "the-db", 'user' => "user", 'password' => "secret", 'maxSize' => 5 } # Create the pooled client client = ReactivePgClient::PgClient.pool(options) ``` The pooled client uses a connection pool and any operation will borrow a connection from the pool to execute the operation and release it to the pool. If you are running with Vert.x you can pass it your Vertx instance: ```ruby require 'reactive-pg-client/pg_client' # Pool options options = { 'port' => 5432, 'host' => "the-host", 'database' => "the-db", 'user' => "user", 'password' => "secret", 'maxSize' => 5 } # Create the pooled client client = ReactivePgClient::PgClient.pool(vertx, options) ``` You need to release the pool when you don't need it anymore: ```ruby # Close the pool and all the associated resources pool.close() ``` When you need to execute several operations on the same connection, you need to use a client [`connection`](../../yardoc/ReactivePgClient/PgConnection.html). You can easily get one from the pool: ```ruby require 'reactive-pg-client/pg_client' # Pool options options = { 'port' => 5432, 'host' => "the-host", 'database' => "the-db", 'user' => "user", 'password' => "secret", 'maxSize' => 5 } # Create the pooled client client = ReactivePgClient::PgClient.pool(vertx, options) # Get a connection from the pool client.get_connection() { |ar1_err,ar1| if (ar1_err == nil) puts "Connected" # Obtain our connection conn = ar1 # All operations execute on the same connection conn.query("SELECT * FROM users WHERE id='julien'") { |ar2_err,ar2| if (ar2_err == nil) conn.query("SELECT * FROM users WHERE id='emad'") { |ar3_err,ar3| # Release the connection to the pool conn.close() } else # Release the connection to the pool conn.close() end } else puts "Could not connect: #{ar1_err.get_message()}" end } ``` Once you are done with the connection you must close it to release it to the pool, so it can be reused. Sometimes you want to improve performance via Unix domain socket connection, we achieve this with Vert.x Native transports. Make sure you have added the required `netty-transport-native` dependency in your classpath and enabled the Unix domain socket option. ```ruby require 'reactive-pg-client/pg_client' # Pool Options # Socket file name will be /var/run/postgresql/.s.PGSQL.5432 options = { 'host' => "/var/run/postgresql", 'port' => 5432, 'database' => "the-db" } # Create the pooled client client = ReactivePgClient::PgClient.pool(options) # Create the pooled client with a vertx instance # Make sure the vertx instance has enabled native transports client2 = ReactivePgClient::PgClient.pool(vertx, options) ``` More information can be found in the [Vert.x documentation](https://vertx.io/docs/vertx-core/java/#_native_transports). ## Configuration There are several options for you to configure the client. Apart from configuring with a `PgPoolOptions` data object, We also provide you an alternative way to connect when you want to configure with a connection URI: ```ruby require 'reactive-pg-client/pg_client' # Connection URI connectionUri = "postgresql://dbuser:secretpassword@database.server.com:3211/mydb" # Create the pool from the connection URI pool = ReactivePgClient::PgClient.pool(connectionUri) # Create the connection from the connection URI ReactivePgClient::PgClient.connect(vertx, connectionUri) { |res_err,res| # Handling your connection } ``` More information about connection string formats can be found in the [PostgreSQL Manuals](https://www.postgresql.org/docs/9.6/static/libpq-connect.html#LIBPQ-CONNSTRING). You can also use environment variables to set default connection setting values, this is useful when you want to avoid hard-coding database connection information. You can refer to the [official documentation](https://www.postgresql.org/docs/9.6/static/libpq-envars.html) for more details. The following parameters are supported: * `PGHOST` * `PGHOSTADDR` * `PGPORT` * `PGDATABASE` * `PGUSER` * `PGPASSWORD` * `PGSSLMODE` If you don't specify a data object or a connection URI string to connect, environment variables will take precedence over them. ``` $ PGUSER=user \ PGHOST=the-host \ PGPASSWORD=secret \ PGDATABASE=the-db \ PGPORT=5432 \ PGSSLMODE=DISABLE ``` ```ruby require 'reactive-pg-client/pg_client' # Create the pool from the environment variables pool = ReactivePgClient::PgClient.pool() # Create the connection from the environment variables ReactivePgClient::PgClient.connect(vertx) { |res_err,res| # Handling your connection } ``` ## Running queries When you don't need a transaction or run single queries, you can run queries directly on the pool; the pool will use one of its connection to run the query and return the result to you. Here is how to run simple queries: ```ruby client.query("SELECT * FROM users WHERE id='julien'") { |ar_err,ar| if (ar_err == nil) result = ar puts "Got #{result.size()} rows " else puts "Failure: #{ar_err.get_message()}" end } ``` You can do the same with prepared queries. The SQL string can refer to parameters by position, using `$1`, `$2`, etc…​ ```ruby require 'reactive-pg-client/tuple' client.prepared_query("SELECT * FROM users WHERE id=$1", ReactivePgClient::Tuple.of("julien")) { |ar_err,ar| if (ar_err == nil) rows = ar puts "Got #{rows.size()} rows " else puts "Failure: #{ar_err.get_message()}" end } ``` Query methods provides an asynchronous [`PgRowSet`](../../yardoc/ReactivePgClient/PgRowSet.html) instance that works for _SELECT_ queries ```ruby client.prepared_query("SELECT first_name, last_name FROM users") { |ar_err,ar| if (ar_err == nil) rows = ar rows.each do |row| puts "User #{row.get_string(0)} #{row.get_string(1)}" end else puts "Failure: #{ar_err.get_message()}" end } ``` or _UPDATE_/_INSERT_ queries: ```ruby require 'reactive-pg-client/tuple' client.prepared_query("INSERT INTO users (first_name, last_name) VALUES ($1, $2)", ReactivePgClient::Tuple.of("Julien", "Viet")) { |ar_err,ar| if (ar_err == nil) rows = ar puts rows.row_count() else puts "Failure: #{ar_err.get_message()}" end } ``` The [`Row`](../../yardoc/ReactivePgClient/Row.html) gives you access to your data by index ```ruby puts "User #{row.get_string(0)} #{row.get_string(1)}" ``` or by name ```ruby puts "User #{row.get_string("first_name")} #{row.get_string("last_name")}" ``` You can access a wide variety of of types ```ruby firstName = row.get_string("first_name") male = row.get_boolean?("male") age = row.get_integer("age") # ... ``` You can execute prepared batch ```ruby require 'reactive-pg-client/tuple' # Add commands to the batch batch = Array.new batch.push(ReactivePgClient::Tuple.of("julien", "Julien Viet")) batch.push(ReactivePgClient::Tuple.of("emad", "Emad Alblueshi")) # Execute the prepared batch client.prepared_batch("INSERT INTO USERS (id, name) VALUES ($1, $2)", batch) { |res_err,res| if (res_err == nil) # Process rows rows = res else puts "Batch failed #{res_err}" end } ``` You can cache prepared queries: ```ruby require 'reactive-pg-client/pg_client' # Enable prepare statements options['cachePreparedStatements'] = true client = ReactivePgClient::PgClient.pool(vertx, options) ``` You can fetch generated keys with a 'RETURNING' clause in your query: ```ruby require 'reactive-pg-client/tuple' client.prepared_query("INSERT INTO color (color_name) VALUES ($1), ($2), ($3) RETURNING color_id", ReactivePgClient::Tuple.of("white", "red", "blue")) { |ar_err,ar| if (ar_err == nil) rows = ar puts rows.row_count() rows.each do |row| puts "generated key: #{row.get_integer("color_id")}" end else puts "Failure: #{ar_err.get_message()}" end } ``` ## Using connections When you need to execute sequential queries (without a transaction), you can create a new connection or borrow one from the pool: ```ruby Code not translatable ``` Prepared queries can be created: ```ruby require 'reactive-pg-client/tuple' connection.prepare("SELECT * FROM users WHERE first_name LIKE $1") { |ar1_err,ar1| if (ar1_err == nil) pq = ar1 pq.execute(ReactivePgClient::Tuple.of("julien")) { |ar2_err,ar2| if (ar2_err == nil) # All rows rows = ar2 end } end } ``` NOTE: prepared query caching depends on the [`cachePreparedStatements`](../dataobjects.html#PgConnectOptions#set_cache_prepared_statements-instance_method) and does not depend on whether you are creating prepared queries or use [`direct prepared queries`](../../yardoc/ReactivePgClient/PgClient.html#prepared_query-instance_method) [`PgPreparedQuery`](../../yardoc/ReactivePgClient/PgPreparedQuery.html)can perform efficient batching: ```ruby require 'reactive-pg-client/tuple' connection.prepare("INSERT INTO USERS (id, name) VALUES ($1, $2)") { |ar1_err,ar1| if (ar1_err == nil) prepared = ar1 # Create a query : bind parameters batch = Array.new # Add commands to the createBatch batch.push(ReactivePgClient::Tuple.of("julien", "Julien Viet")) batch.push(ReactivePgClient::Tuple.of("emad", "Emad Alblueshi")) prepared.batch(batch) { |res_err,res| if (res_err == nil) # Process rows rows = res else puts "Batch failed #{res_err}" end } end } ``` ## Using transactions ### Transactions with connections You can execute transaction using SQL `BEGIN`/`COMMIT`/`ROLLBACK`, if you do so you must use a [`PgConnection`](../../yardoc/ReactivePgClient/PgConnection.html) and manage it yourself. Or you can use the transaction API of [`PgConnection`](../../yardoc/ReactivePgClient/PgConnection.html): ```ruby Code not translatable ``` When Postgres reports the current transaction is failed (e.g the infamous _current transaction is aborted, commands ignored until end of transaction block_), the transaction is rollbacked and the [`abortHandler`](../../yardoc/ReactivePgClient/PgTransaction.html#abort_handler-instance_method) is called: ```ruby pool.get_connection() { |res_err,res| if (res_err == nil) # Transaction must use a connection conn = res # Begin the transaction tx = conn.begin().abort_handler() { |v| puts "Transaction failed => rollbacked" } conn.query("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')") { |ar_err,ar| # Works fine of course if (ar_err == nil) else tx.rollback() conn.close() end } conn.query("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')") { |ar_err,ar| # Fails and triggers transaction aborts } # Attempt to commit the transaction tx.commit() { |ar_err,ar| # But transaction abortion fails it # Return the connection to the pool conn.close() } end } ``` ### Simplified transaction API When you use a pool, you can start a transaction directly on the pool. It borrows a connection from the pool, begins the transaction and releases the connection to the pool when the transaction ends. ```ruby Code not translatable ``` ## Cursors and streaming By default prepared query execution fetches all rows, you can use a [`PgCursor`](../../yardoc/ReactivePgClient/PgCursor.html)to control the amount of rows you want to read: ```ruby require 'reactive-pg-client/tuple' connection.prepare("SELECT * FROM users WHERE first_name LIKE $1") { |ar1_err,ar1| if (ar1_err == nil) pq = ar1 # Cursors require to run within a transaction tx = connection.begin() # Create a cursor cursor = pq.cursor(ReactivePgClient::Tuple.of("julien")) # Read 50 rows cursor.read(50) { |ar2_err,ar2| if (ar2_err == nil) rows = ar2 # Check for more ? if (cursor.has_more?()) # Repeat the process... else # No more rows - commit the transaction tx.commit() end end } end } ``` PostreSQL destroys cursors at the end of a transaction, so the cursor API shall be used within a transaction, otherwise you will likely get the `34000` PostgreSQL error. Cursors shall be closed when they are released prematurely: ```ruby cursor.read(50) { |ar2_err,ar2| if (ar2_err == nil) # Close the cursor cursor.close() end } ``` A stream API is also available for cursors, which can be more convenient, specially with the Rxified version. ```ruby require 'reactive-pg-client/tuple' connection.prepare("SELECT * FROM users WHERE first_name LIKE $1") { |ar1_err,ar1| if (ar1_err == nil) pq = ar1 # Streams require to run within a transaction tx = connection.begin() # Fetch 50 rows at a time stream = pq.create_stream(50, ReactivePgClient::Tuple.of("julien")) # Use the stream stream.exception_handler() { |err| puts "Error: #{err.get_message()}" } stream.end_handler() { |v| tx.commit() puts "End of stream" } stream.handler() { |row| puts "User: #{row.get_string("last_name")}" } end } ``` The stream read the rows by batch of `50` and stream them, when the rows have been passed to the handler, a new batch of `50` is read and so on. The stream can be resumed or paused, the loaded rows will remain in memory until they are delivered and the cursor will stop iterating. ## Postgres type mapping Currently the client supports the following Postgres types * BOOLEAN (`java.lang.Boolean`) * INT2 (`java.lang.Short`) * INT4 (`java.lang.Integer`) * INT8 (`java.lang.Long`) * FLOAT4 (`java.lang.Float`) * FLOAT8 (`java.lang.Double`) * CHAR (`java.lang.String`) * VARCHAR (`java.lang.String`) * TEXT (`java.lang.String`) * ENUM (`java.lang.String`) * NAME (`java.lang.String`) * SERIAL2 (`java.lang.Short`) * SERIAL4 (`java.lang.Integer`) * SERIAL8 (`java.lang.Long`) * NUMERIC (`io.reactiverse.pgclient.data.Numeric`) * UUID (`java.util.UUID`) * DATE (`java.time.LocalDate`) * TIME (`java.time.LocalTime`) * TIMETZ (`java.time.OffsetTime`) * TIMESTAMP (`java.time.LocalDateTime`) * TIMESTAMPTZ (`java.time.OffsetDateTime`) * INTERVAL (`io.reactiverse.pgclient.data.Interval`) * BYTEA (`io.vertx.core.buffer.Buffer`) * JSON (`io.reactiverse.pgclient.data.Json`) * JSONB (`io.reactiverse.pgclient.data.Json`) * POINT (`io.reactiverse.pgclient.data.Point`) * LINE (`io.reactiverse.pgclient.data.Line`) * LSEG (`io.reactiverse.pgclient.data.LineSegment`) * BOX (`io.reactiverse.pgclient.data.Box`) * PATH (`io.reactiverse.pgclient.data.Path`) * POLYGON (`io.reactiverse.pgclient.data.Polygon`) * CIRCLE (`io.reactiverse.pgclient.data.Circle`) Tuple decoding uses the above types when storing values, it also performs on the flu conversion the actual value when possible: ```ruby pool.query("SELECT 1::BIGINT \"VAL\"") { |ar_err,ar| rowSet = ar row = rowSet.iterator().next() # Stored as java.lang.Long value = row.get_value(0) # Convert to java.lang.Integer intValue = row.get_integer(0) } ``` Tuple encoding uses the above type mapping for encoding, unless the type is numeric in which case `java.lang.Number` is used instead: ```ruby pool.query("SELECT 1::BIGINT \"VAL\"") { |ar_err,ar| rowSet = ar row = rowSet.iterator().next() # Stored as java.lang.Long value = row.get_value(0) # Convert to java.lang.Integer intValue = row.get_integer(0) } ``` Arrays of these types are supported. ### Handling JSON The [`Json`](../../yardoc/ReactivePgClient/Json.html) Java type is used to represent the Postgres `JSON` and `JSONB` type. The main reason of this type is handling `null` JSON values. ```ruby require 'reactive-pg-client/json' require 'reactive-pg-client/tuple' # Create a tuple tuple = ReactivePgClient::Tuple.of(ReactivePgClient::Json.create(ReactivePgClient::Json.create(nil)), ReactivePgClient::Json.create(ReactivePgClient::Json.create({ 'foo' => "bar" })), ReactivePgClient::Json.create(ReactivePgClient::Json.create(nil))) # Retrieving json value = tuple.get_json(0).value() # value = tuple.get_json(1).value() # value = tuple.get_json(3).value() ``` ### Handling NUMERIC The [`Numeric`](unavailable) Java type is used to represent the Postgres `NUMERIC` type. ```ruby numeric = row.get_numeric("value") if (numeric.na_n?()) # Handle NaN else value = numeric.big_decimal_value() end ``` ## Handling arrays Arrays are available on [`Tuple`](../../yardoc/ReactivePgClient/Tuple.html) and [`Row`](../../yardoc/ReactivePgClient/Row.html): ```ruby Code not translatable ``` ## Handling custom types Strings are used to represent custom types, both sent to and returned from Postgres. You can read from Postgres and get the custom type as a string ```ruby require 'reactive-pg-client/tuple' client.prepared_query("SELECT address, (address).city FROM address_book WHERE id=$1", ReactivePgClient::Tuple.of(3)) { |ar_err,ar| if (ar_err == nil) rows = ar rows.each do |row| puts "Full Address #{row.get_string(0)}, City #{row.get_string(1)}" end else puts "Failure: #{ar_err.get_message()}" end } ``` You can also write to Postgres by providing a string ```ruby require 'reactive-pg-client/tuple' client.prepared_query("INSERT INTO address_book (id, address) VALUES ($1, $2)", ReactivePgClient::Tuple.of(3, "('Anytown', 'Second Ave', false)")) { |ar_err,ar| if (ar_err == nil) rows = ar puts rows.row_count() else puts "Failure: #{ar_err.get_message()}" end } ``` ## Collector queries You can use Java collectors with the query API: ```ruby Code not translatable ``` The collector processing must not keep a reference on the [`Row`](../../yardoc/ReactivePgClient/Row.html) as there is a single row used for processing the entire set. The Java `Collectors` provides many interesting predefined collectors, for example you can create easily create a string directly from the row set: ```ruby Code not translatable ``` ## RxJava support The rxified API supports RxJava 1 and RxJava 2, the following examples use RxJava 2. Most asynchronous constructs are available as methods prefixed by `rx`: ```ruby Code not translatable ``` ### Streaming RxJava 2 supports `Observable` and `Flowable` types, these are exposed using the [`PgStream`](unavailable) that you can get from a [`PgPreparedQuery`](unavailable): ```ruby Code not translatable ``` The same example using `Flowable`: ```ruby Code not translatable ``` ### Transaction The simplified transaction API allows to easily write transactional asynchronous flows: ```ruby Code not translatable ``` ## Pub/sub Postgres supports pub/sub communication channels. You can set a [`notificationHandler`](../../yardoc/ReactivePgClient/PgConnection.html#notification_handler-instance_method) to receive Postgres notifications: ```ruby connection.notification_handler() { |notification| puts "Received #{notification['payload']} on channel #{notification['channel']}" } connection.query("LISTEN some-channel") { |ar_err,ar| puts "Subscribed to channel" } ``` The [`PgSubscriber`](../../yardoc/ReactivePgClient/PgSubscriber.html) is a channel manager managing a single connection that provides per channel subscription: ```ruby require 'reactive-pg-client/pg_subscriber' subscriber = ReactivePgClient::PgSubscriber.subscriber(vertx, { 'port' => 5432, 'host' => "the-host", 'database' => "the-db", 'user' => "user", 'password' => "secret" }) # You can set the channel before connect subscriber.channel("channel1").handler() { |payload| puts "Received #{payload}" } subscriber.connect() { |ar_err,ar| if (ar_err == nil) # Or you can set the channel after connect subscriber.channel("channel2").handler() { |payload| puts "Received #{payload}" } end } ``` The channel name that is given to the channel method will be the exact name of the channel as held by Postgres for sending notifications. Note this is different than the representation of the channel name in SQL, and internally [`PgSubscriber`](../../yardoc/ReactivePgClient/PgSubscriber.html) will prepare the submitted channel name as a quoted identifier: ```ruby require 'reactive-pg-client/pg_subscriber' subscriber = ReactivePgClient::PgSubscriber.subscriber(vertx, { 'port' => 5432, 'host' => "the-host", 'database' => "the-db", 'user' => "user", 'password' => "secret" }) subscriber.connect() { |ar_err,ar| if (ar_err == nil) # Complex channel name - name in PostgreSQL requires a quoted ID subscriber.channel("Complex.Channel.Name").handler() { |payload| puts "Received #{payload}" } subscriber.channel("Complex.Channel.Name").subscribe_handler() { |subscribed| subscriber.actual_connection().query("NOTIFY \"Complex.Channel.Name\", 'msg'") { |notified_err,notified| puts "Notified \"Complex.Channel.Name\"" } } # PostgreSQL simple ID's are forced lower-case subscriber.channel("simple_channel").handler() { |payload| puts "Received #{payload}" } subscriber.channel("simple_channel").subscribe_handler() { |subscribed| # The following simple channel identifier is forced to lower case subscriber.actual_connection().query("NOTIFY Simple_CHANNEL, 'msg'") { |notified_err,notified| puts "Notified simple_channel" } } # The following channel name is longer than the current # (NAMEDATALEN = 64) - 1 == 63 character limit and will be truncated subscriber.channel("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbb").handler() { |payload| puts "Received #{payload}" } end } ``` You can provide a reconnect policy as a function that takes the number of `retries` as argument and returns an `amountOfTime` value: * when `amountOfTime < 0`: the subscriber is closed and there is no retry * when `amountOfTime = 0`: the subscriber retries to connect immediately * when `amountOfTime > 0`: the subscriber retries after `amountOfTime` milliseconds ```ruby require 'reactive-pg-client/pg_subscriber' subscriber = ReactivePgClient::PgSubscriber.subscriber(vertx, { 'port' => 5432, 'host' => "the-host", 'database' => "the-db", 'user' => "user", 'password' => "secret" }) # Reconnect at most 10 times after 100 ms each subscriber.reconnect_policy(lambda { |retries| if (retries < 10) return 100 else return -1 end }) ``` The default policy is to not reconnect. ## Cancelling Request Postgres supports cancellation of requests in progress. You can cancel inflight requests using [`cancelRequest`](../../yardoc/ReactivePgClient/PgConnection.html#cancel_request-instance_method). Cancelling a request opens a new connection to the server and cancels the request and then close the connection. ```ruby connection.query("SELECT pg_sleep(20)") { |ar_err,ar| if (ar_err == nil) # imagine this is a long query and is still running puts "Query success" else # the server will abort the current query after cancelling request puts "Failed to query due to #{ar_err.get_message()}" end } connection.cancel_request() { |ar_err,ar| if (ar_err == nil) puts "Cancelling request has been sent" else puts "Failed to send cancelling request" end } ``` > The cancellation signal might or might not have any effect — for example, if it arrives after the backend has finished processing the query, then it will have no effect. If the cancellation is effective, it results in the current command being terminated early with an error message. More information can be found in the [official documentation](https://www.postgresql.org/docs/11/protocol-flow.html#id-1.10.5.7.9). ## Using SSL/TLS To configure the client to use SSL connection, you can configure the [`PgConnectOptions`](../dataobjects.html#PgConnectOptions) like a Vert.x `NetClient`. All [SSL modes](https://www.postgresql.org/docs/current/libpq-ssl.html#LIBPQ-SSL-PROTECTION) are supported and you are able to configure `sslmode`. The client is in `DISABLE` SSL mode by default. `ssl` parameter is kept as a mere shortcut for setting `sslmode`. `setSsl(true)` is equivalent to `setSslMode(VERIFY_CA)` and `setSsl(false)` is equivalent to `setSslMode(DISABLE)`. ```ruby require 'reactive-pg-client/pg_client' options = { 'port' => 5432, 'host' => "the-host", 'database' => "the-db", 'user' => "user", 'password' => "secret", 'sslMode' => "VERIFY_CA", 'pemTrustOptions' => { 'certPaths' => [ "/path/to/cert.pem" ] } } ReactivePgClient::PgClient.connect(vertx, options) { |res_err,res| if (res_err == nil) # Connected with SSL else puts "Could not connect #{res_err}" end } ``` More information can be found in the [Vert.x documentation](http://vertx.io/docs/vertx-core/java/#ssl). ## Using a proxy You can also configure the client to use an HTTP/1.x CONNECT, SOCKS4a or SOCKS5 proxy. More information can be found in the [Vert.x documentation](http://vertx.io/docs/vertx-core/java/#_using_a_proxy_for_client_connections). ================================================ FILE: docs/jsdoc/index.html ================================================ JSDoc: Home

Home


Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:18 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/json.js.html ================================================ JSDoc: Source: json.js

Source: json.js

/*
 * Copyright 2014 Red Hat, Inc.
 *
 * Red Hat 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.
 */

/** @module reactive-pg-client-js/json */
var utils = require('vertx-js/util/utils');

var io = Packages.io;
var JsonObject = io.vertx.core.json.JsonObject;
var JJson = Java.type('io.reactiverse.pgclient.data.Json');

/**
 @class
*/
var Json = function(j_val) {

  var j_json = j_val;
  var that = this;

  var __super_create = this.create;
  var __super_value = this.value;
  /**

   @public

   @return {Object}
   */
  this.value =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      return utils.convReturnTypeUnknown(j_json["value()"]()) ;
    } else if (typeof __super_value != 'undefined') {
      return __super_value.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  // A reference to the underlying Java delegate
  // NOTE! This is an internal API and must not be used in user code.
  // If you rely on this property your code is likely to break if we change it / remove it without warning.
  this._jdel = j_json;
};

Json._jclass = utils.getJavaClass("io.reactiverse.pgclient.data.Json");
Json._jtype = {accept: function(obj) {
    return Json._jclass.isInstance(obj._jdel);
  },wrap: function(jdel) {
    var obj = Object.create(Json.prototype, {});
    Json.apply(obj, arguments);
    return obj;
  },
  unwrap: function(obj) {
    return obj._jdel;
  }
};
Json._create = function(jdel) {var obj = Object.create(Json.prototype, {});
  Json.apply(obj, arguments);
  return obj;
}
/**

 @memberof module:reactive-pg-client-js/json
 @param value {Object} 
 @return {Json}
 */
Json.create =  function(value) {
  var __args = arguments;
  if (__args.length === 1 && typeof __args[0] !== 'function') {
    return utils.convReturnVertxGen(Json, JJson["create(java.lang.Object)"](utils.convParamTypeUnknown(__args[0]))) ;
  }else throw new TypeError('function invoked with invalid arguments');
};

module.exports = Json;

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:18 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_json-Json.html ================================================ JSDoc: Class: Json

Class: Json

reactive-pg-client-js/json~ Json


Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:18 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_json.html ================================================ JSDoc: Module: reactive-pg-client-js/json

Module: reactive-pg-client-js/json

Classes

Json

Methods

(static) Json.create(value) → {Json}

Parameters:
Name Type Description
value Object
Source:
Returns:
Type
Json

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:18 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_pg_channel-PgChannel.html ================================================ JSDoc: Class: PgChannel

Class: PgChannel

reactive-pg-client-js/pg_channel~ PgChannel

new PgChannel()

Source:

Methods

endHandler(endHandler) → {PgChannel}

Set an handler to be called when no more notifications will be received.
Parameters:
Name Type Description
endHandler function the handler
Source:
Returns:
a reference to this, so the API can be used fluently
Type
PgChannel

exceptionHandler(handler) → {PgChannel}

Parameters:
Name Type Description
handler function
Source:
Returns:
Type
PgChannel

fetch(arg0) → {ReadStream}

Parameters:
Name Type Description
arg0 number
Source:
Returns:
Type
ReadStream

handler(handler) → {PgChannel}

Set or unset an handler to be called when a the channel is notified by Postgres.

  • when the handler is set, the subscriber sends a LISTEN command if needed
  • when the handler is unset, the subscriber sends a UNLISTEN command if needed
Parameters:
Name Type Description
handler function the handler
Source:
Returns:
a reference to this, so the API can be used fluently
Type
PgChannel

pause() → {PgChannel}

Pause the channel, all notifications are discarded.
Source:
Returns:
a reference to this, so the API can be used fluently
Type
PgChannel

resume() → {PgChannel}

Resume the channel.
Source:
Returns:
a reference to this, so the API can be used fluently
Type
PgChannel

subscribeHandler(handler) → {PgChannel}

Set an handler called when the the channel get subscribed.
Parameters:
Name Type Description
handler function the handler
Source:
Returns:
a reference to this, so the API can be used fluently
Type
PgChannel

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:18 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_pg_channel.html ================================================ JSDoc: Module: reactive-pg-client-js/pg_channel

Module: reactive-pg-client-js/pg_channel


Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:18 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_pg_client-PgClient.html ================================================ JSDoc: Class: PgClient

Class: PgClient

reactive-pg-client-js/pg_client~ PgClient

new PgClient()

Defines the client operations with a Postgres Database.
Source:

Methods

preparedBatch(sql, batch, handler) → {PgClient}

Prepare and execute a createBatch.
Parameters:
Name Type Description
sql string the prepared query SQL
batch Array.<Tuple> the batch of tuples
handler function the handler notified with the execution result
Source:
Returns:
a reference to this, so the API can be used fluently
Type
PgClient

preparedQuery(sql, arguments, handler) → {PgClient}

Prepare and execute a query.
Parameters:
Name Type Description
sql string the prepared query SQL
arguments Tuple the list of arguments
handler function the handler notified with the execution result
Source:
Returns:
a reference to this, so the API can be used fluently
Type
PgClient

query(sql, handler) → {PgClient}

Execute a simple query.
Parameters:
Name Type Description
sql string the query SQL
handler function the handler notified with the execution result
Source:
Returns:
a reference to this, so the API can be used fluently
Type
PgClient

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:18 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_pg_client.html ================================================ JSDoc: Module: reactive-pg-client-js/pg_client

Module: reactive-pg-client-js/pg_client

Classes

PgClient

Methods

(static) PgClient.connect(vertx, connectionUri, handler)

Like PgClient#connect with options build from connectionUri.
Parameters:
Name Type Description
vertx Vertx
connectionUri string
handler function
Source:

(static) PgClient.pool(vertx, options) → {PgPool}

Like PgClient#pool with a specific instance.
Parameters:
Name Type Description
vertx Vertx
options Object
Source:
Returns:
Type
PgPool

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:18 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_pg_connection-PgConnection.html ================================================ JSDoc: Class: PgConnection

Class: PgConnection

reactive-pg-client-js/pg_connection~ PgConnection

new PgConnection()

A connection to Postgres.
Source:

Methods

begin() → {PgTransaction}

Begin a transaction and returns a PgTransaction for controlling and tracking this transaction.

When the connection is explicitely closed, any inflight transaction is rollbacked.

Source:
Returns:
the transaction instance
Type
PgTransaction

cancelRequest(handler) → {PgConnection}

Send a request cancellation message to tell the server to cancel processing request in this connection.
Note: Use this with caution because the cancellation signal may or may not have any effect.
Parameters:
Name Type Description
handler function the handler notified if cancelling request is sent
Source:
Returns:
a reference to this, so the API can be used fluently
Type
PgConnection

close()

Close the current connection after all the pending commands have been processed.
Source:

closeHandler(handler) → {PgConnection}

Set an handler called when the connection is closed.
Parameters:
Name Type Description
handler function the handler
Source:
Returns:
a reference to this, so the API can be used fluently
Type
PgConnection

exceptionHandler(handler) → {PgConnection}

Set an handler called with connection errors.
Parameters:
Name Type Description
handler function the handler
Source:
Returns:
a reference to this, so the API can be used fluently
Type
PgConnection

isSSL() → {boolean}

Source:
Returns:
whether the connection uses SSL
Type
boolean

notificationHandler(handler) → {PgConnection}

Set an handler called when the connection receives notification on a channel.

The handler is called with the PgNotification and has access to the channel name and the notification payload.

Parameters:
Name Type Description
handler function the handler
Source:
Returns:
the transaction instance
Type
PgConnection

prepare(sql, handler) → {PgConnection}

Create a prepared query.
Parameters:
Name Type Description
sql string the sql
handler function the handler notified with the prepared query asynchronously
Source:
Returns:
Type
PgConnection

preparedBatch(sql, batch, handler) → {PgConnection}

Parameters:
Name Type Description
sql string
batch Array.<Tuple>
handler function
Source:
Returns:
Type
PgConnection

preparedQuery(sql, arguments, handler) → {PgConnection}

Parameters:
Name Type Description
sql string
arguments Tuple
handler function
Source:
Returns:
Type
PgConnection

processId() → {number}

Source:
Returns:
The process ID of the target backend
Type
number

query(sql, handler) → {PgConnection}

Parameters:
Name Type Description
sql string
handler function
Source:
Returns:
Type
PgConnection

secretKey() → {number}

Source:
Returns:
The secret key for the target backend
Type
number

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:19 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_pg_connection.html ================================================ JSDoc: Module: reactive-pg-client-js/pg_connection

Module: reactive-pg-client-js/pg_connection


Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:19 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_pg_cursor-PgCursor.html ================================================ JSDoc: Class: PgCursor

Class: PgCursor

reactive-pg-client-js/pg_cursor~ PgCursor

new PgCursor()

A cursor that reads progressively the rows from Postgres, it is usefull for reading very large result.
Source:

Methods

close(completionHandler)

Like PgCursor#close but with a completionHandler called when the cursor has been released.
Parameters:
Name Type Description
completionHandler function
Source:

hasMore() → {boolean}

Returns true when the cursor has results in progress and the should be called to retrieve them.
Source:
Returns:
whether the cursor has more results,
Type
boolean

read(count, handler)

Read rows from the cursor, the result is provided asynchronously to the handler.
Parameters:
Name Type Description
count number the amount of rows to read
handler function the handler for the result
Source:

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:19 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_pg_cursor.html ================================================ JSDoc: Module: reactive-pg-client-js/pg_cursor

Module: reactive-pg-client-js/pg_cursor


Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:19 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_pg_iterator-PgIterator.html ================================================ JSDoc: Class: PgIterator

Class: PgIterator

reactive-pg-client-js/pg_iterator~ PgIterator


Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:19 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_pg_iterator.html ================================================ JSDoc: Module: reactive-pg-client-js/pg_iterator

Module: reactive-pg-client-js/pg_iterator


Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:19 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_pg_pool-PgPool.html ================================================ JSDoc: Class: PgPool

Class: PgPool

reactive-pg-client-js/pg_pool~ PgPool

new PgPool()

A pool of connection.
Source:

Methods

begin(handler)

Borrow a connection from the pool and begin a transaction, the underlying connection will be returned to the pool when the transaction ends.
Parameters:
Name Type Description
handler function
Source:

close()

Close the pool and release the associated resources.
Source:

getConnection(handler)

Get a connection from the pool.
Parameters:
Name Type Description
handler function the handler that will get the connection result
Source:

preparedBatch(sql, batch, handler) → {PgPool}

Parameters:
Name Type Description
sql string
batch Array.<Tuple>
handler function
Source:
Returns:
Type
PgPool

preparedQuery(sql, arguments, handler) → {PgPool}

Parameters:
Name Type Description
sql string
arguments Tuple
handler function
Source:
Returns:
Type
PgPool

query(sql, handler) → {PgPool}

Parameters:
Name Type Description
sql string
handler function
Source:
Returns:
Type
PgPool

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:19 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_pg_pool.html ================================================ JSDoc: Module: reactive-pg-client-js/pg_pool

Module: reactive-pg-client-js/pg_pool


Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:19 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_pg_prepared_query-PgPreparedQuery.html ================================================ JSDoc: Class: PgPreparedQuery

Class: PgPreparedQuery

reactive-pg-client-js/pg_prepared_query~ PgPreparedQuery

new PgPreparedQuery()

A prepared query.
Source:

Methods

batch(argsList, handler) → {PgPreparedQuery}

Execute a batch.
Parameters:
Name Type Description
argsList Array.<Tuple> the list of tuple for the batch
handler function
Source:
Returns:
the createBatch
Type
PgPreparedQuery

close(completionHandler)

Like PgPreparedQuery#close but notifies the completionHandler when it's closed.
Parameters:
Name Type Description
completionHandler function
Source:

createStream(fetch, args) → {PgStream}

Execute the prepared query with a cursor and createStream the result. The createStream opens a cursor with a fetch size to fetch the results.

Note: this requires to be in a transaction, since cursors require it.

Parameters:
Name Type Description
fetch number the cursor fetch size
args Tuple the prepared query arguments
Source:
Returns:
the createStream
Type
PgStream

cursor(args) → {PgCursor}

Create a cursor with the provided arguments.
Parameters:
Name Type Description
args Tuple the list of arguments
Source:
Returns:
the query
Type
PgCursor

execute(args, handler) → {PgPreparedQuery}

Create a cursor with the provided arguments.
Parameters:
Name Type Description
args Tuple the list of arguments
handler function
Source:
Returns:
the query
Type
PgPreparedQuery

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:19 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_pg_prepared_query.html ================================================ JSDoc: Module: reactive-pg-client-js/pg_prepared_query

Module: reactive-pg-client-js/pg_prepared_query


Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:19 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_pg_result-PgResult.html ================================================ JSDoc: Class: PgResult

Class: PgResult

reactive-pg-client-js/pg_result~ PgResult

new PgResult()

Represents the result of an operation on database.
Source:

Methods

columnsNames() → {Array.<string>}

Get the names of columns in the PgResult.
Source:
Returns:
the list of names of columns.
Type
Array.<string>

next() → {PgResult}

Return the next available result or null, e.g for a simple query that executed multiple queries or for a batch result.
Source:
Returns:
the next available result or null if none is available
Type
PgResult

rowCount() → {number}

Get the number of the affected rows in the operation to this PgResult.

The meaning depends on the executed statement:

  • INSERT: the number of rows inserted
  • DELETE: the number of rows deleted
  • UPDATE: the number of rows updated
  • SELECT: the number of rows retrieved
Source:
Returns:
the count of affected rows.
Type
number

size() → {number}

Get the number of rows in the PgResult.
Source:
Returns:
the count of rows.
Type
number

value() → {Object}

Get the result value.
Source:
Returns:
the result
Type
Object

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:19 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_pg_result.html ================================================ JSDoc: Module: reactive-pg-client-js/pg_result

Module: reactive-pg-client-js/pg_result


Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:19 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_pg_row_set-PgRowSet.html ================================================ JSDoc: Class: PgRowSet

Class: PgRowSet

reactive-pg-client-js/pg_row_set~ PgRowSet


Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:19 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_pg_row_set.html ================================================ JSDoc: Module: reactive-pg-client-js/pg_row_set

Module: reactive-pg-client-js/pg_row_set


Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:19 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_pg_stream-PgStream.html ================================================ JSDoc: Class: PgStream

Class: PgStream

reactive-pg-client-js/pg_stream~ PgStream

new PgStream()

A row oriented stream.
Source:

Methods

close(completionHandler)

Close the stream and release the resources.
Parameters:
Name Type Description
completionHandler function the completion handler for this operation
Source:

endHandler(endHandler) → {PgStream}

Parameters:
Name Type Description
endHandler function
Source:
Returns:
Type
PgStream

exceptionHandler(handler) → {PgStream}

Parameters:
Name Type Description
handler function
Source:
Returns:
Type
PgStream

fetch(arg0) → {ReadStream}

Parameters:
Name Type Description
arg0 number
Source:
Returns:
Type
ReadStream

handler(handler) → {PgStream}

Parameters:
Name Type Description
handler function
Source:
Returns:
Type
PgStream

pause() → {PgStream}

Source:
Returns:
Type
PgStream

resume() → {PgStream}

Source:
Returns:
Type
PgStream

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:19 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_pg_stream.html ================================================ JSDoc: Module: reactive-pg-client-js/pg_stream

Module: reactive-pg-client-js/pg_stream


Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:19 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_pg_subscriber-PgSubscriber.html ================================================ JSDoc: Class: PgSubscriber

Class: PgSubscriber

reactive-pg-client-js/pg_subscriber~ PgSubscriber

new PgSubscriber()

Source:

Methods

actualConnection() → {PgConnection}

Source:
Returns:
the actual connection to Postgres, it might be null
Type
PgConnection

channel(name) → {PgChannel}

Return a channel for the given name.
Parameters:
Name Type Description
name string the channel name

This will be the name of the channel exactly as held by Postgres for sending notifications. Internally this name will be truncated to the Postgres identifier maxiumum length of (NAMEDATALEN = 64) - 1 == 63 characters, and prepared as a quoted identifier without unicode escape sequence support for use in LISTEN/UNLISTEN commands. Examples of channel names and corresponding NOTIFY commands:

  • when name == "the_channel": NOTIFY the_channel, 'msg', NOTIFY The_Channel, 'msg', or NOTIFY "the_channel", 'msg' succeed in delivering a message to the created channel
  • when name == "The_Channel": NOTIFY "The_Channel", 'msg', succeeds in delivering a message to the created channel
Source:
Returns:
the channel
Type
PgChannel

close()

Close the subscriber, the retry policy will not be invoked.
Source:

closed() → {boolean}

Source:
Returns:
whether the subscriber is closed
Type
boolean

closeHandler(handler) → {PgSubscriber}

Set an handler called when the subscriber is closed.
Parameters:
Name Type Description
handler function the handler
Source:
Returns:
a reference to this, so the API can be used fluently
Type
PgSubscriber

connect(handler) → {PgSubscriber}

Connect the subscriber to Postgres.
Parameters:
Name Type Description
handler function the handler notified of the connection success or failure
Source:
Returns:
a reference to this, so the API can be used fluently
Type
PgSubscriber

reconnectPolicy(policy) → {PgSubscriber}

Set the reconnect policy that is executed when the subscriber is disconnected.

When the subscriber is disconnected, the policy function is called with the actual number of retries and returns an amountOfTime value:

  • when amountOfTime < 0: the subscriber is closed and there is no retry
  • when amountOfTime == 0: the subscriber retries to connect immediately
  • when amountOfTime > 0: the subscriber retries after amountOfTime milliseconds

The default policy does not perform any retries.

Parameters:
Name Type Description
policy function the policy to set
Source:
Returns:
a reference to this, so the API can be used fluently
Type
PgSubscriber

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:19 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_pg_subscriber.html ================================================ JSDoc: Module: reactive-pg-client-js/pg_subscriber

Module: reactive-pg-client-js/pg_subscriber

Classes

PgSubscriber

Methods

(static) PgSubscriber.subscriber(vertx, options) → {PgSubscriber}

Create a subscriber.
Parameters:
Name Type Description
vertx Vertx the vertx instance
options Object the connect options
Source:
Returns:
the subscriber
Type
PgSubscriber

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:19 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_pg_transaction-PgTransaction.html ================================================ JSDoc: Class: PgTransaction

Class: PgTransaction

reactive-pg-client-js/pg_transaction~ PgTransaction

new PgTransaction()

A transaction that allows to control the transaction and receive events.
Source:

Methods

abortHandler(handler) → {PgTransaction}

Set an handler to be called when the transaction is aborted.
Parameters:
Name Type Description
handler function the handler
Source:
Returns:
Type
PgTransaction

commit(handler)

Like PgTransaction#commit with an handler to be notified when the transaction commit has completed
Parameters:
Name Type Description
handler function
Source:

prepare(sql, handler) → {PgTransaction}

Create a prepared query.
Parameters:
Name Type Description
sql string the sql
handler function the handler notified with the prepared query asynchronously
Source:
Returns:
Type
PgTransaction

preparedBatch(sql, batch, handler) → {PgTransaction}

Parameters:
Name Type Description
sql string
batch Array.<Tuple>
handler function
Source:
Returns:
Type
PgTransaction

preparedQuery(sql, arguments, handler) → {PgTransaction}

Parameters:
Name Type Description
sql string
arguments Tuple
handler function
Source:
Returns:
Type
PgTransaction

query(sql, handler) → {PgTransaction}

Parameters:
Name Type Description
sql string
handler function
Source:
Returns:
Type
PgTransaction

rollback(handler)

Like PgTransaction#rollback with an handler to be notified when the transaction rollback has completed
Parameters:
Name Type Description
handler function
Source:

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:19 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_pg_transaction.html ================================================ JSDoc: Module: reactive-pg-client-js/pg_transaction

Module: reactive-pg-client-js/pg_transaction


Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:19 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_row-Row.html ================================================ JSDoc: Class: Row

Class: Row

reactive-pg-client-js/row~ Row

new Row()

Source:

Methods

getBoolean(name) → {boolean}

Get a boolean value at pos.
Parameters:
Name Type Description
name string the column
Source:
Returns:
the value or null
Type
boolean

getBox(name) → {Object}

Get value at pos.
Parameters:
Name Type Description
name string the column
Source:
Returns:
the value or null
Type
Object

getBuffer(name) → {Buffer}

Get a buffer value at pos.
Parameters:
Name Type Description
name string the column
Source:
Returns:
the value or null
Type
Buffer

getCircle(name) → {Object}

Get value at pos.
Parameters:
Name Type Description
name string the column
Source:
Returns:
the value or null
Type
Object

getColumnName(pos) → {string}

Get a column name at pos.
Parameters:
Name Type Description
pos number the position
Source:
Returns:
the column name or null
Type
string

getDouble(name) → {number}

Get a double value at pos.
Parameters:
Name Type Description
name string the column
Source:
Returns:
the value or null
Type
number

getFloat(name) → {number}

Get a float value at pos.
Parameters:
Name Type Description
name string the column
Source:
Returns:
the value or null
Type
number

getInteger(name) → {number}

Get an integer value at pos.
Parameters:
Name Type Description
name string the column
Source:
Returns:
the value or null
Type
number

getInterval(name) → {Object}

Get value at pos.
Parameters:
Name Type Description
name string the column
Source:
Returns:
the value or null
Type
Object

getJson(name) → {Json}

Get a json value at pos.
Parameters:
Name Type Description
name string the column
Source:
Returns:
the value or null
Type
Json

getLine(name) → {Object}

Get value at pos.
Parameters:
Name Type Description
name string the column
Source:
Returns:
the value or null
Type
Object

getLineSegment(name) → {Object}

Get value at pos.
Parameters:
Name Type Description
name string the column
Source:
Returns:
the value or null
Type
Object

getLong(name) → {number}

Get a long value at pos.
Parameters:
Name Type Description
name string the column
Source:
Returns:
the value or null
Type
number

getPath(name) → {Object}

Get value at pos.
Parameters:
Name Type Description
name string the column
Source:
Returns:
the value or null
Type
Object

getPoint(name) → {Object}

Get value at pos.
Parameters:
Name Type Description
name string the column
Source:
Returns:
the value or null
Type
Object

getPolygon(name) → {Object}

Get value at pos.
Parameters:
Name Type Description
name string the column
Source:
Returns:
the value or null
Type
Object

getShort(name) → {number}

Get a short value at pos.
Parameters:
Name Type Description
name string the column
Source:
Returns:
the value or null
Type
number

getString(name) → {string}

Get a string value at pos.
Parameters:
Name Type Description
name string the column
Source:
Returns:
the value or null
Type
string

getValue(name) → {Object}

Get an object value at pos.
Parameters:
Name Type Description
name string the column
Source:
Returns:
the value or null
Type
Object

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:19 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_row.html ================================================ JSDoc: Module: reactive-pg-client-js/row

Module: reactive-pg-client-js/row


Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:19 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_tuple-Tuple.html ================================================ JSDoc: Class: Tuple

Class: Tuple

reactive-pg-client-js/tuple~ Tuple

new Tuple()

A general purpose tuple.
Source:

Methods

addBoolean(value) → {Tuple}

Add a boolean value at the end of the tuple.
Parameters:
Name Type Description
value boolean the value
Source:
Returns:
a reference to this, so the API can be used fluently
Type
Tuple

addBox(value) → {Tuple}

Add a value at the end of the tuple.
Parameters:
Name Type Description
value Object the value
Source:
Returns:
a reference to this, so the API can be used fluently
Type
Tuple

addBuffer(value) → {Tuple}

Add a buffer value at the end of the tuple.
Parameters:
Name Type Description
value Buffer the value
Source:
Returns:
a reference to this, so the API can be used fluently
Type
Tuple

addCircle(value) → {Tuple}

Add a value at the end of the tuple.
Parameters:
Name Type Description
value Object the value
Source:
Returns:
a reference to this, so the API can be used fluently
Type
Tuple

addDouble(value) → {Tuple}

Add a double value at the end of the tuple.
Parameters:
Name Type Description
value number the value
Source:
Returns:
a reference to this, so the API can be used fluently
Type
Tuple

addFloat(value) → {Tuple}

Add a float value at the end of the tuple.
Parameters:
Name Type Description
value number the value
Source:
Returns:
a reference to this, so the API can be used fluently
Type
Tuple

addInteger(value) → {Tuple}

Add an integer value at the end of the tuple.
Parameters:
Name Type Description
value number the value
Source:
Returns:
a reference to this, so the API can be used fluently
Type
Tuple

addInterval(value) → {Tuple}

Add a value at the end of the tuple.
Parameters:
Name Type Description
value Object the value
Source:
Returns:
a reference to this, so the API can be used fluently
Type
Tuple

addJson(value) → {Tuple}

Add a json value at the end of the tuple.
Parameters:
Name Type Description
value Json the value
Source:
Returns:
a reference to this, so the API can be used fluently
Type
Tuple

addLine(value) → {Tuple}

Add a value at the end of the tuple.
Parameters:
Name Type Description
value Object the value
Source:
Returns:
a reference to this, so the API can be used fluently
Type
Tuple

addLineSegment(value) → {Tuple}

Add a value at the end of the tuple.
Parameters:
Name Type Description
value Object the value
Source:
Returns:
a reference to this, so the API can be used fluently
Type
Tuple

addLong(value) → {Tuple}

Add a long value at the end of the tuple.
Parameters:
Name Type Description
value number the value
Source:
Returns:
a reference to this, so the API can be used fluently
Type
Tuple

addPath(value) → {Tuple}

Add a value at the end of the tuple.
Parameters:
Name Type Description
value Object the value
Source:
Returns:
a reference to this, so the API can be used fluently
Type
Tuple

addPoint(value) → {Tuple}

Add a value at the end of the tuple.
Parameters:
Name Type Description
value Object the value
Source:
Returns:
a reference to this, so the API can be used fluently
Type
Tuple

addPolygon(value) → {Tuple}

Add a value at the end of the tuple.
Parameters:
Name Type Description
value Object the value
Source:
Returns:
a reference to this, so the API can be used fluently
Type
Tuple

addShort(value) → {Tuple}

Add a short value at the end of the tuple.
Parameters:
Name Type Description
value number the value
Source:
Returns:
a reference to this, so the API can be used fluently
Type
Tuple

addString(value) → {Tuple}

Add a string value at the end of the tuple.
Parameters:
Name Type Description
value string the value
Source:
Returns:
a reference to this, so the API can be used fluently
Type
Tuple

addValue(value) → {Tuple}

Add an object value at the end of the tuple.
Parameters:
Name Type Description
value Object the value
Source:
Returns:
a reference to this, so the API can be used fluently
Type
Tuple

clear()

Source:

getBoolean(pos) → {boolean}

Get a boolean value at pos.
Parameters:
Name Type Description
pos number the position
Source:
Returns:
the value or null
Type
boolean

getBox(pos) → {Object}

Get value at pos.
Parameters:
Name Type Description
pos number the position
Source:
Returns:
the value or null
Type
Object

getBuffer(pos) → {Buffer}

Get a buffer value at pos.
Parameters:
Name Type Description
pos number the position
Source:
Returns:
the value or null
Type
Buffer

getCircle(pos) → {Object}

Get value at pos.
Parameters:
Name Type Description
pos number the position
Source:
Returns:
the value or null
Type
Object

getDouble(pos) → {number}

Get a double value at pos.
Parameters:
Name Type Description
pos number the position
Source:
Returns:
the value or null
Type
number

getFloat(pos) → {number}

Get a float value at pos.
Parameters:
Name Type Description
pos number the position
Source:
Returns:
the value or null
Type
number

getInteger(pos) → {number}

Get an integer value at pos.
Parameters:
Name Type Description
pos number the position
Source:
Returns:
the value or null
Type
number

getInterval(pos) → {Object}

Get value at pos.
Parameters:
Name Type Description
pos number the position
Source:
Returns:
the value or null
Type
Object

getJson(pos) → {Json}

Get a json value at pos.
Parameters:
Name Type Description
pos number the position
Source:
Returns:
the value or null
Type
Json

getLine(pos) → {Object}

Get value at pos.
Parameters:
Name Type Description
pos number the position
Source:
Returns:
the value or null
Type
Object

getLineSegment(pos) → {Object}

Get value at pos.
Parameters:
Name Type Description
pos number the position
Source:
Returns:
the value or null
Type
Object

getLong(pos) → {number}

Get a long value at pos.
Parameters:
Name Type Description
pos number the position
Source:
Returns:
the value or null
Type
number

getPath(pos) → {Object}

Get value at pos.
Parameters:
Name Type Description
pos number the position
Source:
Returns:
the value or null
Type
Object

getPoint(pos) → {Object}

Get value at pos.
Parameters:
Name Type Description
pos number the position
Source:
Returns:
the value or null
Type
Object

getPolygon(pos) → {Object}

Get value at pos.
Parameters:
Name Type Description
pos number the position
Source:
Returns:
the value or null
Type
Object

getShort(pos) → {number}

Get a short value at pos.
Parameters:
Name Type Description
pos number the position
Source:
Returns:
the value or null
Type
number

getString(pos) → {string}

Get a string value at pos.
Parameters:
Name Type Description
pos number the position
Source:
Returns:
the value or null
Type
string

getValue(pos) → {Object}

Get an object value at pos.
Parameters:
Name Type Description
pos number the position
Source:
Returns:
the value or null
Type
Object

size() → {number}

Source:
Returns:
the tuple size
Type
number

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:19 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/module-reactive-pg-client-js_tuple.html ================================================ JSDoc: Module: reactive-pg-client-js/tuple

Module: reactive-pg-client-js/tuple

Classes

Tuple

Methods

(static) Tuple.of(elt1, elt2, elt3, elt4, elt5, elt6) → {Tuple}

Create a tuple of six elements.
Parameters:
Name Type Description
elt1 Object the first value
elt2 Object the second valueg
elt3 Object the third value
elt4 Object the fourth value
elt5 Object the fifth value
elt6 Object the sixth value
Source:
Returns:
the tuple
Type
Tuple

(static) Tuple.tuple() → {Tuple}

Source:
Returns:
a new empty tuple
Type
Tuple

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:19 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/pg_channel.js.html ================================================ JSDoc: Source: pg_channel.js

Source: pg_channel.js

/*
 * Copyright 2014 Red Hat, Inc.
 *
 * Red Hat 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.
 */

/** @module reactive-pg-client-js/pg_channel */
var utils = require('vertx-js/util/utils');
var ReadStream = require('vertx-js/read_stream');

var io = Packages.io;
var JsonObject = io.vertx.core.json.JsonObject;
var JPgChannel = Java.type('io.reactiverse.pgclient.pubsub.PgChannel');

/**

 @class
*/
var PgChannel = function(j_val) {

  var j_pgChannel = j_val;
  var that = this;
  ReadStream.call(this, j_val);

  var __super_fetch = this.fetch;
  var __super_subscribeHandler = this.subscribeHandler;
  var __super_handler = this.handler;
  var __super_pause = this.pause;
  var __super_resume = this.resume;
  var __super_endHandler = this.endHandler;
  var __super_exceptionHandler = this.exceptionHandler;
  /**

   @public
   @param arg0 {number} 
   @return {ReadStream}
   */
  this.fetch =  function(arg0) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      j_pgChannel["fetch(long)"](__args[0]) ;
      return that;
    } else if (typeof __super_fetch != 'undefined') {
      return __super_fetch.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Set an handler called when the the channel get subscribed.

   @public
   @param handler {function} the handler 
   @return {PgChannel} a reference to this, so the API can be used fluently
   */
  this.subscribeHandler =  function(handler) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'function') {
      j_pgChannel["subscribeHandler(io.vertx.core.Handler)"](__args[0]) ;
      return that;
    } else if (typeof __super_subscribeHandler != 'undefined') {
      return __super_subscribeHandler.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Set or unset an handler to be called when a the channel is notified by Postgres.
   <p/>
   <ul>
     <li>when the handler is set, the subscriber sends a <code>LISTEN</code> command if needed</li>
     <li>when the handler is unset, the subscriber sends a <code>UNLISTEN</code> command if needed</li>
   </ul>

   @public
   @param handler {function} the handler 
   @return {PgChannel} a reference to this, so the API can be used fluently
   */
  this.handler =  function(handler) {
    var __args = arguments;
    if (__args.length === 1 && (typeof __args[0] === 'function' || __args[0] == null)) {
      j_pgChannel["handler(io.vertx.core.Handler)"](__args[0] == null ? null : function(jVal) {
        __args[0](jVal);
      }) ;
      return that;
    } else if (typeof __super_handler != 'undefined') {
      return __super_handler.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Pause the channel, all notifications are discarded.

   @public

   @return {PgChannel} a reference to this, so the API can be used fluently
   */
  this.pause =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      j_pgChannel["pause()"]() ;
      return that;
    } else if (typeof __super_pause != 'undefined') {
      return __super_pause.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Resume the channel.

   @public

   @return {PgChannel} a reference to this, so the API can be used fluently
   */
  this.resume =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      j_pgChannel["resume()"]() ;
      return that;
    } else if (typeof __super_resume != 'undefined') {
      return __super_resume.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Set an handler to be called when no more notifications will be received.

   @public
   @param endHandler {function} the handler 
   @return {PgChannel} a reference to this, so the API can be used fluently
   */
  this.endHandler =  function(endHandler) {
    var __args = arguments;
    if (__args.length === 1 && (typeof __args[0] === 'function' || __args[0] == null)) {
      j_pgChannel["endHandler(io.vertx.core.Handler)"](__args[0]) ;
      return that;
    } else if (typeof __super_endHandler != 'undefined') {
      return __super_endHandler.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**

   @public
   @param handler {function} 
   @return {PgChannel}
   */
  this.exceptionHandler =  function(handler) {
    var __args = arguments;
    if (__args.length === 1 && (typeof __args[0] === 'function' || __args[0] == null)) {
      j_pgChannel["exceptionHandler(io.vertx.core.Handler)"](__args[0] == null ? null : function(jVal) {
        __args[0](utils.convReturnThrowable(jVal));
      }) ;
      return that;
    } else if (typeof __super_exceptionHandler != 'undefined') {
      return __super_exceptionHandler.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  // A reference to the underlying Java delegate
  // NOTE! This is an internal API and must not be used in user code.
  // If you rely on this property your code is likely to break if we change it / remove it without warning.
  this._jdel = j_pgChannel;
};

PgChannel._jclass = utils.getJavaClass("io.reactiverse.pgclient.pubsub.PgChannel");
PgChannel._jtype = {accept: function(obj) {
    return PgChannel._jclass.isInstance(obj._jdel);
  },wrap: function(jdel) {
    var obj = Object.create(PgChannel.prototype, {});
    PgChannel.apply(obj, arguments);
    return obj;
  },
  unwrap: function(obj) {
    return obj._jdel;
  }
};
PgChannel._create = function(jdel) {var obj = Object.create(PgChannel.prototype, {});
  PgChannel.apply(obj, arguments);
  return obj;
}
module.exports = PgChannel;

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:18 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/pg_client.js.html ================================================ JSDoc: Source: pg_client.js

Source: pg_client.js

/*
 * Copyright 2014 Red Hat, Inc.
 *
 * Red Hat 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.
 */

/** @module reactive-pg-client-js/pg_client */
var utils = require('vertx-js/util/utils');
var PgPool = require('reactive-pg-client-js/pg_pool');
var Vertx = require('vertx-js/vertx');
var Tuple = require('reactive-pg-client-js/tuple');
var PgConnection = require('reactive-pg-client-js/pg_connection');
var PgRowSet = require('reactive-pg-client-js/pg_row_set');

var io = Packages.io;
var JsonObject = io.vertx.core.json.JsonObject;
var JPgClient = Java.type('io.reactiverse.pgclient.PgClient');
var PgConnectOptions = Java.type('io.reactiverse.pgclient.PgConnectOptions');
var PgPoolOptions = Java.type('io.reactiverse.pgclient.PgPoolOptions');

/**
 Defines the client operations with a Postgres Database.

 @class
*/
var PgClient = function(j_val) {

  var j_pgClient = j_val;
  var that = this;

  var __super_pool = this.pool;
  var __super_pool = this.pool;
  var __super_pool = this.pool;
  var __super_pool = this.pool;
  var __super_pool = this.pool;
  var __super_pool = this.pool;
  var __super_connect = this.connect;
  var __super_connect = this.connect;
  var __super_connect = this.connect;
  var __super_query = this.query;
  var __super_preparedQuery = this.preparedQuery;
  var __super_preparedQuery = this.preparedQuery;
  var __super_preparedBatch = this.preparedBatch;
  /**
   Execute a simple query.

   @public
   @param sql {string} the query SQL 
   @param handler {function} the handler notified with the execution result 
   @return {PgClient} a reference to this, so the API can be used fluently
   */
  this.query =  function(sql, handler) {
    var __args = arguments;
    if (__args.length === 2 && typeof __args[0] === 'string' && typeof __args[1] === 'function') {
      j_pgClient["query(java.lang.String,io.vertx.core.Handler)"](__args[0], function(ar) {
        if (ar.succeeded()) {
          __args[1](utils.convReturnVertxGen(PgRowSet, ar.result()), null);
        } else {
          __args[1](null, ar.cause());
        }
      }) ;
      return that;
    } else if (typeof __super_query != 'undefined') {
      return __super_query.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Prepare and execute a query.

   @public
   @param sql {string} the prepared query SQL 
   @param arguments {Tuple} the list of arguments 
   @param handler {function} the handler notified with the execution result 
   @return {PgClient} a reference to this, so the API can be used fluently
   */
  this.preparedQuery =  function() {
    var __args = arguments;
    if (__args.length === 2 && typeof __args[0] === 'string' && typeof __args[1] === 'function') {
      j_pgClient["preparedQuery(java.lang.String,io.vertx.core.Handler)"](__args[0], function(ar) {
        if (ar.succeeded()) {
          __args[1](utils.convReturnVertxGen(PgRowSet, ar.result()), null);
        } else {
          __args[1](null, ar.cause());
        }
      }) ;
      return that;
    } else if (__args.length === 3 && typeof __args[0] === 'string' && typeof __args[1] === 'object' && __args[1]._jdel && typeof __args[2] === 'function') {
      j_pgClient["preparedQuery(java.lang.String,io.reactiverse.pgclient.Tuple,io.vertx.core.Handler)"](__args[0], __args[1]._jdel, function(ar) {
        if (ar.succeeded()) {
          __args[2](utils.convReturnVertxGen(PgRowSet, ar.result()), null);
        } else {
          __args[2](null, ar.cause());
        }
      }) ;
      return that;
    } else if (typeof __super_preparedQuery != 'undefined') {
      return __super_preparedQuery.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Prepare and execute a createBatch.

   @public
   @param sql {string} the prepared query SQL 
   @param batch {Array.<Tuple>} the batch of tuples 
   @param handler {function} the handler notified with the execution result 
   @return {PgClient} a reference to this, so the API can be used fluently
   */
  this.preparedBatch =  function(sql, batch, handler) {
    var __args = arguments;
    if (__args.length === 3 && typeof __args[0] === 'string' && typeof __args[1] === 'object' && __args[1] instanceof Array && typeof __args[2] === 'function') {
      j_pgClient["preparedBatch(java.lang.String,java.util.List,io.vertx.core.Handler)"](__args[0], utils.convParamListVertxGen(__args[1]), function(ar) {
        if (ar.succeeded()) {
          __args[2](utils.convReturnVertxGen(PgRowSet, ar.result()), null);
        } else {
          __args[2](null, ar.cause());
        }
      }) ;
      return that;
    } else if (typeof __super_preparedBatch != 'undefined') {
      return __super_preparedBatch.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  // A reference to the underlying Java delegate
  // NOTE! This is an internal API and must not be used in user code.
  // If you rely on this property your code is likely to break if we change it / remove it without warning.
  this._jdel = j_pgClient;
};

PgClient._jclass = utils.getJavaClass("io.reactiverse.pgclient.PgClient");
PgClient._jtype = {accept: function(obj) {
    return PgClient._jclass.isInstance(obj._jdel);
  },wrap: function(jdel) {
    var obj = Object.create(PgClient.prototype, {});
    PgClient.apply(obj, arguments);
    return obj;
  },
  unwrap: function(obj) {
    return obj._jdel;
  }
};
PgClient._create = function(jdel) {var obj = Object.create(PgClient.prototype, {});
  PgClient.apply(obj, arguments);
  return obj;
}
/**
 Like {@link PgClient#pool} with a specific  instance.

 @memberof module:reactive-pg-client-js/pg_client
 @param vertx {Vertx} 
 @param options {Object} 
 @return {PgPool}
 */
PgClient.pool =  function() {
  var __args = arguments;
  if (__args.length === 0) {
    return utils.convReturnVertxGen(PgPool, JPgClient["pool()"]()) ;
  } else if (__args.length === 1 && typeof __args[0] === 'string') {
    return utils.convReturnVertxGen(PgPool, JPgClient["pool(java.lang.String)"](__args[0])) ;
  } else if (__args.length === 1 && typeof __args[0] === 'object' && __args[0]._jdel) {
    return utils.convReturnVertxGen(PgPool, JPgClient["pool(io.vertx.core.Vertx)"](__args[0]._jdel)) ;
  } else if (__args.length === 2 && typeof __args[0] === 'object' && __args[0]._jdel && typeof __args[1] === 'string') {
    return utils.convReturnVertxGen(PgPool, JPgClient["pool(io.vertx.core.Vertx,java.lang.String)"](__args[0]._jdel, __args[1])) ;
  } else if (__args.length === 1 && (typeof __args[0] === 'object' && __args[0] != null)) {
    return utils.convReturnVertxGen(PgPool, JPgClient["pool(io.reactiverse.pgclient.PgPoolOptions)"](__args[0]  != null ? new PgPoolOptions(new JsonObject(Java.asJSONCompatible(__args[0]))) : null)) ;
  } else if (__args.length === 2 && typeof __args[0] === 'object' && __args[0]._jdel && (typeof __args[1] === 'object' && __args[1] != null)) {
    return utils.convReturnVertxGen(PgPool, JPgClient["pool(io.vertx.core.Vertx,io.reactiverse.pgclient.PgPoolOptions)"](__args[0]._jdel, __args[1]  != null ? new PgPoolOptions(new JsonObject(Java.asJSONCompatible(__args[1]))) : null)) ;
  }else throw new TypeError('function invoked with invalid arguments');
};

/**
 Like {@link PgClient#connect} with options build from <code>connectionUri</code>.

 @memberof module:reactive-pg-client-js/pg_client
 @param vertx {Vertx} 
 @param connectionUri {string} 
 @param handler {function} 
 */
PgClient.connect =  function() {
  var __args = arguments;
  if (__args.length === 3 && typeof __args[0] === 'object' && __args[0]._jdel && (typeof __args[1] === 'object' && __args[1] != null) && typeof __args[2] === 'function') {
    JPgClient["connect(io.vertx.core.Vertx,io.reactiverse.pgclient.PgConnectOptions,io.vertx.core.Handler)"](__args[0]._jdel, __args[1]  != null ? new PgConnectOptions(new JsonObject(Java.asJSONCompatible(__args[1]))) : null, function(ar) {
      if (ar.succeeded()) {
        __args[2](utils.convReturnVertxGen(PgConnection, ar.result()), null);
      } else {
        __args[2](null, ar.cause());
      }
    });
  } else if (__args.length === 2 && typeof __args[0] === 'object' && __args[0]._jdel && typeof __args[1] === 'function') {
    JPgClient["connect(io.vertx.core.Vertx,io.vertx.core.Handler)"](__args[0]._jdel, function(ar) {
      if (ar.succeeded()) {
        __args[1](utils.convReturnVertxGen(PgConnection, ar.result()), null);
      } else {
        __args[1](null, ar.cause());
      }
    });
  } else if (__args.length === 3 && typeof __args[0] === 'object' && __args[0]._jdel && typeof __args[1] === 'string' && typeof __args[2] === 'function') {
    JPgClient["connect(io.vertx.core.Vertx,java.lang.String,io.vertx.core.Handler)"](__args[0]._jdel, __args[1], function(ar) {
      if (ar.succeeded()) {
        __args[2](utils.convReturnVertxGen(PgConnection, ar.result()), null);
      } else {
        __args[2](null, ar.cause());
      }
    });
  }else throw new TypeError('function invoked with invalid arguments');
};

module.exports = PgClient;

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:18 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/pg_connection.js.html ================================================ JSDoc: Source: pg_connection.js

Source: pg_connection.js

/*
 * Copyright 2014 Red Hat, Inc.
 *
 * Red Hat 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.
 */

/** @module reactive-pg-client-js/pg_connection */
var utils = require('vertx-js/util/utils');
var PgClient = require('reactive-pg-client-js/pg_client');
var PgTransaction = require('reactive-pg-client-js/pg_transaction');
var Tuple = require('reactive-pg-client-js/tuple');
var PgPreparedQuery = require('reactive-pg-client-js/pg_prepared_query');
var PgRowSet = require('reactive-pg-client-js/pg_row_set');

var io = Packages.io;
var JsonObject = io.vertx.core.json.JsonObject;
var JPgConnection = Java.type('io.reactiverse.pgclient.PgConnection');
var PgNotification = Java.type('io.reactiverse.pgclient.PgNotification');

/**
 A connection to Postgres.

 @class
*/
var PgConnection = function(j_val) {

  var j_pgConnection = j_val;
  var that = this;
  PgClient.call(this, j_val);

  var __super_prepare = this.prepare;
  var __super_exceptionHandler = this.exceptionHandler;
  var __super_closeHandler = this.closeHandler;
  var __super_begin = this.begin;
  var __super_notificationHandler = this.notificationHandler;
  var __super_processId = this.processId;
  var __super_secretKey = this.secretKey;
  var __super_cancelRequest = this.cancelRequest;
  var __super_isSSL = this.isSSL;
  var __super_close = this.close;
  var __super_preparedQuery = this.preparedQuery;
  var __super_query = this.query;
  var __super_preparedQuery = this.preparedQuery;
  var __super_preparedBatch = this.preparedBatch;
  /**
   Create a prepared query.

   @public
   @param sql {string} the sql 
   @param handler {function} the handler notified with the prepared query asynchronously 
   @return {PgConnection}
   */
  this.prepare =  function(sql, handler) {
    var __args = arguments;
    if (__args.length === 2 && typeof __args[0] === 'string' && typeof __args[1] === 'function') {
      j_pgConnection["prepare(java.lang.String,io.vertx.core.Handler)"](__args[0], function(ar) {
        if (ar.succeeded()) {
          __args[1](utils.convReturnVertxGen(PgPreparedQuery, ar.result()), null);
        } else {
          __args[1](null, ar.cause());
        }
      }) ;
      return that;
    } else if (typeof __super_prepare != 'undefined') {
      return __super_prepare.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Set an handler called with connection errors.

   @public
   @param handler {function} the handler 
   @return {PgConnection} a reference to this, so the API can be used fluently
   */
  this.exceptionHandler =  function(handler) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'function') {
      j_pgConnection["exceptionHandler(io.vertx.core.Handler)"](function(jVal) {
        __args[0](utils.convReturnThrowable(jVal));
      }) ;
      return that;
    } else if (typeof __super_exceptionHandler != 'undefined') {
      return __super_exceptionHandler.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Set an handler called when the connection is closed.

   @public
   @param handler {function} the handler 
   @return {PgConnection} a reference to this, so the API can be used fluently
   */
  this.closeHandler =  function(handler) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'function') {
      j_pgConnection["closeHandler(io.vertx.core.Handler)"](__args[0]) ;
      return that;
    } else if (typeof __super_closeHandler != 'undefined') {
      return __super_closeHandler.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Begin a transaction and returns a {@link PgTransaction} for controlling and tracking
   this transaction.
   <p/>
   When the connection is explicitely closed, any inflight transaction is rollbacked.

   @public

   @return {PgTransaction} the transaction instance
   */
  this.begin =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      return utils.convReturnVertxGen(PgTransaction, j_pgConnection["begin()"]()) ;
    } else if (typeof __super_begin != 'undefined') {
      return __super_begin.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Set an handler called when the connection receives notification on a channel.
   <p/>
   The handler is called with the <a href="../../dataobjects.html#PgNotification">PgNotification</a> and has access to the channel name
   and the notification payload.

   @public
   @param handler {function} the handler 
   @return {PgConnection} the transaction instance
   */
  this.notificationHandler =  function(handler) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'function') {
      j_pgConnection["notificationHandler(io.vertx.core.Handler)"](function(jVal) {
        __args[0](utils.convReturnDataObject(jVal));
      }) ;
      return that;
    } else if (typeof __super_notificationHandler != 'undefined') {
      return __super_notificationHandler.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**

   @public

   @return {number} The process ID of the target backend
   */
  this.processId =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      return j_pgConnection["processId()"]() ;
    } else if (typeof __super_processId != 'undefined') {
      return __super_processId.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**

   @public

   @return {number} The secret key for the target backend
   */
  this.secretKey =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      return j_pgConnection["secretKey()"]() ;
    } else if (typeof __super_secretKey != 'undefined') {
      return __super_secretKey.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Send a request cancellation message to tell the server to cancel processing request in this connection.
   <br>Note: Use this with caution because the cancellation signal may or may not have any effect.

   @public
   @param handler {function} the handler notified if cancelling request is sent 
   @return {PgConnection} a reference to this, so the API can be used fluently
   */
  this.cancelRequest =  function(handler) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'function') {
      return utils.convReturnVertxGen(PgConnection, j_pgConnection["cancelRequest(io.vertx.core.Handler)"](function(ar) {
        if (ar.succeeded()) {
          __args[0](null, null);
        } else {
          __args[0](null, ar.cause());
        }
      })) ;
    } else if (typeof __super_cancelRequest != 'undefined') {
      return __super_cancelRequest.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**

   @public

   @return {boolean} whether the connection uses SSL
   */
  this.isSSL =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      return j_pgConnection["isSSL()"]() ;
    } else if (typeof __super_isSSL != 'undefined') {
      return __super_isSSL.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Close the current connection after all the pending commands have been processed.

   @public

   */
  this.close =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      j_pgConnection["close()"]();
    } else if (typeof __super_close != 'undefined') {
      return __super_close.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**

   @public
   @param sql {string} 
   @param arguments {Tuple} 
   @param handler {function} 
   @return {PgConnection}
   */
  this.preparedQuery =  function() {
    var __args = arguments;
    if (__args.length === 2 && typeof __args[0] === 'string' && typeof __args[1] === 'function') {
      j_pgConnection["preparedQuery(java.lang.String,io.vertx.core.Handler)"](__args[0], function(ar) {
        if (ar.succeeded()) {
          __args[1](utils.convReturnVertxGen(PgRowSet, ar.result()), null);
        } else {
          __args[1](null, ar.cause());
        }
      }) ;
      return that;
    } else if (__args.length === 3 && typeof __args[0] === 'string' && typeof __args[1] === 'object' && __args[1]._jdel && typeof __args[2] === 'function') {
      j_pgConnection["preparedQuery(java.lang.String,io.reactiverse.pgclient.Tuple,io.vertx.core.Handler)"](__args[0], __args[1]._jdel, function(ar) {
        if (ar.succeeded()) {
          __args[2](utils.convReturnVertxGen(PgRowSet, ar.result()), null);
        } else {
          __args[2](null, ar.cause());
        }
      }) ;
      return that;
    } else if (typeof __super_preparedQuery != 'undefined') {
      return __super_preparedQuery.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**

   @public
   @param sql {string} 
   @param handler {function} 
   @return {PgConnection}
   */
  this.query =  function(sql, handler) {
    var __args = arguments;
    if (__args.length === 2 && typeof __args[0] === 'string' && typeof __args[1] === 'function') {
      j_pgConnection["query(java.lang.String,io.vertx.core.Handler)"](__args[0], function(ar) {
        if (ar.succeeded()) {
          __args[1](utils.convReturnVertxGen(PgRowSet, ar.result()), null);
        } else {
          __args[1](null, ar.cause());
        }
      }) ;
      return that;
    } else if (typeof __super_query != 'undefined') {
      return __super_query.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**

   @public
   @param sql {string} 
   @param batch {Array.<Tuple>} 
   @param handler {function} 
   @return {PgConnection}
   */
  this.preparedBatch =  function(sql, batch, handler) {
    var __args = arguments;
    if (__args.length === 3 && typeof __args[0] === 'string' && typeof __args[1] === 'object' && __args[1] instanceof Array && typeof __args[2] === 'function') {
      j_pgConnection["preparedBatch(java.lang.String,java.util.List,io.vertx.core.Handler)"](__args[0], utils.convParamListVertxGen(__args[1]), function(ar) {
        if (ar.succeeded()) {
          __args[2](utils.convReturnVertxGen(PgRowSet, ar.result()), null);
        } else {
          __args[2](null, ar.cause());
        }
      }) ;
      return that;
    } else if (typeof __super_preparedBatch != 'undefined') {
      return __super_preparedBatch.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  // A reference to the underlying Java delegate
  // NOTE! This is an internal API and must not be used in user code.
  // If you rely on this property your code is likely to break if we change it / remove it without warning.
  this._jdel = j_pgConnection;
};

PgConnection._jclass = utils.getJavaClass("io.reactiverse.pgclient.PgConnection");
PgConnection._jtype = {accept: function(obj) {
    return PgConnection._jclass.isInstance(obj._jdel);
  },wrap: function(jdel) {
    var obj = Object.create(PgConnection.prototype, {});
    PgConnection.apply(obj, arguments);
    return obj;
  },
  unwrap: function(obj) {
    return obj._jdel;
  }
};
PgConnection._create = function(jdel) {var obj = Object.create(PgConnection.prototype, {});
  PgConnection.apply(obj, arguments);
  return obj;
}
module.exports = PgConnection;

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:18 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/pg_cursor.js.html ================================================ JSDoc: Source: pg_cursor.js

Source: pg_cursor.js

/*
 * Copyright 2014 Red Hat, Inc.
 *
 * Red Hat 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.
 */

/** @module reactive-pg-client-js/pg_cursor */
var utils = require('vertx-js/util/utils');
var PgRowSet = require('reactive-pg-client-js/pg_row_set');

var io = Packages.io;
var JsonObject = io.vertx.core.json.JsonObject;
var JPgCursor = Java.type('io.reactiverse.pgclient.PgCursor');

/**
 A cursor that reads progressively the rows from Postgres, it is usefull for reading very large result.

 @class
*/
var PgCursor = function(j_val) {

  var j_pgCursor = j_val;
  var that = this;

  var __super_read = this.read;
  var __super_hasMore = this.hasMore;
  var __super_close = this.close;
  var __super_close = this.close;
  /**
   Read rows from the cursor, the result is provided asynchronously to the <code>handler</code>.

   @public
   @param count {number} the amount of rows to read 
   @param handler {function} the handler for the result 
   */
  this.read =  function(count, handler) {
    var __args = arguments;
    if (__args.length === 2 && typeof __args[0] ==='number' && typeof __args[1] === 'function') {
      j_pgCursor["read(int,io.vertx.core.Handler)"](__args[0], function(ar) {
        if (ar.succeeded()) {
          __args[1](utils.convReturnVertxGen(PgRowSet, ar.result()), null);
        } else {
          __args[1](null, ar.cause());
        }
      });
    } else if (typeof __super_read != 'undefined') {
      return __super_read.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Returns <code>true</code> when the cursor has results in progress and the  should be called to retrieve
   them.

   @public

   @return {boolean} whether the cursor has more results,
   */
  this.hasMore =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      return j_pgCursor["hasMore()"]() ;
    } else if (typeof __super_hasMore != 'undefined') {
      return __super_hasMore.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Like {@link PgCursor#close} but with a <code>completionHandler</code> called when the cursor has been released.

   @public
   @param completionHandler {function} 
   */
  this.close =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      j_pgCursor["close()"]();
    } else if (__args.length === 1 && typeof __args[0] === 'function') {
      j_pgCursor["close(io.vertx.core.Handler)"](function(ar) {
        if (ar.succeeded()) {
          __args[0](null, null);
        } else {
          __args[0](null, ar.cause());
        }
      });
    } else if (typeof __super_close != 'undefined') {
      return __super_close.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  // A reference to the underlying Java delegate
  // NOTE! This is an internal API and must not be used in user code.
  // If you rely on this property your code is likely to break if we change it / remove it without warning.
  this._jdel = j_pgCursor;
};

PgCursor._jclass = utils.getJavaClass("io.reactiverse.pgclient.PgCursor");
PgCursor._jtype = {accept: function(obj) {
    return PgCursor._jclass.isInstance(obj._jdel);
  },wrap: function(jdel) {
    var obj = Object.create(PgCursor.prototype, {});
    PgCursor.apply(obj, arguments);
    return obj;
  },
  unwrap: function(obj) {
    return obj._jdel;
  }
};
PgCursor._create = function(jdel) {var obj = Object.create(PgCursor.prototype, {});
  PgCursor.apply(obj, arguments);
  return obj;
}
module.exports = PgCursor;

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:18 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/pg_iterator.js.html ================================================ JSDoc: Source: pg_iterator.js

Source: pg_iterator.js

/*
 * Copyright 2014 Red Hat, Inc.
 *
 * Red Hat 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.
 */

/** @module reactive-pg-client-js/pg_iterator */
var utils = require('vertx-js/util/utils');
var Row = require('reactive-pg-client-js/row');

var io = Packages.io;
var JsonObject = io.vertx.core.json.JsonObject;
var JPgIterator = Java.type('io.reactiverse.pgclient.PgIterator');

/**
 An iterator for processing postgres items synchronously.

 @class
*/
var PgIterator = function(j_val) {

  var j_pgIterator = j_val;
  var that = this;

  var __super_hasNext = this.hasNext;
  var __super_next = this.next;
  /**

   @public

   @return {boolean}
   */
  this.hasNext =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      return j_pgIterator["hasNext()"]() ;
    } else if (typeof __super_hasNext != 'undefined') {
      return __super_hasNext.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**

   @public

   @return {Row}
   */
  this.next =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      return utils.convReturnVertxGen(Row, j_pgIterator["next()"]()) ;
    } else if (typeof __super_next != 'undefined') {
      return __super_next.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  // A reference to the underlying Java delegate
  // NOTE! This is an internal API and must not be used in user code.
  // If you rely on this property your code is likely to break if we change it / remove it without warning.
  this._jdel = j_pgIterator;
};

PgIterator._jclass = utils.getJavaClass("io.reactiverse.pgclient.PgIterator");
PgIterator._jtype = {accept: function(obj) {
    return PgIterator._jclass.isInstance(obj._jdel);
  },wrap: function(jdel) {
    var obj = Object.create(PgIterator.prototype, {});
    PgIterator.apply(obj, arguments);
    return obj;
  },
  unwrap: function(obj) {
    return obj._jdel;
  }
};
PgIterator._create = function(jdel) {var obj = Object.create(PgIterator.prototype, {});
  PgIterator.apply(obj, arguments);
  return obj;
}
module.exports = PgIterator;

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:18 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/pg_pool.js.html ================================================ JSDoc: Source: pg_pool.js

Source: pg_pool.js

/*
 * Copyright 2014 Red Hat, Inc.
 *
 * Red Hat 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.
 */

/** @module reactive-pg-client-js/pg_pool */
var utils = require('vertx-js/util/utils');
var PgClient = require('reactive-pg-client-js/pg_client');
var PgTransaction = require('reactive-pg-client-js/pg_transaction');
var Tuple = require('reactive-pg-client-js/tuple');
var PgConnection = require('reactive-pg-client-js/pg_connection');
var PgRowSet = require('reactive-pg-client-js/pg_row_set');

var io = Packages.io;
var JsonObject = io.vertx.core.json.JsonObject;
var JPgPool = Java.type('io.reactiverse.pgclient.PgPool');

/**
 A pool of connection.

 @class
*/
var PgPool = function(j_val) {

  var j_pgPool = j_val;
  var that = this;
  PgClient.call(this, j_val);

  var __super_preparedQuery = this.preparedQuery;
  var __super_query = this.query;
  var __super_preparedQuery = this.preparedQuery;
  var __super_preparedBatch = this.preparedBatch;
  var __super_getConnection = this.getConnection;
  var __super_begin = this.begin;
  var __super_close = this.close;
  /**

   @public
   @param sql {string} 
   @param arguments {Tuple} 
   @param handler {function} 
   @return {PgPool}
   */
  this.preparedQuery =  function() {
    var __args = arguments;
    if (__args.length === 2 && typeof __args[0] === 'string' && typeof __args[1] === 'function') {
      j_pgPool["preparedQuery(java.lang.String,io.vertx.core.Handler)"](__args[0], function(ar) {
        if (ar.succeeded()) {
          __args[1](utils.convReturnVertxGen(PgRowSet, ar.result()), null);
        } else {
          __args[1](null, ar.cause());
        }
      }) ;
      return that;
    } else if (__args.length === 3 && typeof __args[0] === 'string' && typeof __args[1] === 'object' && __args[1]._jdel && typeof __args[2] === 'function') {
      j_pgPool["preparedQuery(java.lang.String,io.reactiverse.pgclient.Tuple,io.vertx.core.Handler)"](__args[0], __args[1]._jdel, function(ar) {
        if (ar.succeeded()) {
          __args[2](utils.convReturnVertxGen(PgRowSet, ar.result()), null);
        } else {
          __args[2](null, ar.cause());
        }
      }) ;
      return that;
    } else if (typeof __super_preparedQuery != 'undefined') {
      return __super_preparedQuery.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**

   @public
   @param sql {string} 
   @param handler {function} 
   @return {PgPool}
   */
  this.query =  function(sql, handler) {
    var __args = arguments;
    if (__args.length === 2 && typeof __args[0] === 'string' && typeof __args[1] === 'function') {
      j_pgPool["query(java.lang.String,io.vertx.core.Handler)"](__args[0], function(ar) {
        if (ar.succeeded()) {
          __args[1](utils.convReturnVertxGen(PgRowSet, ar.result()), null);
        } else {
          __args[1](null, ar.cause());
        }
      }) ;
      return that;
    } else if (typeof __super_query != 'undefined') {
      return __super_query.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**

   @public
   @param sql {string} 
   @param batch {Array.<Tuple>} 
   @param handler {function} 
   @return {PgPool}
   */
  this.preparedBatch =  function(sql, batch, handler) {
    var __args = arguments;
    if (__args.length === 3 && typeof __args[0] === 'string' && typeof __args[1] === 'object' && __args[1] instanceof Array && typeof __args[2] === 'function') {
      j_pgPool["preparedBatch(java.lang.String,java.util.List,io.vertx.core.Handler)"](__args[0], utils.convParamListVertxGen(__args[1]), function(ar) {
        if (ar.succeeded()) {
          __args[2](utils.convReturnVertxGen(PgRowSet, ar.result()), null);
        } else {
          __args[2](null, ar.cause());
        }
      }) ;
      return that;
    } else if (typeof __super_preparedBatch != 'undefined') {
      return __super_preparedBatch.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get a connection from the pool.

   @public
   @param handler {function} the handler that will get the connection result 
   */
  this.getConnection =  function(handler) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'function') {
      j_pgPool["getConnection(io.vertx.core.Handler)"](function(ar) {
        if (ar.succeeded()) {
          __args[0](utils.convReturnVertxGen(PgConnection, ar.result()), null);
        } else {
          __args[0](null, ar.cause());
        }
      });
    } else if (typeof __super_getConnection != 'undefined') {
      return __super_getConnection.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Borrow a connection from the pool and begin a transaction, the underlying connection will be returned
   to the pool when the transaction ends.

   @public
   @param handler {function} 
   */
  this.begin =  function(handler) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'function') {
      j_pgPool["begin(io.vertx.core.Handler)"](function(ar) {
        if (ar.succeeded()) {
          __args[0](utils.convReturnVertxGen(PgTransaction, ar.result()), null);
        } else {
          __args[0](null, ar.cause());
        }
      });
    } else if (typeof __super_begin != 'undefined') {
      return __super_begin.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Close the pool and release the associated resources.

   @public

   */
  this.close =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      j_pgPool["close()"]();
    } else if (typeof __super_close != 'undefined') {
      return __super_close.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  // A reference to the underlying Java delegate
  // NOTE! This is an internal API and must not be used in user code.
  // If you rely on this property your code is likely to break if we change it / remove it without warning.
  this._jdel = j_pgPool;
};

PgPool._jclass = utils.getJavaClass("io.reactiverse.pgclient.PgPool");
PgPool._jtype = {accept: function(obj) {
    return PgPool._jclass.isInstance(obj._jdel);
  },wrap: function(jdel) {
    var obj = Object.create(PgPool.prototype, {});
    PgPool.apply(obj, arguments);
    return obj;
  },
  unwrap: function(obj) {
    return obj._jdel;
  }
};
PgPool._create = function(jdel) {var obj = Object.create(PgPool.prototype, {});
  PgPool.apply(obj, arguments);
  return obj;
}
module.exports = PgPool;

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:18 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/pg_prepared_query.js.html ================================================ JSDoc: Source: pg_prepared_query.js

Source: pg_prepared_query.js

/*
 * Copyright 2014 Red Hat, Inc.
 *
 * Red Hat 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.
 */

/** @module reactive-pg-client-js/pg_prepared_query */
var utils = require('vertx-js/util/utils');
var Row = require('reactive-pg-client-js/row');
var Tuple = require('reactive-pg-client-js/tuple');
var PgCursor = require('reactive-pg-client-js/pg_cursor');
var PgRowSet = require('reactive-pg-client-js/pg_row_set');
var PgStream = require('reactive-pg-client-js/pg_stream');

var io = Packages.io;
var JsonObject = io.vertx.core.json.JsonObject;
var JPgPreparedQuery = Java.type('io.reactiverse.pgclient.PgPreparedQuery');

/**
 A prepared query.

 @class
*/
var PgPreparedQuery = function(j_val) {

  var j_pgPreparedQuery = j_val;
  var that = this;

  var __super_execute = this.execute;
  var __super_execute = this.execute;
  var __super_cursor = this.cursor;
  var __super_cursor = this.cursor;
  var __super_createStream = this.createStream;
  var __super_batch = this.batch;
  var __super_close = this.close;
  var __super_close = this.close;
  /**
   Create a cursor with the provided <code>arguments</code>.

   @public
   @param args {Tuple} the list of arguments 
   @param handler {function} 
   @return {PgPreparedQuery} the query
   */
  this.execute =  function() {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'function') {
      j_pgPreparedQuery["execute(io.vertx.core.Handler)"](function(ar) {
        if (ar.succeeded()) {
          __args[0](utils.convReturnVertxGen(PgRowSet, ar.result()), null);
        } else {
          __args[0](null, ar.cause());
        }
      }) ;
      return that;
    } else if (__args.length === 2 && typeof __args[0] === 'object' && __args[0]._jdel && typeof __args[1] === 'function') {
      j_pgPreparedQuery["execute(io.reactiverse.pgclient.Tuple,io.vertx.core.Handler)"](__args[0]._jdel, function(ar) {
        if (ar.succeeded()) {
          __args[1](utils.convReturnVertxGen(PgRowSet, ar.result()), null);
        } else {
          __args[1](null, ar.cause());
        }
      }) ;
      return that;
    } else if (typeof __super_execute != 'undefined') {
      return __super_execute.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Create a cursor with the provided <code>arguments</code>.

   @public
   @param args {Tuple} the list of arguments 
   @return {PgCursor} the query
   */
  this.cursor =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      return utils.convReturnVertxGen(PgCursor, j_pgPreparedQuery["cursor()"]()) ;
    } else if (__args.length === 1 && typeof __args[0] === 'object' && __args[0]._jdel) {
      return utils.convReturnVertxGen(PgCursor, j_pgPreparedQuery["cursor(io.reactiverse.pgclient.Tuple)"](__args[0]._jdel)) ;
    } else if (typeof __super_cursor != 'undefined') {
      return __super_cursor.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Execute the prepared query with a cursor and createStream the result. The createStream opens a cursor
   with a <code>fetch</code> size to fetch the results.
   <p/>
   Note: this requires to be in a transaction, since cursors require it.

   @public
   @param fetch {number} the cursor fetch size 
   @param args {Tuple} the prepared query arguments 
   @return {PgStream} the createStream
   */
  this.createStream =  function(fetch, args) {
    var __args = arguments;
    if (__args.length === 2 && typeof __args[0] ==='number' && typeof __args[1] === 'object' && __args[1]._jdel) {
      return utils.convReturnVertxGen(PgStream, j_pgPreparedQuery["createStream(int,io.reactiverse.pgclient.Tuple)"](__args[0], __args[1]._jdel), Row._jtype) ;
    } else if (typeof __super_createStream != 'undefined') {
      return __super_createStream.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Execute a batch.

   @public
   @param argsList {Array.<Tuple>} the list of tuple for the batch 
   @param handler {function} 
   @return {PgPreparedQuery} the createBatch
   */
  this.batch =  function(argsList, handler) {
    var __args = arguments;
    if (__args.length === 2 && typeof __args[0] === 'object' && __args[0] instanceof Array && typeof __args[1] === 'function') {
      j_pgPreparedQuery["batch(java.util.List,io.vertx.core.Handler)"](utils.convParamListVertxGen(__args[0]), function(ar) {
        if (ar.succeeded()) {
          __args[1](utils.convReturnVertxGen(PgRowSet, ar.result()), null);
        } else {
          __args[1](null, ar.cause());
        }
      }) ;
      return that;
    } else if (typeof __super_batch != 'undefined') {
      return __super_batch.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Like {@link PgPreparedQuery#close} but notifies the <code>completionHandler</code> when it's closed.

   @public
   @param completionHandler {function} 
   */
  this.close =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      j_pgPreparedQuery["close()"]();
    } else if (__args.length === 1 && typeof __args[0] === 'function') {
      j_pgPreparedQuery["close(io.vertx.core.Handler)"](function(ar) {
        if (ar.succeeded()) {
          __args[0](null, null);
        } else {
          __args[0](null, ar.cause());
        }
      });
    } else if (typeof __super_close != 'undefined') {
      return __super_close.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  // A reference to the underlying Java delegate
  // NOTE! This is an internal API and must not be used in user code.
  // If you rely on this property your code is likely to break if we change it / remove it without warning.
  this._jdel = j_pgPreparedQuery;
};

PgPreparedQuery._jclass = utils.getJavaClass("io.reactiverse.pgclient.PgPreparedQuery");
PgPreparedQuery._jtype = {accept: function(obj) {
    return PgPreparedQuery._jclass.isInstance(obj._jdel);
  },wrap: function(jdel) {
    var obj = Object.create(PgPreparedQuery.prototype, {});
    PgPreparedQuery.apply(obj, arguments);
    return obj;
  },
  unwrap: function(obj) {
    return obj._jdel;
  }
};
PgPreparedQuery._create = function(jdel) {var obj = Object.create(PgPreparedQuery.prototype, {});
  PgPreparedQuery.apply(obj, arguments);
  return obj;
}
module.exports = PgPreparedQuery;

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:18 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/pg_result.js.html ================================================ JSDoc: Source: pg_result.js

Source: pg_result.js

/*
 * Copyright 2014 Red Hat, Inc.
 *
 * Red Hat 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.
 */

/** @module reactive-pg-client-js/pg_result */
var utils = require('vertx-js/util/utils');

var io = Packages.io;
var JsonObject = io.vertx.core.json.JsonObject;
var JPgResult = Java.type('io.reactiverse.pgclient.PgResult');

/**
 Represents the result of an operation on database.
 @class
*/
var PgResult = function(j_val, j_arg_0) {

  var j_pgResult = j_val;
  var that = this;
  var j_T = typeof j_arg_0 !== 'undefined' ? j_arg_0 : utils.unknown_jtype;
  var __super_rowCount = this.rowCount;
  var __super_columnsNames = this.columnsNames;
  var __super_size = this.size;
  var __super_value = this.value;
  var __super_next = this.next;
  /**
   Get the number of the affected rows in the operation to this PgResult.
   <p/>
   The meaning depends on the executed statement:
   <ul>
     <li>INSERT: the number of rows inserted</li>
     <li>DELETE: the number of rows deleted</li>
     <li>UPDATE: the number of rows updated</li>
     <li>SELECT: the number of rows retrieved</li>
   </ul>

   @public

   @return {number} the count of affected rows.
   */
  this.rowCount =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      return j_pgResult["rowCount()"]() ;
    } else if (typeof __super_rowCount != 'undefined') {
      return __super_rowCount.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get the names of columns in the PgResult.

   @public

   @return {Array.<string>} the list of names of columns.
   */
  this.columnsNames =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      return j_pgResult["columnsNames()"]() ;
    } else if (typeof __super_columnsNames != 'undefined') {
      return __super_columnsNames.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get the number of rows in the PgResult.

   @public

   @return {number} the count of rows.
   */
  this.size =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      return j_pgResult["size()"]() ;
    } else if (typeof __super_size != 'undefined') {
      return __super_size.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get the result value.

   @public

   @return {Object} the result
   */
  this.value =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      return j_T.wrap(j_pgResult["value()"]()) ;
    } else if (typeof __super_value != 'undefined') {
      return __super_value.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Return the next available result or <code>null</code>, e.g for a simple query that executed multiple queries or for
   a batch result.

   @public

   @return {PgResult} the next available result or <code>null</code> if none is available
   */
  this.next =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      return utils.convReturnVertxGen(PgResult, j_pgResult["next()"](), undefined) ;
    } else if (typeof __super_next != 'undefined') {
      return __super_next.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  // A reference to the underlying Java delegate
  // NOTE! This is an internal API and must not be used in user code.
  // If you rely on this property your code is likely to break if we change it / remove it without warning.
  this._jdel = j_pgResult;
};

PgResult._jclass = utils.getJavaClass("io.reactiverse.pgclient.PgResult");
PgResult._jtype = {accept: function(obj) {
    return PgResult._jclass.isInstance(obj._jdel);
  },wrap: function(jdel) {
    var obj = Object.create(PgResult.prototype, {});
    PgResult.apply(obj, arguments);
    return obj;
  },
  unwrap: function(obj) {
    return obj._jdel;
  }
};
PgResult._create = function(jdel) {var obj = Object.create(PgResult.prototype, {});
  PgResult.apply(obj, arguments);
  return obj;
}
module.exports = PgResult;

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:18 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/pg_row_set.js.html ================================================ JSDoc: Source: pg_row_set.js

Source: pg_row_set.js

/*
 * Copyright 2014 Red Hat, Inc.
 *
 * Red Hat 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.
 */

/** @module reactive-pg-client-js/pg_row_set */
var utils = require('vertx-js/util/utils');
var PgIterator = require('reactive-pg-client-js/pg_iterator');
var Row = require('reactive-pg-client-js/row');
var PgResult = require('reactive-pg-client-js/pg_result');

var io = Packages.io;
var JsonObject = io.vertx.core.json.JsonObject;
var JPgRowSet = Java.type('io.reactiverse.pgclient.PgRowSet');

/**
 A set of rows.

 @class
*/
var PgRowSet = function(j_val) {

  var j_pgRowSet = j_val;
  var that = this;
  PgResult.call(this, j_val, PgRowSet._jtype);

  var __super_value = this.value;
  var __super_iterator = this.iterator;
  var __super_next = this.next;
  /**
   Get the result value.

   @public

   @return {PgRowSet} the result
   */
  this.value =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      return utils.convReturnVertxGen(PgRowSet, j_pgRowSet["value()"]()) ;
    } else if (typeof __super_value != 'undefined') {
      return __super_value.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**

   @public

   @return {PgIterator}
   */
  this.iterator =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      return utils.convReturnVertxGen(PgIterator, j_pgRowSet["iterator()"]()) ;
    } else if (typeof __super_iterator != 'undefined') {
      return __super_iterator.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**

   @public

   @return {PgRowSet}
   */
  this.next =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      return utils.convReturnVertxGen(PgRowSet, j_pgRowSet["next()"]()) ;
    } else if (typeof __super_next != 'undefined') {
      return __super_next.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  // A reference to the underlying Java delegate
  // NOTE! This is an internal API and must not be used in user code.
  // If you rely on this property your code is likely to break if we change it / remove it without warning.
  this._jdel = j_pgRowSet;
};

PgRowSet._jclass = utils.getJavaClass("io.reactiverse.pgclient.PgRowSet");
PgRowSet._jtype = {accept: function(obj) {
    return PgRowSet._jclass.isInstance(obj._jdel);
  },wrap: function(jdel) {
    var obj = Object.create(PgRowSet.prototype, {});
    PgRowSet.apply(obj, arguments);
    return obj;
  },
  unwrap: function(obj) {
    return obj._jdel;
  }
};
PgRowSet._create = function(jdel) {var obj = Object.create(PgRowSet.prototype, {});
  PgRowSet.apply(obj, arguments);
  return obj;
}
module.exports = PgRowSet;

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:18 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/pg_stream.js.html ================================================ JSDoc: Source: pg_stream.js

Source: pg_stream.js

/*
 * Copyright 2014 Red Hat, Inc.
 *
 * Red Hat 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.
 */

/** @module reactive-pg-client-js/pg_stream */
var utils = require('vertx-js/util/utils');
var ReadStream = require('vertx-js/read_stream');

var io = Packages.io;
var JsonObject = io.vertx.core.json.JsonObject;
var JPgStream = Java.type('io.reactiverse.pgclient.PgStream');

/**
 A row oriented stream.

 @class
*/
var PgStream = function(j_val, j_arg_0) {

  var j_pgStream = j_val;
  var that = this;
  var j_T = typeof j_arg_0 !== 'undefined' ? j_arg_0 : utils.unknown_jtype;ReadStream.call(this, j_val);

  var __super_fetch = this.fetch;
  var __super_exceptionHandler = this.exceptionHandler;
  var __super_handler = this.handler;
  var __super_pause = this.pause;
  var __super_resume = this.resume;
  var __super_endHandler = this.endHandler;
  var __super_close = this.close;
  var __super_close = this.close;
  /**

   @public
   @param arg0 {number} 
   @return {ReadStream}
   */
  this.fetch =  function(arg0) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      j_pgStream["fetch(long)"](__args[0]) ;
      return that;
    } else if (typeof __super_fetch != 'undefined') {
      return __super_fetch.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**

   @public
   @param handler {function} 
   @return {PgStream}
   */
  this.exceptionHandler =  function(handler) {
    var __args = arguments;
    if (__args.length === 1 && (typeof __args[0] === 'function' || __args[0] == null)) {
      j_pgStream["exceptionHandler(io.vertx.core.Handler)"](__args[0] == null ? null : function(jVal) {
        __args[0](utils.convReturnThrowable(jVal));
      }) ;
      return that;
    } else if (typeof __super_exceptionHandler != 'undefined') {
      return __super_exceptionHandler.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**

   @public
   @param handler {function} 
   @return {PgStream}
   */
  this.handler =  function(handler) {
    var __args = arguments;
    if (__args.length === 1 && (typeof __args[0] === 'function' || __args[0] == null)) {
      j_pgStream["handler(io.vertx.core.Handler)"](__args[0] == null ? null : function(jVal) {
        __args[0](j_T.wrap(jVal));
      }) ;
      return that;
    } else if (typeof __super_handler != 'undefined') {
      return __super_handler.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**

   @public

   @return {PgStream}
   */
  this.pause =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      j_pgStream["pause()"]() ;
      return that;
    } else if (typeof __super_pause != 'undefined') {
      return __super_pause.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**

   @public

   @return {PgStream}
   */
  this.resume =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      j_pgStream["resume()"]() ;
      return that;
    } else if (typeof __super_resume != 'undefined') {
      return __super_resume.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**

   @public
   @param endHandler {function} 
   @return {PgStream}
   */
  this.endHandler =  function(endHandler) {
    var __args = arguments;
    if (__args.length === 1 && (typeof __args[0] === 'function' || __args[0] == null)) {
      j_pgStream["endHandler(io.vertx.core.Handler)"](__args[0]) ;
      return that;
    } else if (typeof __super_endHandler != 'undefined') {
      return __super_endHandler.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Close the stream and release the resources.

   @public
   @param completionHandler {function} the completion handler for this operation 
   */
  this.close =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      j_pgStream["close()"]();
    } else if (__args.length === 1 && typeof __args[0] === 'function') {
      j_pgStream["close(io.vertx.core.Handler)"](function(ar) {
        if (ar.succeeded()) {
          __args[0](null, null);
        } else {
          __args[0](null, ar.cause());
        }
      });
    } else if (typeof __super_close != 'undefined') {
      return __super_close.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  // A reference to the underlying Java delegate
  // NOTE! This is an internal API and must not be used in user code.
  // If you rely on this property your code is likely to break if we change it / remove it without warning.
  this._jdel = j_pgStream;
};

PgStream._jclass = utils.getJavaClass("io.reactiverse.pgclient.PgStream");
PgStream._jtype = {accept: function(obj) {
    return PgStream._jclass.isInstance(obj._jdel);
  },wrap: function(jdel) {
    var obj = Object.create(PgStream.prototype, {});
    PgStream.apply(obj, arguments);
    return obj;
  },
  unwrap: function(obj) {
    return obj._jdel;
  }
};
PgStream._create = function(jdel) {var obj = Object.create(PgStream.prototype, {});
  PgStream.apply(obj, arguments);
  return obj;
}
module.exports = PgStream;

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:18 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/pg_subscriber.js.html ================================================ JSDoc: Source: pg_subscriber.js

Source: pg_subscriber.js

/*
 * Copyright 2014 Red Hat, Inc.
 *
 * Red Hat 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.
 */

/** @module reactive-pg-client-js/pg_subscriber */
var utils = require('vertx-js/util/utils');
var Vertx = require('vertx-js/vertx');
var PgConnection = require('reactive-pg-client-js/pg_connection');
var PgChannel = require('reactive-pg-client-js/pg_channel');

var io = Packages.io;
var JsonObject = io.vertx.core.json.JsonObject;
var JPgSubscriber = Java.type('io.reactiverse.pgclient.pubsub.PgSubscriber');
var PgConnectOptions = Java.type('io.reactiverse.pgclient.PgConnectOptions');

/**

 @class
*/
var PgSubscriber = function(j_val) {

  var j_pgSubscriber = j_val;
  var that = this;

  var __super_subscriber = this.subscriber;
  var __super_channel = this.channel;
  var __super_connect = this.connect;
  var __super_reconnectPolicy = this.reconnectPolicy;
  var __super_closeHandler = this.closeHandler;
  var __super_actualConnection = this.actualConnection;
  var __super_closed = this.closed;
  var __super_close = this.close;
  /**
   Return a channel for the given <code>name</code>.

   @public
   @param name {string} the channel name <p/> This will be the name of the channel exactly as held by Postgres for sending notifications. Internally this name will be truncated to the Postgres identifier maxiumum length of <code>(NAMEDATALEN = 64) - 1 == 63</code> characters, and prepared as a quoted identifier without unicode escape sequence support for use in <code>LISTEN/UNLISTEN</code> commands. Examples of channel names and corresponding <code>NOTIFY</code> commands: <ul> <li>when <code>name == "the_channel"</code>: <code>NOTIFY the_channel, 'msg'</code>, <code>NOTIFY The_Channel, 'msg'</code>, or <code>NOTIFY "the_channel", 'msg'</code> succeed in delivering a message to the created channel </li> <li>when <code>name == "The_Channel"</code>: <code>NOTIFY "The_Channel", 'msg'</code>, succeeds in delivering a message to the created channel </li> <li></li> </ul> 
   @return {PgChannel} the channel
   */
  this.channel =  function(name) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'string') {
      return utils.convReturnVertxGen(PgChannel, j_pgSubscriber["channel(java.lang.String)"](__args[0])) ;
    } else if (typeof __super_channel != 'undefined') {
      return __super_channel.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Connect the subscriber to Postgres.

   @public
   @param handler {function} the handler notified of the connection success or failure 
   @return {PgSubscriber} a reference to this, so the API can be used fluently
   */
  this.connect =  function(handler) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'function') {
      j_pgSubscriber["connect(io.vertx.core.Handler)"](function(ar) {
        if (ar.succeeded()) {
          __args[0](null, null);
        } else {
          __args[0](null, ar.cause());
        }
      }) ;
      return that;
    } else if (typeof __super_connect != 'undefined') {
      return __super_connect.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Set the reconnect policy that is executed when the subscriber is disconnected.
   <p/>
   When the subscriber is disconnected, the <code>policy</code> function is called with the actual
   number of retries and returns an <code>amountOfTime</code> value:
   <ul>
     <li>when <code>amountOfTime < 0</code>: the subscriber is closed and there is no retry</li>
     <li>when <code>amountOfTime == 0</code>: the subscriber retries to connect immediately</li>
     <li>when <code>amountOfTime > 0</code>: the subscriber retries after <code>amountOfTime</code> milliseconds</li>
   </ul>
   <p/>
   The default policy does not perform any retries.

   @public
   @param policy {function} the policy to set 
   @return {PgSubscriber} a reference to this, so the API can be used fluently
   */
  this.reconnectPolicy =  function(policy) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'function') {
      j_pgSubscriber["reconnectPolicy(java.util.function.Function)"](function(jVal) {
        var jRet = __args[0](jVal);
        return utils.convParamLong(jRet);
      }) ;
      return that;
    } else if (typeof __super_reconnectPolicy != 'undefined') {
      return __super_reconnectPolicy.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Set an handler called when the subscriber is closed.

   @public
   @param handler {function} the handler 
   @return {PgSubscriber} a reference to this, so the API can be used fluently
   */
  this.closeHandler =  function(handler) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'function') {
      j_pgSubscriber["closeHandler(io.vertx.core.Handler)"](__args[0]) ;
      return that;
    } else if (typeof __super_closeHandler != 'undefined') {
      return __super_closeHandler.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**

   @public

   @return {PgConnection} the actual connection to Postgres, it might be <code>null</code>
   */
  this.actualConnection =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      return utils.convReturnVertxGen(PgConnection, j_pgSubscriber["actualConnection()"]()) ;
    } else if (typeof __super_actualConnection != 'undefined') {
      return __super_actualConnection.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**

   @public

   @return {boolean} whether the subscriber is closed
   */
  this.closed =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      return j_pgSubscriber["closed()"]() ;
    } else if (typeof __super_closed != 'undefined') {
      return __super_closed.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Close the subscriber, the retry policy will not be invoked.

   @public

   */
  this.close =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      j_pgSubscriber["close()"]();
    } else if (typeof __super_close != 'undefined') {
      return __super_close.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  // A reference to the underlying Java delegate
  // NOTE! This is an internal API and must not be used in user code.
  // If you rely on this property your code is likely to break if we change it / remove it without warning.
  this._jdel = j_pgSubscriber;
};

PgSubscriber._jclass = utils.getJavaClass("io.reactiverse.pgclient.pubsub.PgSubscriber");
PgSubscriber._jtype = {accept: function(obj) {
    return PgSubscriber._jclass.isInstance(obj._jdel);
  },wrap: function(jdel) {
    var obj = Object.create(PgSubscriber.prototype, {});
    PgSubscriber.apply(obj, arguments);
    return obj;
  },
  unwrap: function(obj) {
    return obj._jdel;
  }
};
PgSubscriber._create = function(jdel) {var obj = Object.create(PgSubscriber.prototype, {});
  PgSubscriber.apply(obj, arguments);
  return obj;
}
/**
 Create a subscriber.

 @memberof module:reactive-pg-client-js/pg_subscriber
 @param vertx {Vertx} the vertx instance 
 @param options {Object} the connect options 
 @return {PgSubscriber} the subscriber
 */
PgSubscriber.subscriber =  function(vertx, options) {
  var __args = arguments;
  if (__args.length === 2 && typeof __args[0] === 'object' && __args[0]._jdel && (typeof __args[1] === 'object' && __args[1] != null)) {
    return utils.convReturnVertxGen(PgSubscriber, JPgSubscriber["subscriber(io.vertx.core.Vertx,io.reactiverse.pgclient.PgConnectOptions)"](__args[0]._jdel, __args[1]  != null ? new PgConnectOptions(new JsonObject(Java.asJSONCompatible(__args[1]))) : null)) ;
  }else throw new TypeError('function invoked with invalid arguments');
};

module.exports = PgSubscriber;

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:18 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/pg_transaction.js.html ================================================ JSDoc: Source: pg_transaction.js

Source: pg_transaction.js

/*
 * Copyright 2014 Red Hat, Inc.
 *
 * Red Hat 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.
 */

/** @module reactive-pg-client-js/pg_transaction */
var utils = require('vertx-js/util/utils');
var PgClient = require('reactive-pg-client-js/pg_client');
var Tuple = require('reactive-pg-client-js/tuple');
var PgPreparedQuery = require('reactive-pg-client-js/pg_prepared_query');
var PgRowSet = require('reactive-pg-client-js/pg_row_set');

var io = Packages.io;
var JsonObject = io.vertx.core.json.JsonObject;
var JPgTransaction = Java.type('io.reactiverse.pgclient.PgTransaction');

/**
 A transaction that allows to control the transaction and receive events.

 @class
*/
var PgTransaction = function(j_val) {

  var j_pgTransaction = j_val;
  var that = this;
  PgClient.call(this, j_val);

  var __super_prepare = this.prepare;
  var __super_commit = this.commit;
  var __super_commit = this.commit;
  var __super_rollback = this.rollback;
  var __super_rollback = this.rollback;
  var __super_abortHandler = this.abortHandler;
  var __super_query = this.query;
  var __super_preparedQuery = this.preparedQuery;
  var __super_preparedQuery = this.preparedQuery;
  var __super_preparedBatch = this.preparedBatch;
  /**
   Create a prepared query.

   @public
   @param sql {string} the sql 
   @param handler {function} the handler notified with the prepared query asynchronously 
   @return {PgTransaction}
   */
  this.prepare =  function(sql, handler) {
    var __args = arguments;
    if (__args.length === 2 && typeof __args[0] === 'string' && typeof __args[1] === 'function') {
      j_pgTransaction["prepare(java.lang.String,io.vertx.core.Handler)"](__args[0], function(ar) {
        if (ar.succeeded()) {
          __args[1](utils.convReturnVertxGen(PgPreparedQuery, ar.result()), null);
        } else {
          __args[1](null, ar.cause());
        }
      }) ;
      return that;
    } else if (typeof __super_prepare != 'undefined') {
      return __super_prepare.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Like {@link PgTransaction#commit} with an handler to be notified when the transaction commit has completed

   @public
   @param handler {function} 
   */
  this.commit =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      j_pgTransaction["commit()"]();
    } else if (__args.length === 1 && typeof __args[0] === 'function') {
      j_pgTransaction["commit(io.vertx.core.Handler)"](function(ar) {
        if (ar.succeeded()) {
          __args[0](null, null);
        } else {
          __args[0](null, ar.cause());
        }
      });
    } else if (typeof __super_commit != 'undefined') {
      return __super_commit.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Like {@link PgTransaction#rollback} with an handler to be notified when the transaction rollback has completed

   @public
   @param handler {function} 
   */
  this.rollback =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      j_pgTransaction["rollback()"]();
    } else if (__args.length === 1 && typeof __args[0] === 'function') {
      j_pgTransaction["rollback(io.vertx.core.Handler)"](function(ar) {
        if (ar.succeeded()) {
          __args[0](null, null);
        } else {
          __args[0](null, ar.cause());
        }
      });
    } else if (typeof __super_rollback != 'undefined') {
      return __super_rollback.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Set an handler to be called when the transaction is aborted.

   @public
   @param handler {function} the handler 
   @return {PgTransaction}
   */
  this.abortHandler =  function(handler) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'function') {
      j_pgTransaction["abortHandler(io.vertx.core.Handler)"](__args[0]) ;
      return that;
    } else if (typeof __super_abortHandler != 'undefined') {
      return __super_abortHandler.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**

   @public
   @param sql {string} 
   @param handler {function} 
   @return {PgTransaction}
   */
  this.query =  function(sql, handler) {
    var __args = arguments;
    if (__args.length === 2 && typeof __args[0] === 'string' && typeof __args[1] === 'function') {
      j_pgTransaction["query(java.lang.String,io.vertx.core.Handler)"](__args[0], function(ar) {
        if (ar.succeeded()) {
          __args[1](utils.convReturnVertxGen(PgRowSet, ar.result()), null);
        } else {
          __args[1](null, ar.cause());
        }
      }) ;
      return that;
    } else if (typeof __super_query != 'undefined') {
      return __super_query.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**

   @public
   @param sql {string} 
   @param arguments {Tuple} 
   @param handler {function} 
   @return {PgTransaction}
   */
  this.preparedQuery =  function() {
    var __args = arguments;
    if (__args.length === 2 && typeof __args[0] === 'string' && typeof __args[1] === 'function') {
      j_pgTransaction["preparedQuery(java.lang.String,io.vertx.core.Handler)"](__args[0], function(ar) {
        if (ar.succeeded()) {
          __args[1](utils.convReturnVertxGen(PgRowSet, ar.result()), null);
        } else {
          __args[1](null, ar.cause());
        }
      }) ;
      return that;
    } else if (__args.length === 3 && typeof __args[0] === 'string' && typeof __args[1] === 'object' && __args[1]._jdel && typeof __args[2] === 'function') {
      j_pgTransaction["preparedQuery(java.lang.String,io.reactiverse.pgclient.Tuple,io.vertx.core.Handler)"](__args[0], __args[1]._jdel, function(ar) {
        if (ar.succeeded()) {
          __args[2](utils.convReturnVertxGen(PgRowSet, ar.result()), null);
        } else {
          __args[2](null, ar.cause());
        }
      }) ;
      return that;
    } else if (typeof __super_preparedQuery != 'undefined') {
      return __super_preparedQuery.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**

   @public
   @param sql {string} 
   @param batch {Array.<Tuple>} 
   @param handler {function} 
   @return {PgTransaction}
   */
  this.preparedBatch =  function(sql, batch, handler) {
    var __args = arguments;
    if (__args.length === 3 && typeof __args[0] === 'string' && typeof __args[1] === 'object' && __args[1] instanceof Array && typeof __args[2] === 'function') {
      j_pgTransaction["preparedBatch(java.lang.String,java.util.List,io.vertx.core.Handler)"](__args[0], utils.convParamListVertxGen(__args[1]), function(ar) {
        if (ar.succeeded()) {
          __args[2](utils.convReturnVertxGen(PgRowSet, ar.result()), null);
        } else {
          __args[2](null, ar.cause());
        }
      }) ;
      return that;
    } else if (typeof __super_preparedBatch != 'undefined') {
      return __super_preparedBatch.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  // A reference to the underlying Java delegate
  // NOTE! This is an internal API and must not be used in user code.
  // If you rely on this property your code is likely to break if we change it / remove it without warning.
  this._jdel = j_pgTransaction;
};

PgTransaction._jclass = utils.getJavaClass("io.reactiverse.pgclient.PgTransaction");
PgTransaction._jtype = {accept: function(obj) {
    return PgTransaction._jclass.isInstance(obj._jdel);
  },wrap: function(jdel) {
    var obj = Object.create(PgTransaction.prototype, {});
    PgTransaction.apply(obj, arguments);
    return obj;
  },
  unwrap: function(obj) {
    return obj._jdel;
  }
};
PgTransaction._create = function(jdel) {var obj = Object.create(PgTransaction.prototype, {});
  PgTransaction.apply(obj, arguments);
  return obj;
}
module.exports = PgTransaction;

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:18 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/row.js.html ================================================ JSDoc: Source: row.js

Source: row.js

/*
 * Copyright 2014 Red Hat, Inc.
 *
 * Red Hat 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.
 */

/** @module reactive-pg-client-js/row */
var utils = require('vertx-js/util/utils');
var Json = require('reactive-pg-client-js/json');
var Buffer = require('vertx-js/buffer');
var Tuple = require('reactive-pg-client-js/tuple');

var io = Packages.io;
var JsonObject = io.vertx.core.json.JsonObject;
var JRow = Java.type('io.reactiverse.pgclient.Row');
var Point = Java.type('io.reactiverse.pgclient.data.Point');
var Path = Java.type('io.reactiverse.pgclient.data.Path');
var Box = Java.type('io.reactiverse.pgclient.data.Box');
var Circle = Java.type('io.reactiverse.pgclient.data.Circle');
var Polygon = Java.type('io.reactiverse.pgclient.data.Polygon');
var Interval = Java.type('io.reactiverse.pgclient.data.Interval');
var LineSegment = Java.type('io.reactiverse.pgclient.data.LineSegment');
var Line = Java.type('io.reactiverse.pgclient.data.Line');

/**
 @class
*/
var Row = function(j_val) {

  var j_row = j_val;
  var that = this;
  Tuple.call(this, j_val);

  var __super_getColumnName = this.getColumnName;
  var __super_getBoolean = this.getBoolean;
  var __super_getValue = this.getValue;
  var __super_getShort = this.getShort;
  var __super_getInteger = this.getInteger;
  var __super_getLong = this.getLong;
  var __super_getFloat = this.getFloat;
  var __super_getDouble = this.getDouble;
  var __super_getString = this.getString;
  var __super_getJson = this.getJson;
  var __super_getBuffer = this.getBuffer;
  var __super_getPoint = this.getPoint;
  var __super_getLine = this.getLine;
  var __super_getLineSegment = this.getLineSegment;
  var __super_getBox = this.getBox;
  var __super_getPath = this.getPath;
  var __super_getPolygon = this.getPolygon;
  var __super_getCircle = this.getCircle;
  var __super_getInterval = this.getInterval;
  /**
   Get a column name at <code>pos</code>.

   @public
   @param pos {number} the position 
   @return {string} the column name or <code>null</code>
   */
  this.getColumnName =  function(pos) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      return j_row["getColumnName(int)"](__args[0]) ;
    } else if (typeof __super_getColumnName != 'undefined') {
      return __super_getColumnName.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get a boolean value at <code>pos</code>.

   @public
   @param name {string} the column 
   @return {boolean} the value or <code>null</code>
   */
  this.getBoolean =  function(name) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'string') {
      return j_row["getBoolean(java.lang.String)"](__args[0]) ;
    } else if (typeof __super_getBoolean != 'undefined') {
      return __super_getBoolean.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get an object value at <code>pos</code>.

   @public
   @param name {string} the column 
   @return {Object} the value or <code>null</code>
   */
  this.getValue =  function(name) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'string') {
      return utils.convReturnTypeUnknown(j_row["getValue(java.lang.String)"](__args[0])) ;
    } else if (typeof __super_getValue != 'undefined') {
      return __super_getValue.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get a short value at <code>pos</code>.

   @public
   @param name {string} the column 
   @return {number} the value or <code>null</code>
   */
  this.getShort =  function(name) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'string') {
      return j_row["getShort(java.lang.String)"](__args[0]) ;
    } else if (typeof __super_getShort != 'undefined') {
      return __super_getShort.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get an integer value at <code>pos</code>.

   @public
   @param name {string} the column 
   @return {number} the value or <code>null</code>
   */
  this.getInteger =  function(name) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'string') {
      return j_row["getInteger(java.lang.String)"](__args[0]) ;
    } else if (typeof __super_getInteger != 'undefined') {
      return __super_getInteger.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get a long value at <code>pos</code>.

   @public
   @param name {string} the column 
   @return {number} the value or <code>null</code>
   */
  this.getLong =  function(name) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'string') {
      return utils.convReturnLong(j_row["getLong(java.lang.String)"](__args[0])) ;
    } else if (typeof __super_getLong != 'undefined') {
      return __super_getLong.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get a float value at <code>pos</code>.

   @public
   @param name {string} the column 
   @return {number} the value or <code>null</code>
   */
  this.getFloat =  function(name) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'string') {
      return j_row["getFloat(java.lang.String)"](__args[0]) ;
    } else if (typeof __super_getFloat != 'undefined') {
      return __super_getFloat.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get a double value at <code>pos</code>.

   @public
   @param name {string} the column 
   @return {number} the value or <code>null</code>
   */
  this.getDouble =  function(name) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'string') {
      return j_row["getDouble(java.lang.String)"](__args[0]) ;
    } else if (typeof __super_getDouble != 'undefined') {
      return __super_getDouble.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get a string value at <code>pos</code>.

   @public
   @param name {string} the column 
   @return {string} the value or <code>null</code>
   */
  this.getString =  function(name) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'string') {
      return j_row["getString(java.lang.String)"](__args[0]) ;
    } else if (typeof __super_getString != 'undefined') {
      return __super_getString.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get a json value at <code>pos</code>.

   @public
   @param name {string} the column 
   @return {Json} the value or <code>null</code>
   */
  this.getJson =  function(name) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'string') {
      return utils.convReturnVertxGen(Json, j_row["getJson(java.lang.String)"](__args[0])) ;
    } else if (typeof __super_getJson != 'undefined') {
      return __super_getJson.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get a buffer value at <code>pos</code>.

   @public
   @param name {string} the column 
   @return {Buffer} the value or <code>null</code>
   */
  this.getBuffer =  function(name) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'string') {
      return utils.convReturnVertxGen(Buffer, j_row["getBuffer(java.lang.String)"](__args[0])) ;
    } else if (typeof __super_getBuffer != 'undefined') {
      return __super_getBuffer.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get  value at <code>pos</code>.

   @public
   @param name {string} the column 
   @return {Object} the value or <code>null</code>
   */
  this.getPoint =  function(name) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'string') {
      return utils.convReturnDataObject(j_row["getPoint(java.lang.String)"](__args[0])) ;
    } else if (typeof __super_getPoint != 'undefined') {
      return __super_getPoint.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get  value at <code>pos</code>.

   @public
   @param name {string} the column 
   @return {Object} the value or <code>null</code>
   */
  this.getLine =  function(name) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'string') {
      return utils.convReturnDataObject(j_row["getLine(java.lang.String)"](__args[0])) ;
    } else if (typeof __super_getLine != 'undefined') {
      return __super_getLine.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get  value at <code>pos</code>.

   @public
   @param name {string} the column 
   @return {Object} the value or <code>null</code>
   */
  this.getLineSegment =  function(name) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'string') {
      return utils.convReturnDataObject(j_row["getLineSegment(java.lang.String)"](__args[0])) ;
    } else if (typeof __super_getLineSegment != 'undefined') {
      return __super_getLineSegment.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get  value at <code>pos</code>.

   @public
   @param name {string} the column 
   @return {Object} the value or <code>null</code>
   */
  this.getBox =  function(name) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'string') {
      return utils.convReturnDataObject(j_row["getBox(java.lang.String)"](__args[0])) ;
    } else if (typeof __super_getBox != 'undefined') {
      return __super_getBox.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get  value at <code>pos</code>.

   @public
   @param name {string} the column 
   @return {Object} the value or <code>null</code>
   */
  this.getPath =  function(name) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'string') {
      return utils.convReturnDataObject(j_row["getPath(java.lang.String)"](__args[0])) ;
    } else if (typeof __super_getPath != 'undefined') {
      return __super_getPath.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get  value at <code>pos</code>.

   @public
   @param name {string} the column 
   @return {Object} the value or <code>null</code>
   */
  this.getPolygon =  function(name) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'string') {
      return utils.convReturnDataObject(j_row["getPolygon(java.lang.String)"](__args[0])) ;
    } else if (typeof __super_getPolygon != 'undefined') {
      return __super_getPolygon.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get  value at <code>pos</code>.

   @public
   @param name {string} the column 
   @return {Object} the value or <code>null</code>
   */
  this.getCircle =  function(name) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'string') {
      return utils.convReturnDataObject(j_row["getCircle(java.lang.String)"](__args[0])) ;
    } else if (typeof __super_getCircle != 'undefined') {
      return __super_getCircle.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get  value at <code>pos</code>.

   @public
   @param name {string} the column 
   @return {Object} the value or <code>null</code>
   */
  this.getInterval =  function(name) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'string') {
      return utils.convReturnDataObject(j_row["getInterval(java.lang.String)"](__args[0])) ;
    } else if (typeof __super_getInterval != 'undefined') {
      return __super_getInterval.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  // A reference to the underlying Java delegate
  // NOTE! This is an internal API and must not be used in user code.
  // If you rely on this property your code is likely to break if we change it / remove it without warning.
  this._jdel = j_row;
};

Row._jclass = utils.getJavaClass("io.reactiverse.pgclient.Row");
Row._jtype = {accept: function(obj) {
    return Row._jclass.isInstance(obj._jdel);
  },wrap: function(jdel) {
    var obj = Object.create(Row.prototype, {});
    Row.apply(obj, arguments);
    return obj;
  },
  unwrap: function(obj) {
    return obj._jdel;
  }
};
Row._create = function(jdel) {var obj = Object.create(Row.prototype, {});
  Row.apply(obj, arguments);
  return obj;
}
module.exports = Row;

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:18 GMT+0100 (CET)
================================================ FILE: docs/jsdoc/scripts/linenumber.js ================================================ /*global document */ (function() { var source = document.getElementsByClassName('prettyprint source linenums'); var i = 0; var lineNumber = 0; var lineId; var lines; var totalLines; var anchorHash; if (source && source[0]) { anchorHash = document.location.hash.substring(1); lines = source[0].getElementsByTagName('li'); totalLines = lines.length; for (; i < totalLines; i++) { lineNumber++; lineId = 'line' + lineNumber; lines[i].id = lineId; if (lineId === anchorHash) { lines[i].className += ' selected'; } } } })(); ================================================ FILE: docs/jsdoc/scripts/prettify/Apache-License-2.0.txt ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed 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. ================================================ FILE: docs/jsdoc/scripts/prettify/lang-css.js ================================================ PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\f\r ]+/,null," \t\r\n "]],[["str",/^"(?:[^\n\f\r"\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*"/,null],["str",/^'(?:[^\n\f\r'\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*'/,null],["lang-css-str",/^url\(([^"')]*)\)/i],["kwd",/^(?:url|rgb|!important|@import|@page|@media|@charset|inherit)(?=[^\w-]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*)\s*:/i],["com",/^\/\*[^*]*\*+(?:[^*/][^*]*\*+)*\//],["com", /^(?:<\!--|--\>)/],["lit",/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],["lit",/^#[\da-f]{3,6}/i],["pln",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i],["pun",/^[^\s\w"']+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[["kwd",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[["str",/^[^"')]+/]]),["css-str"]); ================================================ FILE: docs/jsdoc/scripts/prettify/prettify.js ================================================ var q=null;window.PR_SHOULD_USE_CONTINUATION=!0; (function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a= [],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;ci[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m), l=[],p={},d=0,g=e.length;d=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/, q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/, q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g, "");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a), a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e} for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"], "catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"], H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"], J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+ I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]), ["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css", /^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}), ["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes", hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p=0){var k=k.match(g),f,b;if(b= !k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p p:first-child, .props td.description > p:first-child { margin-top: 0; padding-top: 0; } .params td.description > p:last-child, .props td.description > p:last-child { margin-bottom: 0; padding-bottom: 0; } .disabled { color: #454545; } ================================================ FILE: docs/jsdoc/styles/prettify-jsdoc.css ================================================ /* JSDoc prettify.js theme */ /* plain text */ .pln { color: #000000; font-weight: normal; font-style: normal; } /* string content */ .str { color: #006400; font-weight: normal; font-style: normal; } /* a keyword */ .kwd { color: #000000; font-weight: bold; font-style: normal; } /* a comment */ .com { font-weight: normal; font-style: italic; } /* a type name */ .typ { color: #000000; font-weight: normal; font-style: normal; } /* a literal value */ .lit { color: #006400; font-weight: normal; font-style: normal; } /* punctuation */ .pun { color: #000000; font-weight: bold; font-style: normal; } /* lisp open bracket */ .opn { color: #000000; font-weight: bold; font-style: normal; } /* lisp close bracket */ .clo { color: #000000; font-weight: bold; font-style: normal; } /* a markup tag name */ .tag { color: #006400; font-weight: normal; font-style: normal; } /* a markup attribute name */ .atn { color: #006400; font-weight: normal; font-style: normal; } /* a markup attribute value */ .atv { color: #006400; font-weight: normal; font-style: normal; } /* a declaration */ .dec { color: #000000; font-weight: bold; font-style: normal; } /* a variable name */ .var { color: #000000; font-weight: normal; font-style: normal; } /* a function name */ .fun { color: #000000; font-weight: bold; font-style: normal; } /* Specify class=linenums on a pre to get line numbering */ ol.linenums { margin-top: 0; margin-bottom: 0; } ================================================ FILE: docs/jsdoc/styles/prettify-tomorrow.css ================================================ /* Tomorrow Theme */ /* Original theme - https://github.com/chriskempson/tomorrow-theme */ /* Pretty printing styles. Used with prettify.js. */ /* SPAN elements with the classes below are added by prettyprint. */ /* plain text */ .pln { color: #4d4d4c; } @media screen { /* string content */ .str { color: #718c00; } /* a keyword */ .kwd { color: #8959a8; } /* a comment */ .com { color: #8e908c; } /* a type name */ .typ { color: #4271ae; } /* a literal value */ .lit { color: #f5871f; } /* punctuation */ .pun { color: #4d4d4c; } /* lisp open bracket */ .opn { color: #4d4d4c; } /* lisp close bracket */ .clo { color: #4d4d4c; } /* a markup tag name */ .tag { color: #c82829; } /* a markup attribute name */ .atn { color: #f5871f; } /* a markup attribute value */ .atv { color: #3e999f; } /* a declaration */ .dec { color: #f5871f; } /* a variable name */ .var { color: #c82829; } /* a function name */ .fun { color: #4271ae; } } /* Use higher contrast and text-weight for printable form. */ @media print, projection { .str { color: #060; } .kwd { color: #006; font-weight: bold; } .com { color: #600; font-style: italic; } .typ { color: #404; font-weight: bold; } .lit { color: #044; } .pun, .opn, .clo { color: #440; } .tag { color: #006; font-weight: bold; } .atn { color: #404; } .atv { color: #060; } } /* Style */ /* pre.prettyprint { background: white; font-family: Consolas, Monaco, 'Andale Mono', monospace; font-size: 12px; line-height: 1.5; border: 1px solid #ccc; padding: 10px; } */ /* Specify class=linenums on a pre to get line numbering */ ol.linenums { margin-top: 0; margin-bottom: 0; } /* IE indents via margin-left */ li.L0, li.L1, li.L2, li.L3, li.L4, li.L5, li.L6, li.L7, li.L8, li.L9 { /* */ } /* Alternate shading for lines */ li.L1, li.L3, li.L5, li.L7, li.L9 { /* */ } ================================================ FILE: docs/jsdoc/tuple.js.html ================================================ JSDoc: Source: tuple.js

Source: tuple.js

/*
 * Copyright 2014 Red Hat, Inc.
 *
 * Red Hat 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.
 */

/** @module reactive-pg-client-js/tuple */
var utils = require('vertx-js/util/utils');
var Json = require('reactive-pg-client-js/json');
var Buffer = require('vertx-js/buffer');

var io = Packages.io;
var JsonObject = io.vertx.core.json.JsonObject;
var JTuple = Java.type('io.reactiverse.pgclient.Tuple');
var Point = Java.type('io.reactiverse.pgclient.data.Point');
var Path = Java.type('io.reactiverse.pgclient.data.Path');
var Box = Java.type('io.reactiverse.pgclient.data.Box');
var Circle = Java.type('io.reactiverse.pgclient.data.Circle');
var Polygon = Java.type('io.reactiverse.pgclient.data.Polygon');
var Interval = Java.type('io.reactiverse.pgclient.data.Interval');
var LineSegment = Java.type('io.reactiverse.pgclient.data.LineSegment');
var Line = Java.type('io.reactiverse.pgclient.data.Line');

/**
 A general purpose tuple.

 @class
*/
var Tuple = function(j_val) {

  var j_tuple = j_val;
  var that = this;

  var __super_tuple = this.tuple;
  var __super_of = this.of;
  var __super_of = this.of;
  var __super_of = this.of;
  var __super_of = this.of;
  var __super_of = this.of;
  var __super_of = this.of;
  var __super_getBoolean = this.getBoolean;
  var __super_getValue = this.getValue;
  var __super_getShort = this.getShort;
  var __super_getInteger = this.getInteger;
  var __super_getLong = this.getLong;
  var __super_getFloat = this.getFloat;
  var __super_getDouble = this.getDouble;
  var __super_getString = this.getString;
  var __super_getJson = this.getJson;
  var __super_getPoint = this.getPoint;
  var __super_getLine = this.getLine;
  var __super_getLineSegment = this.getLineSegment;
  var __super_getBox = this.getBox;
  var __super_getPath = this.getPath;
  var __super_getPolygon = this.getPolygon;
  var __super_getCircle = this.getCircle;
  var __super_getInterval = this.getInterval;
  var __super_getBuffer = this.getBuffer;
  var __super_addBoolean = this.addBoolean;
  var __super_addValue = this.addValue;
  var __super_addShort = this.addShort;
  var __super_addInteger = this.addInteger;
  var __super_addLong = this.addLong;
  var __super_addFloat = this.addFloat;
  var __super_addDouble = this.addDouble;
  var __super_addString = this.addString;
  var __super_addJson = this.addJson;
  var __super_addBuffer = this.addBuffer;
  var __super_addPoint = this.addPoint;
  var __super_addLine = this.addLine;
  var __super_addLineSegment = this.addLineSegment;
  var __super_addBox = this.addBox;
  var __super_addPath = this.addPath;
  var __super_addPolygon = this.addPolygon;
  var __super_addCircle = this.addCircle;
  var __super_addInterval = this.addInterval;
  var __super_size = this.size;
  var __super_clear = this.clear;
  /**
   Get a boolean value at <code>pos</code>.

   @public
   @param pos {number} the position 
   @return {boolean} the value or <code>null</code>
   */
  this.getBoolean =  function(pos) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      return j_tuple["getBoolean(int)"](__args[0]) ;
    } else if (typeof __super_getBoolean != 'undefined') {
      return __super_getBoolean.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get an object value at <code>pos</code>.

   @public
   @param pos {number} the position 
   @return {Object} the value or <code>null</code>
   */
  this.getValue =  function(pos) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      return utils.convReturnTypeUnknown(j_tuple["getValue(int)"](__args[0])) ;
    } else if (typeof __super_getValue != 'undefined') {
      return __super_getValue.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get a short value at <code>pos</code>.

   @public
   @param pos {number} the position 
   @return {number} the value or <code>null</code>
   */
  this.getShort =  function(pos) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      return j_tuple["getShort(int)"](__args[0]) ;
    } else if (typeof __super_getShort != 'undefined') {
      return __super_getShort.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get an integer value at <code>pos</code>.

   @public
   @param pos {number} the position 
   @return {number} the value or <code>null</code>
   */
  this.getInteger =  function(pos) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      return j_tuple["getInteger(int)"](__args[0]) ;
    } else if (typeof __super_getInteger != 'undefined') {
      return __super_getInteger.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get a long value at <code>pos</code>.

   @public
   @param pos {number} the position 
   @return {number} the value or <code>null</code>
   */
  this.getLong =  function(pos) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      return utils.convReturnLong(j_tuple["getLong(int)"](__args[0])) ;
    } else if (typeof __super_getLong != 'undefined') {
      return __super_getLong.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get a float value at <code>pos</code>.

   @public
   @param pos {number} the position 
   @return {number} the value or <code>null</code>
   */
  this.getFloat =  function(pos) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      return j_tuple["getFloat(int)"](__args[0]) ;
    } else if (typeof __super_getFloat != 'undefined') {
      return __super_getFloat.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get a double value at <code>pos</code>.

   @public
   @param pos {number} the position 
   @return {number} the value or <code>null</code>
   */
  this.getDouble =  function(pos) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      return j_tuple["getDouble(int)"](__args[0]) ;
    } else if (typeof __super_getDouble != 'undefined') {
      return __super_getDouble.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get a string value at <code>pos</code>.

   @public
   @param pos {number} the position 
   @return {string} the value or <code>null</code>
   */
  this.getString =  function(pos) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      return j_tuple["getString(int)"](__args[0]) ;
    } else if (typeof __super_getString != 'undefined') {
      return __super_getString.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get a json value at <code>pos</code>.

   @public
   @param pos {number} the position 
   @return {Json} the value or <code>null</code>
   */
  this.getJson =  function(pos) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      return utils.convReturnVertxGen(Json, j_tuple["getJson(int)"](__args[0])) ;
    } else if (typeof __super_getJson != 'undefined') {
      return __super_getJson.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get  value at <code>pos</code>.

   @public
   @param pos {number} the position 
   @return {Object} the value or <code>null</code>
   */
  this.getPoint =  function(pos) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      return utils.convReturnDataObject(j_tuple["getPoint(int)"](__args[0])) ;
    } else if (typeof __super_getPoint != 'undefined') {
      return __super_getPoint.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get  value at <code>pos</code>.

   @public
   @param pos {number} the position 
   @return {Object} the value or <code>null</code>
   */
  this.getLine =  function(pos) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      return utils.convReturnDataObject(j_tuple["getLine(int)"](__args[0])) ;
    } else if (typeof __super_getLine != 'undefined') {
      return __super_getLine.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get  value at <code>pos</code>.

   @public
   @param pos {number} the position 
   @return {Object} the value or <code>null</code>
   */
  this.getLineSegment =  function(pos) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      return utils.convReturnDataObject(j_tuple["getLineSegment(int)"](__args[0])) ;
    } else if (typeof __super_getLineSegment != 'undefined') {
      return __super_getLineSegment.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get  value at <code>pos</code>.

   @public
   @param pos {number} the position 
   @return {Object} the value or <code>null</code>
   */
  this.getBox =  function(pos) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      return utils.convReturnDataObject(j_tuple["getBox(int)"](__args[0])) ;
    } else if (typeof __super_getBox != 'undefined') {
      return __super_getBox.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get  value at <code>pos</code>.

   @public
   @param pos {number} the position 
   @return {Object} the value or <code>null</code>
   */
  this.getPath =  function(pos) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      return utils.convReturnDataObject(j_tuple["getPath(int)"](__args[0])) ;
    } else if (typeof __super_getPath != 'undefined') {
      return __super_getPath.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get  value at <code>pos</code>.

   @public
   @param pos {number} the position 
   @return {Object} the value or <code>null</code>
   */
  this.getPolygon =  function(pos) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      return utils.convReturnDataObject(j_tuple["getPolygon(int)"](__args[0])) ;
    } else if (typeof __super_getPolygon != 'undefined') {
      return __super_getPolygon.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get  value at <code>pos</code>.

   @public
   @param pos {number} the position 
   @return {Object} the value or <code>null</code>
   */
  this.getCircle =  function(pos) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      return utils.convReturnDataObject(j_tuple["getCircle(int)"](__args[0])) ;
    } else if (typeof __super_getCircle != 'undefined') {
      return __super_getCircle.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get  value at <code>pos</code>.

   @public
   @param pos {number} the position 
   @return {Object} the value or <code>null</code>
   */
  this.getInterval =  function(pos) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      return utils.convReturnDataObject(j_tuple["getInterval(int)"](__args[0])) ;
    } else if (typeof __super_getInterval != 'undefined') {
      return __super_getInterval.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Get a buffer value at <code>pos</code>.

   @public
   @param pos {number} the position 
   @return {Buffer} the value or <code>null</code>
   */
  this.getBuffer =  function(pos) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      return utils.convReturnVertxGen(Buffer, j_tuple["getBuffer(int)"](__args[0])) ;
    } else if (typeof __super_getBuffer != 'undefined') {
      return __super_getBuffer.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Add a boolean value at the end of the tuple.

   @public
   @param value {boolean} the value 
   @return {Tuple} a reference to this, so the API can be used fluently
   */
  this.addBoolean =  function(value) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='boolean') {
      j_tuple["addBoolean(java.lang.Boolean)"](__args[0]) ;
      return that;
    } else if (typeof __super_addBoolean != 'undefined') {
      return __super_addBoolean.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Add an object value at the end of the tuple.

   @public
   @param value {Object} the value 
   @return {Tuple} a reference to this, so the API can be used fluently
   */
  this.addValue =  function(value) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] !== 'function') {
      j_tuple["addValue(java.lang.Object)"](utils.convParamTypeUnknown(__args[0])) ;
      return that;
    } else if (typeof __super_addValue != 'undefined') {
      return __super_addValue.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Add a short value at the end of the tuple.

   @public
   @param value {number} the value 
   @return {Tuple} a reference to this, so the API can be used fluently
   */
  this.addShort =  function(value) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      j_tuple["addShort(java.lang.Short)"](utils.convParamShort(__args[0])) ;
      return that;
    } else if (typeof __super_addShort != 'undefined') {
      return __super_addShort.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Add an integer value at the end of the tuple.

   @public
   @param value {number} the value 
   @return {Tuple} a reference to this, so the API can be used fluently
   */
  this.addInteger =  function(value) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      j_tuple["addInteger(java.lang.Integer)"](utils.convParamInteger(__args[0])) ;
      return that;
    } else if (typeof __super_addInteger != 'undefined') {
      return __super_addInteger.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Add a long value at the end of the tuple.

   @public
   @param value {number} the value 
   @return {Tuple} a reference to this, so the API can be used fluently
   */
  this.addLong =  function(value) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      j_tuple["addLong(java.lang.Long)"](utils.convParamLong(__args[0])) ;
      return that;
    } else if (typeof __super_addLong != 'undefined') {
      return __super_addLong.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Add a float value at the end of the tuple.

   @public
   @param value {number} the value 
   @return {Tuple} a reference to this, so the API can be used fluently
   */
  this.addFloat =  function(value) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      j_tuple["addFloat(java.lang.Float)"](utils.convParamFloat(__args[0])) ;
      return that;
    } else if (typeof __super_addFloat != 'undefined') {
      return __super_addFloat.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Add a double value at the end of the tuple.

   @public
   @param value {number} the value 
   @return {Tuple} a reference to this, so the API can be used fluently
   */
  this.addDouble =  function(value) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      j_tuple["addDouble(java.lang.Double)"](utils.convParamDouble(__args[0])) ;
      return that;
    } else if (typeof __super_addDouble != 'undefined') {
      return __super_addDouble.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Add a string value at the end of the tuple.

   @public
   @param value {string} the value 
   @return {Tuple} a reference to this, so the API can be used fluently
   */
  this.addString =  function(value) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'string') {
      j_tuple["addString(java.lang.String)"](__args[0]) ;
      return that;
    } else if (typeof __super_addString != 'undefined') {
      return __super_addString.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Add a json value at the end of the tuple.

   @public
   @param value {Json} the value 
   @return {Tuple} a reference to this, so the API can be used fluently
   */
  this.addJson =  function(value) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'object' && __args[0]._jdel) {
      j_tuple["addJson(io.reactiverse.pgclient.data.Json)"](__args[0]._jdel) ;
      return that;
    } else if (typeof __super_addJson != 'undefined') {
      return __super_addJson.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Add a buffer value at the end of the tuple.

   @public
   @param value {Buffer} the value 
   @return {Tuple} a reference to this, so the API can be used fluently
   */
  this.addBuffer =  function(value) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'object' && __args[0]._jdel) {
      j_tuple["addBuffer(io.vertx.core.buffer.Buffer)"](__args[0]._jdel) ;
      return that;
    } else if (typeof __super_addBuffer != 'undefined') {
      return __super_addBuffer.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Add a  value at the end of the tuple.

   @public
   @param value {Object} the value 
   @return {Tuple} a reference to this, so the API can be used fluently
   */
  this.addPoint =  function(value) {
    var __args = arguments;
    if (__args.length === 1 && (typeof __args[0] === 'object' && __args[0] != null)) {
      j_tuple["addPoint(io.reactiverse.pgclient.data.Point)"](__args[0]  != null ? new Point(new JsonObject(Java.asJSONCompatible(__args[0]))) : null) ;
      return that;
    } else if (typeof __super_addPoint != 'undefined') {
      return __super_addPoint.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Add a  value at the end of the tuple.

   @public
   @param value {Object} the value 
   @return {Tuple} a reference to this, so the API can be used fluently
   */
  this.addLine =  function(value) {
    var __args = arguments;
    if (__args.length === 1 && (typeof __args[0] === 'object' && __args[0] != null)) {
      j_tuple["addLine(io.reactiverse.pgclient.data.Line)"](__args[0]  != null ? new Line(new JsonObject(Java.asJSONCompatible(__args[0]))) : null) ;
      return that;
    } else if (typeof __super_addLine != 'undefined') {
      return __super_addLine.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Add a  value at the end of the tuple.

   @public
   @param value {Object} the value 
   @return {Tuple} a reference to this, so the API can be used fluently
   */
  this.addLineSegment =  function(value) {
    var __args = arguments;
    if (__args.length === 1 && (typeof __args[0] === 'object' && __args[0] != null)) {
      j_tuple["addLineSegment(io.reactiverse.pgclient.data.LineSegment)"](__args[0]  != null ? new LineSegment(new JsonObject(Java.asJSONCompatible(__args[0]))) : null) ;
      return that;
    } else if (typeof __super_addLineSegment != 'undefined') {
      return __super_addLineSegment.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Add a  value at the end of the tuple.

   @public
   @param value {Object} the value 
   @return {Tuple} a reference to this, so the API can be used fluently
   */
  this.addBox =  function(value) {
    var __args = arguments;
    if (__args.length === 1 && (typeof __args[0] === 'object' && __args[0] != null)) {
      j_tuple["addBox(io.reactiverse.pgclient.data.Box)"](__args[0]  != null ? new Box(new JsonObject(Java.asJSONCompatible(__args[0]))) : null) ;
      return that;
    } else if (typeof __super_addBox != 'undefined') {
      return __super_addBox.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Add a  value at the end of the tuple.

   @public
   @param value {Object} the value 
   @return {Tuple} a reference to this, so the API can be used fluently
   */
  this.addPath =  function(value) {
    var __args = arguments;
    if (__args.length === 1 && (typeof __args[0] === 'object' && __args[0] != null)) {
      j_tuple["addPath(io.reactiverse.pgclient.data.Path)"](__args[0]  != null ? new Path(new JsonObject(Java.asJSONCompatible(__args[0]))) : null) ;
      return that;
    } else if (typeof __super_addPath != 'undefined') {
      return __super_addPath.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Add a  value at the end of the tuple.

   @public
   @param value {Object} the value 
   @return {Tuple} a reference to this, so the API can be used fluently
   */
  this.addPolygon =  function(value) {
    var __args = arguments;
    if (__args.length === 1 && (typeof __args[0] === 'object' && __args[0] != null)) {
      j_tuple["addPolygon(io.reactiverse.pgclient.data.Polygon)"](__args[0]  != null ? new Polygon(new JsonObject(Java.asJSONCompatible(__args[0]))) : null) ;
      return that;
    } else if (typeof __super_addPolygon != 'undefined') {
      return __super_addPolygon.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Add a  value at the end of the tuple.

   @public
   @param value {Object} the value 
   @return {Tuple} a reference to this, so the API can be used fluently
   */
  this.addCircle =  function(value) {
    var __args = arguments;
    if (__args.length === 1 && (typeof __args[0] === 'object' && __args[0] != null)) {
      j_tuple["addCircle(io.reactiverse.pgclient.data.Circle)"](__args[0]  != null ? new Circle(new JsonObject(Java.asJSONCompatible(__args[0]))) : null) ;
      return that;
    } else if (typeof __super_addCircle != 'undefined') {
      return __super_addCircle.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**
   Add a  value at the end of the tuple.

   @public
   @param value {Object} the value 
   @return {Tuple} a reference to this, so the API can be used fluently
   */
  this.addInterval =  function(value) {
    var __args = arguments;
    if (__args.length === 1 && (typeof __args[0] === 'object' && __args[0] != null)) {
      j_tuple["addInterval(io.reactiverse.pgclient.data.Interval)"](__args[0]  != null ? new Interval(new JsonObject(Java.asJSONCompatible(__args[0]))) : null) ;
      return that;
    } else if (typeof __super_addInterval != 'undefined') {
      return __super_addInterval.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**

   @public

   @return {number} the tuple size
   */
  this.size =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      return j_tuple["size()"]() ;
    } else if (typeof __super_size != 'undefined') {
      return __super_size.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  /**

   @public

   */
  this.clear =  function() {
    var __args = arguments;
    if (__args.length === 0) {
      j_tuple["clear()"]();
    } else if (typeof __super_clear != 'undefined') {
      return __super_clear.apply(this, __args);
    }
    else throw new TypeError('function invoked with invalid arguments');
  };

  // A reference to the underlying Java delegate
  // NOTE! This is an internal API and must not be used in user code.
  // If you rely on this property your code is likely to break if we change it / remove it without warning.
  this._jdel = j_tuple;
};

Tuple._jclass = utils.getJavaClass("io.reactiverse.pgclient.Tuple");
Tuple._jtype = {accept: function(obj) {
    return Tuple._jclass.isInstance(obj._jdel);
  },wrap: function(jdel) {
    var obj = Object.create(Tuple.prototype, {});
    Tuple.apply(obj, arguments);
    return obj;
  },
  unwrap: function(obj) {
    return obj._jdel;
  }
};
Tuple._create = function(jdel) {var obj = Object.create(Tuple.prototype, {});
  Tuple.apply(obj, arguments);
  return obj;
}
/**

 @memberof module:reactive-pg-client-js/tuple

 @return {Tuple} a new empty tuple
 */
Tuple.tuple =  function() {
  var __args = arguments;
  if (__args.length === 0) {
    return utils.convReturnVertxGen(Tuple, JTuple["tuple()"]()) ;
  }else throw new TypeError('function invoked with invalid arguments');
};

/**
 Create a tuple of six elements.

 @memberof module:reactive-pg-client-js/tuple
 @param elt1 {Object} the first value 
 @param elt2 {Object} the second valueg 
 @param elt3 {Object} the third value 
 @param elt4 {Object} the fourth value 
 @param elt5 {Object} the fifth value 
 @param elt6 {Object} the sixth value 
 @return {Tuple} the tuple
 */
Tuple.of =  function() {
  var __args = arguments;
  if (__args.length === 1 && typeof __args[0] !== 'function') {
    return utils.convReturnVertxGen(Tuple, JTuple["of(java.lang.Object)"](utils.convParamTypeUnknown(__args[0]))) ;
  } else if (__args.length === 2 && typeof __args[0] !== 'function' && typeof __args[1] !== 'function') {
    return utils.convReturnVertxGen(Tuple, JTuple["of(java.lang.Object,java.lang.Object)"](utils.convParamTypeUnknown(__args[0]), utils.convParamTypeUnknown(__args[1]))) ;
  } else if (__args.length === 3 && typeof __args[0] !== 'function' && typeof __args[1] !== 'function' && typeof __args[2] !== 'function') {
    return utils.convReturnVertxGen(Tuple, JTuple["of(java.lang.Object,java.lang.Object,java.lang.Object)"](utils.convParamTypeUnknown(__args[0]), utils.convParamTypeUnknown(__args[1]), utils.convParamTypeUnknown(__args[2]))) ;
  } else if (__args.length === 4 && typeof __args[0] !== 'function' && typeof __args[1] !== 'function' && typeof __args[2] !== 'function' && typeof __args[3] !== 'function') {
    return utils.convReturnVertxGen(Tuple, JTuple["of(java.lang.Object,java.lang.Object,java.lang.Object,java.lang.Object)"](utils.convParamTypeUnknown(__args[0]), utils.convParamTypeUnknown(__args[1]), utils.convParamTypeUnknown(__args[2]), utils.convParamTypeUnknown(__args[3]))) ;
  } else if (__args.length === 5 && typeof __args[0] !== 'function' && typeof __args[1] !== 'function' && typeof __args[2] !== 'function' && typeof __args[3] !== 'function' && typeof __args[4] !== 'function') {
    return utils.convReturnVertxGen(Tuple, JTuple["of(java.lang.Object,java.lang.Object,java.lang.Object,java.lang.Object,java.lang.Object)"](utils.convParamTypeUnknown(__args[0]), utils.convParamTypeUnknown(__args[1]), utils.convParamTypeUnknown(__args[2]), utils.convParamTypeUnknown(__args[3]), utils.convParamTypeUnknown(__args[4]))) ;
  } else if (__args.length === 6 && typeof __args[0] !== 'function' && typeof __args[1] !== 'function' && typeof __args[2] !== 'function' && typeof __args[3] !== 'function' && typeof __args[4] !== 'function' && typeof __args[5] !== 'function') {
    return utils.convReturnVertxGen(Tuple, JTuple["of(java.lang.Object,java.lang.Object,java.lang.Object,java.lang.Object,java.lang.Object,java.lang.Object)"](utils.convParamTypeUnknown(__args[0]), utils.convParamTypeUnknown(__args[1]), utils.convParamTypeUnknown(__args[2]), utils.convParamTypeUnknown(__args[3]), utils.convParamTypeUnknown(__args[4]), utils.convParamTypeUnknown(__args[5]))) ;
  }else throw new TypeError('function invoked with invalid arguments');
};

module.exports = Tuple;

Documentation generated by JSDoc 3.3.2 on Fri Jan 25 2019 16:08:18 GMT+0100 (CET)
================================================ FILE: docs/yardoc/ReactivePgClient/Json.html ================================================ Class: ReactivePgClient::Json — Documentation by YARD 0.8.7.6

Class: ReactivePgClient::Json

Inherits:
Object
  • Object
show all
Defined in:
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/json.rb

Constant Summary

@@j_api_type =
Object.new

Class Method Summary (collapse)

Instance Method Summary (collapse)

Class Method Details

+ (Boolean) accept?(obj)

Returns:

  • (Boolean)


16
17
18
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/json.rb', line 16

def @@j_api_type.accept?(obj)
  obj.class == Json
end

+ (::ReactivePgClient::Json) create(value = nil)

Parameters:

  • value (Object) (defaults to: nil)

Returns:

Raises:

  • (ArgumentError)


33
34
35
36
37
38
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/json.rb', line 33

def self.create(value=nil)
  if ::Vertx::Util::unknown_type.accept?(value) && !block_given?
    return ::Vertx::Util::Utils.safe_create(Java::IoReactiversePgclientData::Json.java_method(:create, [Java::java.lang.Object.java_class]).call(::Vertx::Util::Utils.to_object(value)),::ReactivePgClient::Json)
  end
  raise ArgumentError, "Invalid arguments when calling create(#{value})"
end

+ (Object) j_api_type



25
26
27
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/json.rb', line 25

def self.j_api_type
  @@j_api_type
end

+ (Object) j_class



28
29
30
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/json.rb', line 28

def self.j_class
  Java::IoReactiversePgclientData::Json.java_class
end

+ (Object) unwrap(obj)



22
23
24
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/json.rb', line 22

def @@j_api_type.unwrap(obj)
  obj.j_del
end

+ (Object) wrap(obj)



19
20
21
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/json.rb', line 19

def @@j_api_type.wrap(obj)
  Json.new(obj)
end

Instance Method Details

- (Object) value

Returns:

  • (Object)

Raises:

  • (ArgumentError)


40
41
42
43
44
45
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/json.rb', line 40

def value
  if !block_given?
    return ::Vertx::Util::Utils.from_object(@j_del.java_method(:value, []).call())
  end
  raise ArgumentError, "Invalid arguments when calling value()"
end
================================================ FILE: docs/yardoc/ReactivePgClient/PgChannel.html ================================================ Class: ReactivePgClient::PgChannel — Documentation by YARD 0.8.7.6

Class: ReactivePgClient::PgChannel

Inherits:
Object
  • Object
show all
Includes:
Vertx::ReadStream
Defined in:
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_channel.rb

Overview

A channel to Postgres that tracks the subscription to a given Postgres channel using the LISTEN/UNLISTEN commands.

When paused the channel discards the messages.

Constant Summary

@@j_api_type =
Object.new

Class Method Summary (collapse)

Instance Method Summary (collapse)

Class Method Details

+ (Boolean) accept?(obj)

Returns:

  • (Boolean)


21
22
23
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_channel.rb', line 21

def @@j_api_type.accept?(obj)
  obj.class == PgChannel
end

+ (Object) j_api_type



30
31
32
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_channel.rb', line 30

def self.j_api_type
  @@j_api_type
end

+ (Object) j_class



33
34
35
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_channel.rb', line 33

def self.j_class
  Java::IoReactiversePgclientPubsub::PgChannel.java_class
end

+ (Object) unwrap(obj)



27
28
29
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_channel.rb', line 27

def @@j_api_type.unwrap(obj)
  obj.j_del
end

+ (Object) wrap(obj)



24
25
26
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_channel.rb', line 24

def @@j_api_type.wrap(obj)
  PgChannel.new(obj)
end

Instance Method Details

- (self) end_handler { ... }

Set an handler to be called when no more notifications will be received.

Yields:

  • the handler

Returns:

  • (self)

Raises:

  • (ArgumentError)


91
92
93
94
95
96
97
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_channel.rb', line 91

def end_handler
  if block_given?
    @j_del.java_method(:endHandler, [Java::IoVertxCore::Handler.java_class]).call(Proc.new { yield })
    return self
  end
  raise ArgumentError, "Invalid arguments when calling end_handler()"
end

- (self) exception_handler { ... }

Yields:

Returns:

  • (self)

Raises:

  • (ArgumentError)


100
101
102
103
104
105
106
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_channel.rb', line 100

def exception_handler
  if block_given?
    @j_del.java_method(:exceptionHandler, [Java::IoVertxCore::Handler.java_class]).call((Proc.new { |event| yield(::Vertx::Util::Utils.from_throwable(event)) }))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling exception_handler()"
end

- (self) fetch(arg0 = nil)

Parameters:

  • arg0 (Fixnum) (defaults to: nil)

Returns:

  • (self)

Raises:

  • (ArgumentError)


38
39
40
41
42
43
44
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_channel.rb', line 38

def fetch(arg0=nil)
  if arg0.class == Fixnum && !block_given?
    @j_del.java_method(:fetch, [Java::long.java_class]).call(arg0)
    return self
  end
  raise ArgumentError, "Invalid arguments when calling fetch(#{arg0})"
end

- (self) handler { ... }

Set or unset an handler to be called when a the channel is notified by Postgres.

  • when the handler is set, the subscriber sends a LISTEN command if needed
  • when the handler is unset, the subscriber sends a UNLISTEN command if needed

Yields:

  • the handler

Returns:

  • (self)

Raises:

  • (ArgumentError)


63
64
65
66
67
68
69
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_channel.rb', line 63

def handler
  if block_given?
    @j_del.java_method(:handler, [Java::IoVertxCore::Handler.java_class]).call((Proc.new { |event| yield(event) }))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling handler()"
end

- (self) pause

Pause the channel, all notifications are discarded.

Returns:

  • (self)

Raises:

  • (ArgumentError)


72
73
74
75
76
77
78
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_channel.rb', line 72

def pause
  if !block_given?
    @j_del.java_method(:pause, []).call()
    return self
  end
  raise ArgumentError, "Invalid arguments when calling pause()"
end

- (self) resume

Resume the channel.

Returns:

  • (self)

Raises:

  • (ArgumentError)


81
82
83
84
85
86
87
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_channel.rb', line 81

def resume
  if !block_given?
    @j_del.java_method(:resume, []).call()
    return self
  end
  raise ArgumentError, "Invalid arguments when calling resume()"
end

- (self) subscribe_handler { ... }

Set an handler called when the the channel get subscribed.

Yields:

  • the handler

Returns:

  • (self)

Raises:

  • (ArgumentError)


48
49
50
51
52
53
54
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_channel.rb', line 48

def subscribe_handler
  if block_given?
    @j_del.java_method(:subscribeHandler, [Java::IoVertxCore::Handler.java_class]).call(Proc.new { yield })
    return self
  end
  raise ArgumentError, "Invalid arguments when calling subscribe_handler()"
end
================================================ FILE: docs/yardoc/ReactivePgClient/PgClient.html ================================================ Class: ReactivePgClient::PgClient — Documentation by YARD 0.8.7.6

Class: ReactivePgClient::PgClient

Inherits:
Object
  • Object
show all
Defined in:
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_client.rb

Overview

Defines the client operations with a Postgres Database.

Direct Known Subclasses

PgConnection, PgPool, PgTransaction

Constant Summary

@@j_api_type =
Object.new

Class Method Summary (collapse)

Instance Method Summary (collapse)

Class Method Details

+ (Boolean) accept?(obj)

Returns:

  • (Boolean)


22
23
24
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_client.rb', line 22

def @@j_api_type.accept?(obj)
  obj.class == PgClient
end

+ (void) connect(vertx, handler) { ... } + (void) connect(vertx, options, handler) { ... } + (void) connect(vertx, connectionUri, handler) { ... }

This method returns an undefined value.

Like #connect with options build from connectionUri.

Overloads:

  • + (void) connect(vertx, handler) { ... }

    Parameters:

    • vertx (::Vertx::Vertx)

    Yields:

  • + (void) connect(vertx, options, handler) { ... }

    Parameters:

    • vertx (::Vertx::Vertx)
      the vertx instance
    • options (Hash)
      the connect options

    Yields:

    • the handler called with the connection or the failure
  • + (void) connect(vertx, connectionUri, handler) { ... }

    Parameters:

    • vertx (::Vertx::Vertx)
    • connectionUri (String)

    Yields:

Raises:

  • (ArgumentError)


81
82
83
84
85
86
87
88
89
90
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_client.rb', line 81

def self.connect(param_1=nil,param_2=nil)
  if param_1.class.method_defined?(:j_del) && block_given? && param_2 == nil
    return Java::IoReactiversePgclient::PgClient.java_method(:connect, [Java::IoVertxCore::Vertx.java_class,Java::IoVertxCore::Handler.java_class]).call(param_1.j_del,(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgConnection) : nil) }))
  elsif param_1.class.method_defined?(:j_del) && param_2.class == Hash && block_given?
    return Java::IoReactiversePgclient::PgClient.java_method(:connect, [Java::IoVertxCore::Vertx.java_class,Java::IoReactiversePgclient::PgConnectOptions.java_class,Java::IoVertxCore::Handler.java_class]).call(param_1.j_del,Java::IoReactiversePgclient::PgConnectOptions.new(::Vertx::Util::Utils.to_json_object(param_2)),(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgConnection) : nil) }))
  elsif param_1.class.method_defined?(:j_del) && param_2.class == String && block_given?
    return Java::IoReactiversePgclient::PgClient.java_method(:connect, [Java::IoVertxCore::Vertx.java_class,Java::java.lang.String.java_class,Java::IoVertxCore::Handler.java_class]).call(param_1.j_del,param_2,(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgConnection) : nil) }))
  end
  raise ArgumentError, "Invalid arguments when calling connect(#{param_1},#{param_2})"
end

+ (Object) j_api_type



31
32
33
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_client.rb', line 31

def self.j_api_type
  @@j_api_type
end

+ (Object) j_class



34
35
36
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_client.rb', line 34

def self.j_class
  Java::IoReactiversePgclient::PgClient.java_class
end

+ (::ReactivePgClient::PgPool) pool + (::ReactivePgClient::PgPool) pool(connectionUri) + (::ReactivePgClient::PgPool) pool(vertx) + (::ReactivePgClient::PgPool) pool(options) + (::ReactivePgClient::PgPool) pool(vertx, connectionUri) + (::ReactivePgClient::PgPool) pool(vertx, options)

Like #pool with a specific instance.

Overloads:

Returns:

Raises:

  • (ArgumentError)


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_client.rb', line 52

def self.pool(param_1=nil,param_2=nil)
  if !block_given? && param_1 == nil && param_2 == nil
    return ::Vertx::Util::Utils.safe_create(Java::IoReactiversePgclient::PgClient.java_method(:pool, []).call(),::ReactivePgClient::PgPool)
  elsif param_1.class == String && !block_given? && param_2 == nil
    return ::Vertx::Util::Utils.safe_create(Java::IoReactiversePgclient::PgClient.java_method(:pool, [Java::java.lang.String.java_class]).call(param_1),::ReactivePgClient::PgPool)
  elsif param_1.class.method_defined?(:j_del) && !block_given? && param_2 == nil
    return ::Vertx::Util::Utils.safe_create(Java::IoReactiversePgclient::PgClient.java_method(:pool, [Java::IoVertxCore::Vertx.java_class]).call(param_1.j_del),::ReactivePgClient::PgPool)
  elsif param_1.class == Hash && !block_given? && param_2 == nil
    return ::Vertx::Util::Utils.safe_create(Java::IoReactiversePgclient::PgClient.java_method(:pool, [Java::IoReactiversePgclient::PgPoolOptions.java_class]).call(Java::IoReactiversePgclient::PgPoolOptions.new(::Vertx::Util::Utils.to_json_object(param_1))),::ReactivePgClient::PgPool)
  elsif param_1.class.method_defined?(:j_del) && param_2.class == String && !block_given?
    return ::Vertx::Util::Utils.safe_create(Java::IoReactiversePgclient::PgClient.java_method(:pool, [Java::IoVertxCore::Vertx.java_class,Java::java.lang.String.java_class]).call(param_1.j_del,param_2),::ReactivePgClient::PgPool)
  elsif param_1.class.method_defined?(:j_del) && param_2.class == Hash && !block_given?
    return ::Vertx::Util::Utils.safe_create(Java::IoReactiversePgclient::PgClient.java_method(:pool, [Java::IoVertxCore::Vertx.java_class,Java::IoReactiversePgclient::PgPoolOptions.java_class]).call(param_1.j_del,Java::IoReactiversePgclient::PgPoolOptions.new(::Vertx::Util::Utils.to_json_object(param_2))),::ReactivePgClient::PgPool)
  end
  raise ArgumentError, "Invalid arguments when calling pool(#{param_1},#{param_2})"
end

+ (Object) unwrap(obj)



28
29
30
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_client.rb', line 28

def @@j_api_type.unwrap(obj)
  obj.j_del
end

+ (Object) wrap(obj)



25
26
27
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_client.rb', line 25

def @@j_api_type.wrap(obj)
  PgClient.new(obj)
end

Instance Method Details

- (self) prepared_batch(sql = nil, batch = nil) { ... }

Prepare and execute a createBatch.

Parameters:

  • sql (String) (defaults to: nil)
    the prepared query SQL
  • batch (Array<::ReactivePgClient::Tuple>) (defaults to: nil)
    the batch of tuples

Yields:

  • the handler notified with the execution result

Returns:

  • (self)

Raises:

  • (ArgumentError)


122
123
124
125
126
127
128
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_client.rb', line 122

def prepared_batch(sql=nil,batch=nil)
  if sql.class == String && batch.class == Array && block_given?
    @j_del.java_method(:preparedBatch, [Java::java.lang.String.java_class,Java::JavaUtil::List.java_class,Java::IoVertxCore::Handler.java_class]).call(sql,batch.map { |element| element.j_del },(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgRowSet) : nil) }))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling prepared_batch(#{sql},#{batch})"
end

- (self) prepared_query(sql = nil, arguments = nil) { ... }

Prepare and execute a query.

Parameters:

  • sql (String) (defaults to: nil)
    the prepared query SQL
  • arguments (::ReactivePgClient::Tuple) (defaults to: nil)
    the list of arguments

Yields:

  • the handler notified with the execution result

Returns:

  • (self)

Raises:

  • (ArgumentError)


107
108
109
110
111
112
113
114
115
116
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_client.rb', line 107

def prepared_query(sql=nil,arguments=nil)
  if sql.class == String && block_given? && arguments == nil
    @j_del.java_method(:preparedQuery, [Java::java.lang.String.java_class,Java::IoVertxCore::Handler.java_class]).call(sql,(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgRowSet) : nil) }))
    return self
  elsif sql.class == String && arguments.class.method_defined?(:j_del) && block_given?
    @j_del.java_method(:preparedQuery, [Java::java.lang.String.java_class,Java::IoReactiversePgclient::Tuple.java_class,Java::IoVertxCore::Handler.java_class]).call(sql,arguments.j_del,(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgRowSet) : nil) }))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling prepared_query(#{sql},#{arguments})"
end

- (self) query(sql = nil) { ... }

Execute a simple query.

Parameters:

  • sql (String) (defaults to: nil)
    the query SQL

Yields:

  • the handler notified with the execution result

Returns:

  • (self)

Raises:

  • (ArgumentError)


95
96
97
98
99
100
101
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_client.rb', line 95

def query(sql=nil)
  if sql.class == String && block_given?
    @j_del.java_method(:query, [Java::java.lang.String.java_class,Java::IoVertxCore::Handler.java_class]).call(sql,(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgRowSet) : nil) }))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling query(#{sql})"
end
================================================ FILE: docs/yardoc/ReactivePgClient/PgConnection.html ================================================ Class: ReactivePgClient::PgConnection — Documentation by YARD 0.8.7.6

Class: ReactivePgClient::PgConnection

Inherits:
PgClient
  • Object
show all
Defined in:
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_connection.rb

Overview

A connection to Postgres.

Constant Summary

@@j_api_type =
Object.new

Class Method Summary (collapse)

Instance Method Summary (collapse)

Methods inherited from PgClient

connect, pool

Class Method Details

+ (Boolean) accept?(obj)

Returns:

  • (Boolean)


23
24
25
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_connection.rb', line 23

def @@j_api_type.accept?(obj)
  obj.class == PgConnection
end

+ (Object) j_api_type



32
33
34
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_connection.rb', line 32

def self.j_api_type
  @@j_api_type
end

+ (Object) j_class



35
36
37
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_connection.rb', line 35

def self.j_class
  Java::IoReactiversePgclient::PgConnection.java_class
end

+ (Object) unwrap(obj)



29
30
31
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_connection.rb', line 29

def @@j_api_type.unwrap(obj)
  obj.j_del
end

+ (Object) wrap(obj)



26
27
28
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_connection.rb', line 26

def @@j_api_type.wrap(obj)
  PgConnection.new(obj)
end

Instance Method Details

- (::ReactivePgClient::PgTransaction) begin

Begin a transaction and returns a ReactivePgClient::PgTransaction for controlling and tracking this transaction.

When the connection is explicitely closed, any inflight transaction is rollbacked.

Returns:

Raises:

  • (ArgumentError)


74
75
76
77
78
79
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_connection.rb', line 74

def begin
  if !block_given?
    return ::Vertx::Util::Utils.safe_create(@j_del.java_method(:begin, []).call(),::ReactivePgClient::PgTransaction)
  end
  raise ArgumentError, "Invalid arguments when calling begin()"
end

- (::ReactivePgClient::PgConnection) cancel_request { ... }

Send a request cancellation message to tell the server to cancel processing request in this connection.
Note: Use this with caution because the cancellation signal may or may not have any effect.

Yields:

  • the handler notified if cancelling request is sent

Returns:

Raises:

  • (ArgumentError)


111
112
113
114
115
116
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_connection.rb', line 111

def cancel_request
  if block_given?
    return ::Vertx::Util::Utils.safe_create(@j_del.java_method(:cancelRequest, [Java::IoVertxCore::Handler.java_class]).call((Proc.new { |ar| yield(ar.failed ? ar.cause : nil) })),::ReactivePgClient::PgConnection)
  end
  raise ArgumentError, "Invalid arguments when calling cancel_request()"
end

- (void) close

This method returns an undefined value.

Close the current connection after all the pending commands have been processed.

Raises:

  • (ArgumentError)


126
127
128
129
130
131
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_connection.rb', line 126

def close
  if !block_given?
    return @j_del.java_method(:close, []).call()
  end
  raise ArgumentError, "Invalid arguments when calling close()"
end

- (self) close_handler { ... }

Set an handler called when the connection is closed.

Yields:

  • the handler

Returns:

  • (self)

Raises:

  • (ArgumentError)


62
63
64
65
66
67
68
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_connection.rb', line 62

def close_handler
  if block_given?
    @j_del.java_method(:closeHandler, [Java::IoVertxCore::Handler.java_class]).call(Proc.new { yield })
    return self
  end
  raise ArgumentError, "Invalid arguments when calling close_handler()"
end

- (self) exception_handler { ... }

Set an handler called with connection errors.

Yields:

  • the handler

Returns:

  • (self)

Raises:

  • (ArgumentError)


52
53
54
55
56
57
58
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_connection.rb', line 52

def exception_handler
  if block_given?
    @j_del.java_method(:exceptionHandler, [Java::IoVertxCore::Handler.java_class]).call((Proc.new { |event| yield(::Vertx::Util::Utils.from_throwable(event)) }))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling exception_handler()"
end

- (self) notification_handler { ... }

Set an handler called when the connection receives notification on a channel.

The handler is called with the Hash and has access to the channel name and the notification payload.

Yields:

  • the handler

Returns:

  • (self)

Raises:

  • (ArgumentError)


86
87
88
89
90
91
92
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_connection.rb', line 86

def notification_handler
  if block_given?
    @j_del.java_method(:notificationHandler, [Java::IoVertxCore::Handler.java_class]).call((Proc.new { |event| yield(event != nil ? JSON.parse(event.toJson.encode) : nil) }))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling notification_handler()"
end

- (self) prepare(sql = nil) { ... }

Create a prepared query.

Parameters:

  • sql (String) (defaults to: nil)
    the sql

Yields:

  • the handler notified with the prepared query asynchronously

Returns:

  • (self)

Raises:

  • (ArgumentError)


42
43
44
45
46
47
48
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_connection.rb', line 42

def prepare(sql=nil)
  if sql.class == String && block_given?
    @j_del.java_method(:prepare, [Java::java.lang.String.java_class,Java::IoVertxCore::Handler.java_class]).call(sql,(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgPreparedQuery) : nil) }))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling prepare(#{sql})"
end

- (self) prepared_batch(sql = nil, batch = nil) { ... }

Parameters:

Yields:

Returns:

  • (self)

Raises:

  • (ArgumentError)


160
161
162
163
164
165
166
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_connection.rb', line 160

def prepared_batch(sql=nil,batch=nil)
  if sql.class == String && batch.class == Array && block_given?
    @j_del.java_method(:preparedBatch, [Java::java.lang.String.java_class,Java::JavaUtil::List.java_class,Java::IoVertxCore::Handler.java_class]).call(sql,batch.map { |element| element.j_del },(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgRowSet) : nil) }))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling prepared_batch(#{sql},#{batch})"
end

- (self) prepared_query(sql = nil, arguments = nil) { ... }

Parameters:

Yields:

Returns:

  • (self)

Raises:

  • (ArgumentError)


136
137
138
139
140
141
142
143
144
145
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_connection.rb', line 136

def prepared_query(sql=nil,arguments=nil)
  if sql.class == String && block_given? && arguments == nil
    @j_del.java_method(:preparedQuery, [Java::java.lang.String.java_class,Java::IoVertxCore::Handler.java_class]).call(sql,(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgRowSet) : nil) }))
    return self
  elsif sql.class == String && arguments.class.method_defined?(:j_del) && block_given?
    @j_del.java_method(:preparedQuery, [Java::java.lang.String.java_class,Java::IoReactiversePgclient::Tuple.java_class,Java::IoVertxCore::Handler.java_class]).call(sql,arguments.j_del,(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgRowSet) : nil) }))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling prepared_query(#{sql},#{arguments})"
end

- (Fixnum) process_id

Returns The process ID of the target backend

Returns:

  • (Fixnum)
    The process ID of the target backend

Raises:

  • (ArgumentError)


94
95
96
97
98
99
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_connection.rb', line 94

def process_id
  if !block_given?
    return @j_del.java_method(:processId, []).call()
  end
  raise ArgumentError, "Invalid arguments when calling process_id()"
end

- (self) query(sql = nil) { ... }

Parameters:

  • sql (String) (defaults to: nil)

Yields:

Returns:

  • (self)

Raises:

  • (ArgumentError)


149
150
151
152
153
154
155
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_connection.rb', line 149

def query(sql=nil)
  if sql.class == String && block_given?
    @j_del.java_method(:query, [Java::java.lang.String.java_class,Java::IoVertxCore::Handler.java_class]).call(sql,(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgRowSet) : nil) }))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling query(#{sql})"
end

- (Fixnum) secret_key

Returns The secret key for the target backend

Returns:

  • (Fixnum)
    The secret key for the target backend

Raises:

  • (ArgumentError)


101
102
103
104
105
106
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_connection.rb', line 101

def secret_key
  if !block_given?
    return @j_del.java_method(:secretKey, []).call()
  end
  raise ArgumentError, "Invalid arguments when calling secret_key()"
end

- (true, false) ssl?

Returns whether the connection uses SSL

Returns:

  • (true, false)
    whether the connection uses SSL

Raises:

  • (ArgumentError)


118
119
120
121
122
123
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_connection.rb', line 118

def ssl?
  if !block_given?
    return @j_del.java_method(:isSSL, []).call()
  end
  raise ArgumentError, "Invalid arguments when calling ssl?()"
end
================================================ FILE: docs/yardoc/ReactivePgClient/PgCursor.html ================================================ Class: ReactivePgClient::PgCursor — Documentation by YARD 0.8.7.6

Class: ReactivePgClient::PgCursor

Inherits:
Object
  • Object
show all
Defined in:
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_cursor.rb

Overview

A cursor that reads progressively the rows from Postgres, it is usefull for reading very large result.

Constant Summary

@@j_api_type =
Object.new

Class Method Summary (collapse)

Instance Method Summary (collapse)

Class Method Details

+ (Boolean) accept?(obj)

Returns:

  • (Boolean)


18
19
20
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_cursor.rb', line 18

def @@j_api_type.accept?(obj)
  obj.class == PgCursor
end

+ (Object) j_api_type



27
28
29
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_cursor.rb', line 27

def self.j_api_type
  @@j_api_type
end

+ (Object) j_class



30
31
32
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_cursor.rb', line 30

def self.j_class
  Java::IoReactiversePgclient::PgCursor.java_class
end

+ (Object) unwrap(obj)



24
25
26
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_cursor.rb', line 24

def @@j_api_type.unwrap(obj)
  obj.j_del
end

+ (Object) wrap(obj)



21
22
23
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_cursor.rb', line 21

def @@j_api_type.wrap(obj)
  PgCursor.new(obj)
end

Instance Method Details

- (void) close { ... }

This method returns an undefined value.

Like #close but with a completionHandler called when the cursor has been released.

Yields:

Raises:

  • (ArgumentError)


55
56
57
58
59
60
61
62
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_cursor.rb', line 55

def close
  if !block_given?
    return @j_del.java_method(:close, []).call()
  elsif block_given?
    return @j_del.java_method(:close, [Java::IoVertxCore::Handler.java_class]).call((Proc.new { |ar| yield(ar.failed ? ar.cause : nil) }))
  end
  raise ArgumentError, "Invalid arguments when calling close()"
end

- (true, false) has_more?

Returns true when the cursor has results in progress and the should be called to retrieve them.

Returns:

  • (true, false)
    whether the cursor has more results,

Raises:

  • (ArgumentError)


46
47
48
49
50
51
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_cursor.rb', line 46

def has_more?
  if !block_given?
    return @j_del.java_method(:hasMore, []).call()
  end
  raise ArgumentError, "Invalid arguments when calling has_more?()"
end

- (void) read(count = nil) { ... }

This method returns an undefined value.

Read rows from the cursor, the result is provided asynchronously to the handler.

Parameters:

  • count (Fixnum) (defaults to: nil)
    the amount of rows to read

Yields:

  • the handler for the result

Raises:

  • (ArgumentError)


37
38
39
40
41
42
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_cursor.rb', line 37

def read(count=nil)
  if count.class == Fixnum && block_given?
    return @j_del.java_method(:read, [Java::int.java_class,Java::IoVertxCore::Handler.java_class]).call(count,(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgRowSet) : nil) }))
  end
  raise ArgumentError, "Invalid arguments when calling read(#{count})"
end
================================================ FILE: docs/yardoc/ReactivePgClient/PgIterator.html ================================================ Class: ReactivePgClient::PgIterator — Documentation by YARD 0.8.7.6

Class: ReactivePgClient::PgIterator

Inherits:
Object
  • Object
show all
Defined in:
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_iterator.rb

Overview

An iterator for processing postgres items synchronously.

Constant Summary

@@j_api_type =
Object.new

Class Method Summary (collapse)

Instance Method Summary (collapse)

Class Method Details

+ (Boolean) accept?(obj)

Returns:

  • (Boolean)


18
19
20
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_iterator.rb', line 18

def @@j_api_type.accept?(obj)
  obj.class == PgIterator
end

+ (Object) j_api_type



27
28
29
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_iterator.rb', line 27

def self.j_api_type
  @@j_api_type
end

+ (Object) j_class



30
31
32
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_iterator.rb', line 30

def self.j_class
  Java::IoReactiversePgclient::PgIterator.java_class
end

+ (Object) unwrap(obj)



24
25
26
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_iterator.rb', line 24

def @@j_api_type.unwrap(obj)
  obj.j_del
end

+ (Object) wrap(obj)



21
22
23
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_iterator.rb', line 21

def @@j_api_type.wrap(obj)
  PgIterator.new(obj)
end

Instance Method Details

- (true, false) has_next?

Returns:

  • (true, false)

Raises:

  • (ArgumentError)


34
35
36
37
38
39
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_iterator.rb', line 34

def has_next?
  if !block_given?
    return @j_del.java_method(:hasNext, []).call()
  end
  raise ArgumentError, "Invalid arguments when calling has_next?()"
end

- (::ReactivePgClient::Row) next

Returns:

Raises:

  • (ArgumentError)


41
42
43
44
45
46
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_iterator.rb', line 41

def next
  if !block_given?
    return ::Vertx::Util::Utils.safe_create(@j_del.java_method(:next, []).call(),::ReactivePgClient::Row)
  end
  raise ArgumentError, "Invalid arguments when calling next()"
end
================================================ FILE: docs/yardoc/ReactivePgClient/PgPool.html ================================================ Class: ReactivePgClient::PgPool — Documentation by YARD 0.8.7.6

Class: ReactivePgClient::PgPool

Inherits:
PgClient
  • Object
show all
Defined in:
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_pool.rb

Overview

A pool of connection.

Constant Summary

@@j_api_type =
Object.new

Class Method Summary (collapse)

Instance Method Summary (collapse)

Methods inherited from PgClient

connect, pool

Class Method Details

+ (Boolean) accept?(obj)

Returns:

  • (Boolean)


23
24
25
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_pool.rb', line 23

def @@j_api_type.accept?(obj)
  obj.class == PgPool
end

+ (Object) j_api_type



32
33
34
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_pool.rb', line 32

def self.j_api_type
  @@j_api_type
end

+ (Object) j_class



35
36
37
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_pool.rb', line 35

def self.j_class
  Java::IoReactiversePgclient::PgPool.java_class
end

+ (Object) unwrap(obj)



29
30
31
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_pool.rb', line 29

def @@j_api_type.unwrap(obj)
  obj.j_del
end

+ (Object) wrap(obj)



26
27
28
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_pool.rb', line 26

def @@j_api_type.wrap(obj)
  PgPool.new(obj)
end

Instance Method Details

- (void) begin { ... }

This method returns an undefined value.

Borrow a connection from the pool and begin a transaction, the underlying connection will be returned to the pool when the transaction ends.

Yields:

Raises:

  • (ArgumentError)


86
87
88
89
90
91
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_pool.rb', line 86

def begin
  if block_given?
    return @j_del.java_method(:begin, [Java::IoVertxCore::Handler.java_class]).call((Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgTransaction) : nil) }))
  end
  raise ArgumentError, "Invalid arguments when calling begin()"
end

- (void) close

This method returns an undefined value.

Close the pool and release the associated resources.

Raises:

  • (ArgumentError)


94
95
96
97
98
99
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_pool.rb', line 94

def close
  if !block_given?
    return @j_del.java_method(:close, []).call()
  end
  raise ArgumentError, "Invalid arguments when calling close()"
end

- (void) get_connection { ... }

This method returns an undefined value.

Get a connection from the pool.

Yields:

  • the handler that will get the connection result

Raises:

  • (ArgumentError)


76
77
78
79
80
81
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_pool.rb', line 76

def get_connection
  if block_given?
    return @j_del.java_method(:getConnection, [Java::IoVertxCore::Handler.java_class]).call((Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgConnection) : nil) }))
  end
  raise ArgumentError, "Invalid arguments when calling get_connection()"
end

- (self) prepared_batch(sql = nil, batch = nil) { ... }

Parameters:

Yields:

Returns:

  • (self)

Raises:

  • (ArgumentError)


66
67
68
69
70
71
72
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_pool.rb', line 66

def prepared_batch(sql=nil,batch=nil)
  if sql.class == String && batch.class == Array && block_given?
    @j_del.java_method(:preparedBatch, [Java::java.lang.String.java_class,Java::JavaUtil::List.java_class,Java::IoVertxCore::Handler.java_class]).call(sql,batch.map { |element| element.j_del },(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgRowSet) : nil) }))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling prepared_batch(#{sql},#{batch})"
end

- (self) prepared_query(sql = nil, arguments = nil) { ... }

Parameters:

Yields:

Returns:

  • (self)

Raises:

  • (ArgumentError)


42
43
44
45
46
47
48
49
50
51
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_pool.rb', line 42

def prepared_query(sql=nil,arguments=nil)
  if sql.class == String && block_given? && arguments == nil
    @j_del.java_method(:preparedQuery, [Java::java.lang.String.java_class,Java::IoVertxCore::Handler.java_class]).call(sql,(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgRowSet) : nil) }))
    return self
  elsif sql.class == String && arguments.class.method_defined?(:j_del) && block_given?
    @j_del.java_method(:preparedQuery, [Java::java.lang.String.java_class,Java::IoReactiversePgclient::Tuple.java_class,Java::IoVertxCore::Handler.java_class]).call(sql,arguments.j_del,(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgRowSet) : nil) }))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling prepared_query(#{sql},#{arguments})"
end

- (self) query(sql = nil) { ... }

Parameters:

  • sql (String) (defaults to: nil)

Yields:

Returns:

  • (self)

Raises:

  • (ArgumentError)


55
56
57
58
59
60
61
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_pool.rb', line 55

def query(sql=nil)
  if sql.class == String && block_given?
    @j_del.java_method(:query, [Java::java.lang.String.java_class,Java::IoVertxCore::Handler.java_class]).call(sql,(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgRowSet) : nil) }))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling query(#{sql})"
end
================================================ FILE: docs/yardoc/ReactivePgClient/PgPreparedQuery.html ================================================ Class: ReactivePgClient::PgPreparedQuery — Documentation by YARD 0.8.7.6

Class: ReactivePgClient::PgPreparedQuery

Inherits:
Object
  • Object
show all
Defined in:
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_prepared_query.rb

Overview

A prepared query.

Constant Summary

@@j_api_type =
Object.new

Class Method Summary (collapse)

Instance Method Summary (collapse)

Class Method Details

+ (Boolean) accept?(obj)

Returns:

  • (Boolean)


22
23
24
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_prepared_query.rb', line 22

def @@j_api_type.accept?(obj)
  obj.class == PgPreparedQuery
end

+ (Object) j_api_type



31
32
33
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_prepared_query.rb', line 31

def self.j_api_type
  @@j_api_type
end

+ (Object) j_class



34
35
36
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_prepared_query.rb', line 34

def self.j_class
  Java::IoReactiversePgclient::PgPreparedQuery.java_class
end

+ (Object) unwrap(obj)



28
29
30
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_prepared_query.rb', line 28

def @@j_api_type.unwrap(obj)
  obj.j_del
end

+ (Object) wrap(obj)



25
26
27
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_prepared_query.rb', line 25

def @@j_api_type.wrap(obj)
  PgPreparedQuery.new(obj)
end

Instance Method Details

- (self) batch(argsList = nil) { ... }

Execute a batch.

Parameters:

Yields:

Returns:

  • (self)

Raises:

  • (ArgumentError)


79
80
81
82
83
84
85
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_prepared_query.rb', line 79

def batch(argsList=nil)
  if argsList.class == Array && block_given?
    @j_del.java_method(:batch, [Java::JavaUtil::List.java_class,Java::IoVertxCore::Handler.java_class]).call(argsList.map { |element| element.j_del },(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgRowSet) : nil) }))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling batch(#{argsList})"
end

- (void) close { ... }

This method returns an undefined value.

Like #close but notifies the completionHandler when it's closed.

Yields:

Raises:

  • (ArgumentError)


89
90
91
92
93
94
95
96
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_prepared_query.rb', line 89

def close
  if !block_given?
    return @j_del.java_method(:close, []).call()
  elsif block_given?
    return @j_del.java_method(:close, [Java::IoVertxCore::Handler.java_class]).call((Proc.new { |ar| yield(ar.failed ? ar.cause : nil) }))
  end
  raise ArgumentError, "Invalid arguments when calling close()"
end

- (::ReactivePgClient::PgStream) create_stream(fetch = nil, args = nil)

Execute the prepared query with a cursor and createStream the result. The createStream opens a cursor with a fetch size to fetch the results.

Note: this requires to be in a transaction, since cursors require it.

Parameters:

  • fetch (Fixnum) (defaults to: nil)
    the cursor fetch size
  • args (::ReactivePgClient::Tuple) (defaults to: nil)
    the prepared query arguments

Returns:

Raises:

  • (ArgumentError)


69
70
71
72
73
74
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_prepared_query.rb', line 69

def create_stream(fetch=nil,args=nil)
  if fetch.class == Fixnum && args.class.method_defined?(:j_del) && !block_given?
    return ::Vertx::Util::Utils.safe_create(@j_del.java_method(:createStream, [Java::int.java_class,Java::IoReactiversePgclient::Tuple.java_class]).call(fetch,args.j_del),::ReactivePgClient::PgStream,::ReactivePgClient::Row.j_api_type)
  end
  raise ArgumentError, "Invalid arguments when calling create_stream(#{fetch},#{args})"
end

- (::ReactivePgClient::PgCursor) cursor(args = nil)

Create a cursor with the provided arguments.

Parameters:

Returns:

Raises:

  • (ArgumentError)


54
55
56
57
58
59
60
61
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_prepared_query.rb', line 54

def cursor(args=nil)
  if !block_given? && args == nil
    return ::Vertx::Util::Utils.safe_create(@j_del.java_method(:cursor, []).call(),::ReactivePgClient::PgCursor)
  elsif args.class.method_defined?(:j_del) && !block_given?
    return ::Vertx::Util::Utils.safe_create(@j_del.java_method(:cursor, [Java::IoReactiversePgclient::Tuple.java_class]).call(args.j_del),::ReactivePgClient::PgCursor)
  end
  raise ArgumentError, "Invalid arguments when calling cursor(#{args})"
end

- (self) execute(args = nil) { ... }

Create a cursor with the provided arguments.

Parameters:

Yields:

Returns:

  • (self)

Raises:

  • (ArgumentError)


41
42
43
44
45
46
47
48
49
50
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_prepared_query.rb', line 41

def execute(args=nil)
  if block_given? && args == nil
    @j_del.java_method(:execute, [Java::IoVertxCore::Handler.java_class]).call((Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgRowSet) : nil) }))
    return self
  elsif args.class.method_defined?(:j_del) && block_given?
    @j_del.java_method(:execute, [Java::IoReactiversePgclient::Tuple.java_class,Java::IoVertxCore::Handler.java_class]).call(args.j_del,(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgRowSet) : nil) }))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling execute(#{args})"
end
================================================ FILE: docs/yardoc/ReactivePgClient/PgResult.html ================================================ Class: ReactivePgClient::PgResult — Documentation by YARD 0.8.7.6

Class: ReactivePgClient::PgResult

Inherits:
Object
  • Object
show all
Defined in:
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_result.rb

Overview

Represents the result of an operation on database.

Direct Known Subclasses

PgRowSet

Instance Method Summary (collapse)

Instance Method Details

- (Array<String>) columns_names

Get the names of columns in the PgResult.

Returns:

  • (Array<String>)
    the list of names of columns.

Raises:

  • (ArgumentError)


35
36
37
38
39
40
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_result.rb', line 35

def columns_names
  if !block_given?
    return @j_del.java_method(:columnsNames, []).call().to_a.map { |elt| elt }
  end
  raise ArgumentError, "Invalid arguments when calling columns_names()"
end

- (::ReactivePgClient::PgResult) next

Return the next available result or null, e.g for a simple query that executed multiple queries or for a batch result.

Returns:

Raises:

  • (ArgumentError)


60
61
62
63
64
65
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_result.rb', line 60

def next
  if !block_given?
    return ::Vertx::Util::Utils.safe_create(@j_del.java_method(:next, []).call(),::ReactivePgClient::PgResult, nil)
  end
  raise ArgumentError, "Invalid arguments when calling next()"
end

- (Fixnum) row_count

Get the number of the affected rows in the operation to this PgResult.

The meaning depends on the executed statement:

  • INSERT: the number of rows inserted
  • DELETE: the number of rows deleted
  • UPDATE: the number of rows updated
  • SELECT: the number of rows retrieved

Returns:

  • (Fixnum)
    the count of affected rows.

Raises:

  • (ArgumentError)


27
28
29
30
31
32
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_result.rb', line 27

def row_count
  if !block_given?
    return @j_del.java_method(:rowCount, []).call()
  end
  raise ArgumentError, "Invalid arguments when calling row_count()"
end

- (Fixnum) size

Get the number of rows in the PgResult.

Returns:

  • (Fixnum)
    the count of rows.

Raises:

  • (ArgumentError)


43
44
45
46
47
48
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_result.rb', line 43

def size
  if !block_given?
    return @j_del.java_method(:size, []).call()
  end
  raise ArgumentError, "Invalid arguments when calling size()"
end

- (Object) value

Get the result value.

Returns:

  • (Object)
    the result

Raises:

  • (ArgumentError)


51
52
53
54
55
56
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_result.rb', line 51

def value
  if !block_given?
    return @j_arg_T.wrap(@j_del.java_method(:value, []).call())
  end
  raise ArgumentError, "Invalid arguments when calling value()"
end
================================================ FILE: docs/yardoc/ReactivePgClient/PgRowSet.html ================================================ Class: ReactivePgClient::PgRowSet — Documentation by YARD 0.8.7.6

Class: ReactivePgClient::PgRowSet

Inherits:
PgResult
  • Object
show all
Defined in:
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_row_set.rb

Overview

A set of rows.

Constant Summary

@@j_api_type =
Object.new

Class Method Summary (collapse)

Instance Method Summary (collapse)

Class Method Details

+ (Boolean) accept?(obj)

Returns:

  • (Boolean)


21
22
23
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_row_set.rb', line 21

def @@j_api_type.accept?(obj)
  obj.class == PgRowSet
end

+ (Object) j_api_type



30
31
32
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_row_set.rb', line 30

def self.j_api_type
  @@j_api_type
end

+ (Object) j_class



33
34
35
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_row_set.rb', line 33

def self.j_class
  Java::IoReactiversePgclient::PgRowSet.java_class
end

+ (Object) unwrap(obj)



27
28
29
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_row_set.rb', line 27

def @@j_api_type.unwrap(obj)
  obj.j_del
end

+ (Object) wrap(obj)



24
25
26
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_row_set.rb', line 24

def @@j_api_type.wrap(obj)
  PgRowSet.new(obj)
end

Instance Method Details

- (Array<String>) columns_names

Get the names of columns in the PgResult.

Returns:

  • (Array<String>)
    the list of names of columns.

Raises:

  • (ArgumentError)


54
55
56
57
58
59
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_row_set.rb', line 54

def columns_names
  if !block_given?
    return @j_del.java_method(:columnsNames, []).call().to_a.map { |elt| elt }
  end
  raise ArgumentError, "Invalid arguments when calling columns_names()"
end

- (::ReactivePgClient::PgIterator) iterator

Returns:

Raises:

  • (ArgumentError)


77
78
79
80
81
82
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_row_set.rb', line 77

def iterator
  if !block_given?
    return ::Vertx::Util::Utils.safe_create(@j_del.java_method(:iterator, []).call(),::ReactivePgClient::PgIterator)
  end
  raise ArgumentError, "Invalid arguments when calling iterator()"
end

- (::ReactivePgClient::PgRowSet) next

Returns:

Raises:

  • (ArgumentError)


84
85
86
87
88
89
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_row_set.rb', line 84

def next
  if !block_given?
    return ::Vertx::Util::Utils.safe_create(@j_del.java_method(:next, []).call(),::ReactivePgClient::PgRowSet)
  end
  raise ArgumentError, "Invalid arguments when calling next()"
end

- (Fixnum) row_count

Get the number of the affected rows in the operation to this PgResult.

The meaning depends on the executed statement:

  • INSERT: the number of rows inserted
  • DELETE: the number of rows deleted
  • UPDATE: the number of rows updated
  • SELECT: the number of rows retrieved

Returns:

  • (Fixnum)
    the count of affected rows.

Raises:

  • (ArgumentError)


46
47
48
49
50
51
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_row_set.rb', line 46

def row_count
  if !block_given?
    return @j_del.java_method(:rowCount, []).call()
  end
  raise ArgumentError, "Invalid arguments when calling row_count()"
end

- (Fixnum) size

Get the number of rows in the PgResult.

Returns:

  • (Fixnum)
    the count of rows.

Raises:

  • (ArgumentError)


62
63
64
65
66
67
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_row_set.rb', line 62

def size
  if !block_given?
    return @j_del.java_method(:size, []).call()
  end
  raise ArgumentError, "Invalid arguments when calling size()"
end

- (::ReactivePgClient::PgRowSet) value

Get the result value.

Returns:

Raises:

  • (ArgumentError)


70
71
72
73
74
75
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_row_set.rb', line 70

def value
  if !block_given?
    return ::Vertx::Util::Utils.safe_create(@j_del.java_method(:value, []).call(),::ReactivePgClient::PgRowSet)
  end
  raise ArgumentError, "Invalid arguments when calling value()"
end
================================================ FILE: docs/yardoc/ReactivePgClient/PgStream.html ================================================ Class: ReactivePgClient::PgStream — Documentation by YARD 0.8.7.6

Class: ReactivePgClient::PgStream

Inherits:
Object
  • Object
show all
Includes:
Vertx::ReadStream
Defined in:
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_stream.rb

Overview

A row oriented stream.

Instance Method Summary (collapse)

Instance Method Details

- (void) close { ... }

This method returns an undefined value.

Close the stream and release the resources.

Yields:

  • the completion handler for this operation

Raises:

  • (ArgumentError)


74
75
76
77
78
79
80
81
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_stream.rb', line 74

def close
  if !block_given?
    return @j_del.java_method(:close, []).call()
  elsif block_given?
    return @j_del.java_method(:close, [Java::IoVertxCore::Handler.java_class]).call((Proc.new { |ar| yield(ar.failed ? ar.cause : nil) }))
  end
  raise ArgumentError, "Invalid arguments when calling close()"
end

- (self) end_handler { ... }

Yields:

Returns:

  • (self)

Raises:

  • (ArgumentError)


64
65
66
67
68
69
70
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_stream.rb', line 64

def end_handler
  if block_given?
    @j_del.java_method(:endHandler, [Java::IoVertxCore::Handler.java_class]).call(Proc.new { yield })
    return self
  end
  raise ArgumentError, "Invalid arguments when calling end_handler()"
end

- (self) exception_handler { ... }

Yields:

Returns:

  • (self)

Raises:

  • (ArgumentError)


30
31
32
33
34
35
36
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_stream.rb', line 30

def exception_handler
  if block_given?
    @j_del.java_method(:exceptionHandler, [Java::IoVertxCore::Handler.java_class]).call((Proc.new { |event| yield(::Vertx::Util::Utils.from_throwable(event)) }))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling exception_handler()"
end

- (self) fetch(arg0 = nil)

Parameters:

  • arg0 (Fixnum) (defaults to: nil)

Returns:

  • (self)

Raises:

  • (ArgumentError)


21
22
23
24
25
26
27
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_stream.rb', line 21

def fetch(arg0=nil)
  if arg0.class == Fixnum && !block_given?
    @j_del.java_method(:fetch, [Java::long.java_class]).call(arg0)
    return self
  end
  raise ArgumentError, "Invalid arguments when calling fetch(#{arg0})"
end

- (self) handler { ... }

Yields:

Returns:

  • (self)

Raises:

  • (ArgumentError)


39
40
41
42
43
44
45
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_stream.rb', line 39

def handler
  if block_given?
    @j_del.java_method(:handler, [Java::IoVertxCore::Handler.java_class]).call((Proc.new { |event| yield(@j_arg_T.wrap(event)) }))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling handler()"
end

- (self) pause

Returns:

  • (self)

Raises:

  • (ArgumentError)


47
48
49
50
51
52
53
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_stream.rb', line 47

def pause
  if !block_given?
    @j_del.java_method(:pause, []).call()
    return self
  end
  raise ArgumentError, "Invalid arguments when calling pause()"
end

- (self) resume

Returns:

  • (self)

Raises:

  • (ArgumentError)


55
56
57
58
59
60
61
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_stream.rb', line 55

def resume
  if !block_given?
    @j_del.java_method(:resume, []).call()
    return self
  end
  raise ArgumentError, "Invalid arguments when calling resume()"
end
================================================ FILE: docs/yardoc/ReactivePgClient/PgSubscriber.html ================================================ Class: ReactivePgClient::PgSubscriber — Documentation by YARD 0.8.7.6

Class: ReactivePgClient::PgSubscriber

Inherits:
Object
  • Object
show all
Defined in:
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_subscriber.rb

Overview

A class for managing subscriptions using LISTEN/UNLISTEN to Postgres channels.

The subscriber manages a single connection to Postgres.

Constant Summary

@@j_api_type =
Object.new

Class Method Summary (collapse)

Instance Method Summary (collapse)

Class Method Details

+ (Boolean) accept?(obj)

Returns:

  • (Boolean)


22
23
24
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_subscriber.rb', line 22

def @@j_api_type.accept?(obj)
  obj.class == PgSubscriber
end

+ (Object) j_api_type



31
32
33
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_subscriber.rb', line 31

def self.j_api_type
  @@j_api_type
end

+ (Object) j_class



34
35
36
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_subscriber.rb', line 34

def self.j_class
  Java::IoReactiversePgclientPubsub::PgSubscriber.java_class
end

+ (::ReactivePgClient::PgSubscriber) subscriber(vertx = nil, options = nil)

Create a subscriber.

Parameters:

  • vertx (::Vertx::Vertx) (defaults to: nil)
    the vertx instance
  • options (Hash) (defaults to: nil)
    the connect options

Returns:

Raises:

  • (ArgumentError)


41
42
43
44
45
46
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_subscriber.rb', line 41

def self.subscriber(vertx=nil,options=nil)
  if vertx.class.method_defined?(:j_del) && options.class == Hash && !block_given?
    return ::Vertx::Util::Utils.safe_create(Java::IoReactiversePgclientPubsub::PgSubscriber.java_method(:subscriber, [Java::IoVertxCore::Vertx.java_class,Java::IoReactiversePgclient::PgConnectOptions.java_class]).call(vertx.j_del,Java::IoReactiversePgclient::PgConnectOptions.new(::Vertx::Util::Utils.to_json_object(options))),::ReactivePgClient::PgSubscriber)
  end
  raise ArgumentError, "Invalid arguments when calling subscriber(#{vertx},#{options})"
end

+ (Object) unwrap(obj)



28
29
30
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_subscriber.rb', line 28

def @@j_api_type.unwrap(obj)
  obj.j_del
end

+ (Object) wrap(obj)



25
26
27
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_subscriber.rb', line 25

def @@j_api_type.wrap(obj)
  PgSubscriber.new(obj)
end

Instance Method Details

- (::ReactivePgClient::PgConnection) actual_connection

Returns the actual connection to Postgres, it might be null

Returns:

Raises:

  • (ArgumentError)


97
98
99
100
101
102
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_subscriber.rb', line 97

def actual_connection
  if !block_given?
    return ::Vertx::Util::Utils.safe_create(@j_del.java_method(:actualConnection, []).call(),::ReactivePgClient::PgConnection)
  end
  raise ArgumentError, "Invalid arguments when calling actual_connection()"
end

- (::ReactivePgClient::PgChannel) channel(name = nil)

Return a channel for the given name.

Parameters:

  • name (String) (defaults to: nil)
    the channel name

    This will be the name of the channel exactly as held by Postgres for sending notifications. Internally this name will be truncated to the Postgres identifier maxiumum length of (NAMEDATALEN = 64) - 1 == 63 characters, and prepared as a quoted identifier without unicode escape sequence support for use in LISTEN/UNLISTEN commands. Examples of channel names and corresponding NOTIFY commands:

    • when name == "the_channel": NOTIFY the_channel, 'msg', NOTIFY The_Channel, 'msg', or NOTIFY "the_channel", 'msg' succeed in delivering a message to the created channel
    • when name == "The_Channel": NOTIFY "The_Channel", 'msg', succeeds in delivering a message to the created channel

Returns:

Raises:

  • (ArgumentError)


50
51
52
53
54
55
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_subscriber.rb', line 50

def channel(name=nil)
  if name.class == String && !block_given?
    return ::Vertx::Util::Utils.safe_create(@j_del.java_method(:channel, [Java::java.lang.String.java_class]).call(name),::ReactivePgClient::PgChannel)
  end
  raise ArgumentError, "Invalid arguments when calling channel(#{name})"
end

- (void) close

This method returns an undefined value.

Close the subscriber, the retry policy will not be invoked.

Raises:

  • (ArgumentError)


112
113
114
115
116
117
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_subscriber.rb', line 112

def close
  if !block_given?
    return @j_del.java_method(:close, []).call()
  end
  raise ArgumentError, "Invalid arguments when calling close()"
end

- (self) close_handler { ... }

Set an handler called when the subscriber is closed.

Yields:

  • the handler

Returns:

  • (self)

Raises:

  • (ArgumentError)


89
90
91
92
93
94
95
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_subscriber.rb', line 89

def close_handler
  if block_given?
    @j_del.java_method(:closeHandler, [Java::IoVertxCore::Handler.java_class]).call(Proc.new { yield })
    return self
  end
  raise ArgumentError, "Invalid arguments when calling close_handler()"
end

- (true, false) closed?

Returns whether the subscriber is closed

Returns:

  • (true, false)
    whether the subscriber is closed

Raises:

  • (ArgumentError)


104
105
106
107
108
109
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_subscriber.rb', line 104

def closed?
  if !block_given?
    return @j_del.java_method(:closed, []).call()
  end
  raise ArgumentError, "Invalid arguments when calling closed?()"
end

- (self) connect { ... }

Connect the subscriber to Postgres.

Yields:

  • the handler notified of the connection success or failure

Returns:

  • (self)

Raises:

  • (ArgumentError)


59
60
61
62
63
64
65
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_subscriber.rb', line 59

def connect
  if block_given?
    @j_del.java_method(:connect, [Java::IoVertxCore::Handler.java_class]).call((Proc.new { |ar| yield(ar.failed ? ar.cause : nil) }))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling connect()"
end

- (self) reconnect_policy(policy = nil) { ... }

Set the reconnect policy that is executed when the subscriber is disconnected.

When the subscriber is disconnected, the policy function is called with the actual number of retries and returns an amountOfTime value:

  • when amountOfTime < 0: the subscriber is closed and there is no retry
  • when amountOfTime == 0: the subscriber retries to connect immediately
  • when amountOfTime > 0: the subscriber retries after amountOfTime milliseconds

The default policy does not perform any retries.

Yields:

  • the policy to set

Returns:

  • (self)

Raises:

  • (ArgumentError)


79
80
81
82
83
84
85
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_subscriber.rb', line 79

def reconnect_policy(policy=nil)
  if block_given? && policy == nil
    @j_del.java_method(:reconnectPolicy, [Java::JavaUtilFunction::Function.java_class]).call((Proc.new { |event| yield(event) }))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling reconnect_policy(#{policy})"
end
================================================ FILE: docs/yardoc/ReactivePgClient/PgTransaction.html ================================================ Class: ReactivePgClient::PgTransaction — Documentation by YARD 0.8.7.6

Class: ReactivePgClient::PgTransaction

Inherits:
PgClient
  • Object
show all
Defined in:
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_transaction.rb

Overview

A transaction that allows to control the transaction and receive events.

Constant Summary

@@j_api_type =
Object.new

Class Method Summary (collapse)

Instance Method Summary (collapse)

Methods inherited from PgClient

connect, pool

Class Method Details

+ (Boolean) accept?(obj)

Returns:

  • (Boolean)


22
23
24
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_transaction.rb', line 22

def @@j_api_type.accept?(obj)
  obj.class == PgTransaction
end

+ (Object) j_api_type



31
32
33
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_transaction.rb', line 31

def self.j_api_type
  @@j_api_type
end

+ (Object) j_class



34
35
36
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_transaction.rb', line 34

def self.j_class
  Java::IoReactiversePgclient::PgTransaction.java_class
end

+ (Object) unwrap(obj)



28
29
30
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_transaction.rb', line 28

def @@j_api_type.unwrap(obj)
  obj.j_del
end

+ (Object) wrap(obj)



25
26
27
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_transaction.rb', line 25

def @@j_api_type.wrap(obj)
  PgTransaction.new(obj)
end

Instance Method Details

- (self) abort_handler { ... }

Set an handler to be called when the transaction is aborted.

Yields:

  • the handler

Returns:

  • (self)

Raises:

  • (ArgumentError)


73
74
75
76
77
78
79
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_transaction.rb', line 73

def abort_handler
  if block_given?
    @j_del.java_method(:abortHandler, [Java::IoVertxCore::Handler.java_class]).call(Proc.new { yield })
    return self
  end
  raise ArgumentError, "Invalid arguments when calling abort_handler()"
end

- (void) commit { ... }

This method returns an undefined value.

Like #commit with an handler to be notified when the transaction commit has completed

Yields:

Raises:

  • (ArgumentError)


51
52
53
54
55
56
57
58
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_transaction.rb', line 51

def commit
  if !block_given?
    return @j_del.java_method(:commit, []).call()
  elsif block_given?
    return @j_del.java_method(:commit, [Java::IoVertxCore::Handler.java_class]).call((Proc.new { |ar| yield(ar.failed ? ar.cause : nil) }))
  end
  raise ArgumentError, "Invalid arguments when calling commit()"
end

- (self) prepare(sql = nil) { ... }

Create a prepared query.

Parameters:

  • sql (String) (defaults to: nil)
    the sql

Yields:

  • the handler notified with the prepared query asynchronously

Returns:

  • (self)

Raises:

  • (ArgumentError)


41
42
43
44
45
46
47
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_transaction.rb', line 41

def prepare(sql=nil)
  if sql.class == String && block_given?
    @j_del.java_method(:prepare, [Java::java.lang.String.java_class,Java::IoVertxCore::Handler.java_class]).call(sql,(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgPreparedQuery) : nil) }))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling prepare(#{sql})"
end

- (self) prepared_batch(sql = nil, batch = nil) { ... }

Parameters:

Yields:

Returns:

  • (self)

Raises:

  • (ArgumentError)


108
109
110
111
112
113
114
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_transaction.rb', line 108

def prepared_batch(sql=nil,batch=nil)
  if sql.class == String && batch.class == Array && block_given?
    @j_del.java_method(:preparedBatch, [Java::java.lang.String.java_class,Java::JavaUtil::List.java_class,Java::IoVertxCore::Handler.java_class]).call(sql,batch.map { |element| element.j_del },(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgRowSet) : nil) }))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling prepared_batch(#{sql},#{batch})"
end

- (self) prepared_query(sql = nil, arguments = nil) { ... }

Parameters:

Yields:

Returns:

  • (self)

Raises:

  • (ArgumentError)


94
95
96
97
98
99
100
101
102
103
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_transaction.rb', line 94

def prepared_query(sql=nil,arguments=nil)
  if sql.class == String && block_given? && arguments == nil
    @j_del.java_method(:preparedQuery, [Java::java.lang.String.java_class,Java::IoVertxCore::Handler.java_class]).call(sql,(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgRowSet) : nil) }))
    return self
  elsif sql.class == String && arguments.class.method_defined?(:j_del) && block_given?
    @j_del.java_method(:preparedQuery, [Java::java.lang.String.java_class,Java::IoReactiversePgclient::Tuple.java_class,Java::IoVertxCore::Handler.java_class]).call(sql,arguments.j_del,(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgRowSet) : nil) }))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling prepared_query(#{sql},#{arguments})"
end

- (self) query(sql = nil) { ... }

Parameters:

  • sql (String) (defaults to: nil)

Yields:

Returns:

  • (self)

Raises:

  • (ArgumentError)


83
84
85
86
87
88
89
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_transaction.rb', line 83

def query(sql=nil)
  if sql.class == String && block_given?
    @j_del.java_method(:query, [Java::java.lang.String.java_class,Java::IoVertxCore::Handler.java_class]).call(sql,(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ::Vertx::Util::Utils.safe_create(ar.result,::ReactivePgClient::PgRowSet) : nil) }))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling query(#{sql})"
end

- (void) rollback { ... }

This method returns an undefined value.

Like #rollback with an handler to be notified when the transaction rollback has completed

Yields:

Raises:

  • (ArgumentError)


62
63
64
65
66
67
68
69
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_transaction.rb', line 62

def rollback
  if !block_given?
    return @j_del.java_method(:rollback, []).call()
  elsif block_given?
    return @j_del.java_method(:rollback, [Java::IoVertxCore::Handler.java_class]).call((Proc.new { |ar| yield(ar.failed ? ar.cause : nil) }))
  end
  raise ArgumentError, "Invalid arguments when calling rollback()"
end
================================================ FILE: docs/yardoc/ReactivePgClient/Row.html ================================================ Class: ReactivePgClient::Row — Documentation by YARD 0.8.7.6

Class: ReactivePgClient::Row

Inherits:
Tuple
  • Object
show all
Defined in:
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb

Constant Summary

@@j_api_type =
Object.new

Class Method Summary (collapse)

Instance Method Summary (collapse)

Methods inherited from Tuple

of, tuple

Class Method Details

+ (Boolean) accept?(obj)

Returns:

  • (Boolean)


20
21
22
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 20

def @@j_api_type.accept?(obj)
  obj.class == Row
end

+ (Object) j_api_type



29
30
31
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 29

def self.j_api_type
  @@j_api_type
end

+ (Object) j_class



32
33
34
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 32

def self.j_class
  Java::IoReactiversePgclient::Row.java_class
end

+ (Object) unwrap(obj)



26
27
28
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 26

def @@j_api_type.unwrap(obj)
  obj.j_del
end

+ (Object) wrap(obj)



23
24
25
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 23

def @@j_api_type.wrap(obj)
  Row.new(obj)
end

Instance Method Details

- (self) add_boolean(value = nil)

Add a boolean value at the end of the tuple.

Parameters:

  • value (true, false) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


290
291
292
293
294
295
296
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 290

def add_boolean(value=nil)
  if (value.class == TrueClass || value.class == FalseClass) && !block_given?
    @j_del.java_method(:addBoolean, [Java::JavaLang::Boolean.java_class]).call(value)
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_boolean(#{value})"
end

- (self) add_box(value = nil)

Add a value at the end of the tuple.

Parameters:

  • value (Hash) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


420
421
422
423
424
425
426
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 420

def add_box(value=nil)
  if value.class == Hash && !block_given?
    @j_del.java_method(:addBox, [Java::IoReactiversePgclientData::Box.java_class]).call(Java::IoReactiversePgclientData::Box.new(::Vertx::Util::Utils.to_json_object(value)))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_box(#{value})"
end

- (self) add_buffer(value = nil)

Add a buffer value at the end of the tuple.

Parameters:

  • value (::Vertx::Buffer) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


380
381
382
383
384
385
386
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 380

def add_buffer(value=nil)
  if value.class.method_defined?(:j_del) && !block_given?
    @j_del.java_method(:addBuffer, [Java::IoVertxCoreBuffer::Buffer.java_class]).call(value.j_del)
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_buffer(#{value})"
end

- (self) add_circle(value = nil)

Add a value at the end of the tuple.

Parameters:

  • value (Hash) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


450
451
452
453
454
455
456
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 450

def add_circle(value=nil)
  if value.class == Hash && !block_given?
    @j_del.java_method(:addCircle, [Java::IoReactiversePgclientData::Circle.java_class]).call(Java::IoReactiversePgclientData::Circle.new(::Vertx::Util::Utils.to_json_object(value)))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_circle(#{value})"
end

- (self) add_double(value = nil)

Add a double value at the end of the tuple.

Parameters:

  • value (Float) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


350
351
352
353
354
355
356
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 350

def add_double(value=nil)
  if value.class == Float && !block_given?
    @j_del.java_method(:addDouble, [Java::JavaLang::Double.java_class]).call(::Vertx::Util::Utils.to_double(value))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_double(#{value})"
end

- (self) add_float(value = nil)

Add a float value at the end of the tuple.

Parameters:

  • value (Float) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


340
341
342
343
344
345
346
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 340

def add_float(value=nil)
  if value.class == Float && !block_given?
    @j_del.java_method(:addFloat, [Java::JavaLang::Float.java_class]).call(::Vertx::Util::Utils.to_float(value))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_float(#{value})"
end

- (self) add_integer(value = nil)

Add an integer value at the end of the tuple.

Parameters:

  • value (Fixnum) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


320
321
322
323
324
325
326
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 320

def add_integer(value=nil)
  if value.class == Fixnum && !block_given?
    @j_del.java_method(:addInteger, [Java::JavaLang::Integer.java_class]).call(::Vertx::Util::Utils.to_integer(value))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_integer(#{value})"
end

- (self) add_interval(value = nil)

Add a value at the end of the tuple.

Parameters:

  • value (Hash) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


460
461
462
463
464
465
466
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 460

def add_interval(value=nil)
  if value.class == Hash && !block_given?
    @j_del.java_method(:addInterval, [Java::IoReactiversePgclientData::Interval.java_class]).call(Java::IoReactiversePgclientData::Interval.new(::Vertx::Util::Utils.to_json_object(value)))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_interval(#{value})"
end

- (self) add_json(value = nil)

Add a json value at the end of the tuple.

Parameters:

Returns:

  • (self)

Raises:

  • (ArgumentError)


370
371
372
373
374
375
376
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 370

def add_json(value=nil)
  if value.class.method_defined?(:j_del) && !block_given?
    @j_del.java_method(:addJson, [Java::IoReactiversePgclientData::Json.java_class]).call(value.j_del)
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_json(#{value})"
end

- (self) add_line(value = nil)

Add a value at the end of the tuple.

Parameters:

  • value (Hash) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


400
401
402
403
404
405
406
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 400

def add_line(value=nil)
  if value.class == Hash && !block_given?
    @j_del.java_method(:addLine, [Java::IoReactiversePgclientData::Line.java_class]).call(Java::IoReactiversePgclientData::Line.new(::Vertx::Util::Utils.to_json_object(value)))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_line(#{value})"
end

- (self) add_line_segment(value = nil)

Add a value at the end of the tuple.

Parameters:

  • value (Hash) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


410
411
412
413
414
415
416
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 410

def add_line_segment(value=nil)
  if value.class == Hash && !block_given?
    @j_del.java_method(:addLineSegment, [Java::IoReactiversePgclientData::LineSegment.java_class]).call(Java::IoReactiversePgclientData::LineSegment.new(::Vertx::Util::Utils.to_json_object(value)))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_line_segment(#{value})"
end

- (self) add_long(value = nil)

Add a long value at the end of the tuple.

Parameters:

  • value (Fixnum) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


330
331
332
333
334
335
336
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 330

def add_long(value=nil)
  if value.class == Fixnum && !block_given?
    @j_del.java_method(:addLong, [Java::JavaLang::Long.java_class]).call(value)
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_long(#{value})"
end

- (self) add_path(value = nil)

Add a value at the end of the tuple.

Parameters:

  • value (Hash) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


430
431
432
433
434
435
436
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 430

def add_path(value=nil)
  if value.class == Hash && !block_given?
    @j_del.java_method(:addPath, [Java::IoReactiversePgclientData::Path.java_class]).call(Java::IoReactiversePgclientData::Path.new(::Vertx::Util::Utils.to_json_object(value)))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_path(#{value})"
end

- (self) add_point(value = nil)

Add a value at the end of the tuple.

Parameters:

  • value (Hash) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


390
391
392
393
394
395
396
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 390

def add_point(value=nil)
  if value.class == Hash && !block_given?
    @j_del.java_method(:addPoint, [Java::IoReactiversePgclientData::Point.java_class]).call(Java::IoReactiversePgclientData::Point.new(::Vertx::Util::Utils.to_json_object(value)))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_point(#{value})"
end

- (self) add_polygon(value = nil)

Add a value at the end of the tuple.

Parameters:

  • value (Hash) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


440
441
442
443
444
445
446
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 440

def add_polygon(value=nil)
  if value.class == Hash && !block_given?
    @j_del.java_method(:addPolygon, [Java::IoReactiversePgclientData::Polygon.java_class]).call(Java::IoReactiversePgclientData::Polygon.new(::Vertx::Util::Utils.to_json_object(value)))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_polygon(#{value})"
end

- (self) add_short(value = nil)

Add a short value at the end of the tuple.

Parameters:

  • value (Fixnum) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


310
311
312
313
314
315
316
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 310

def add_short(value=nil)
  if value.class == Fixnum && !block_given?
    @j_del.java_method(:addShort, [Java::JavaLang::Short.java_class]).call(::Vertx::Util::Utils.to_short(value))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_short(#{value})"
end

- (self) add_string(value = nil)

Add a string value at the end of the tuple.

Parameters:

  • value (String) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


360
361
362
363
364
365
366
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 360

def add_string(value=nil)
  if value.class == String && !block_given?
    @j_del.java_method(:addString, [Java::java.lang.String.java_class]).call(value)
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_string(#{value})"
end

- (self) add_value(value = nil)

Add an object value at the end of the tuple.

Parameters:

  • value (Object) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


300
301
302
303
304
305
306
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 300

def add_value(value=nil)
  if ::Vertx::Util::unknown_type.accept?(value) && !block_given?
    @j_del.java_method(:addValue, [Java::java.lang.Object.java_class]).call(::Vertx::Util::Utils.to_object(value))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_value(#{value})"
end

- (void) clear

This method returns an undefined value.

Raises:

  • (ArgumentError)


475
476
477
478
479
480
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 475

def clear
  if !block_given?
    return @j_del.java_method(:clear, []).call()
  end
  raise ArgumentError, "Invalid arguments when calling clear()"
end

- (true, false) getBoolean(pos) - (true, false) getBoolean(name)

Get a boolean value at pos.

Overloads:

  • - (true, false) getBoolean(pos)

    Parameters:

    • pos (Fixnum)
      the position
  • - (true, false) getBoolean(name)

    Parameters:

    • name (String)
      the column

Returns:

  • (true, false)
    the value or null

Raises:

  • (ArgumentError)


41
42
43
44
45
46
47
48
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 41

def get_boolean?(param_1=nil)
  if param_1.class == Fixnum && !block_given?
    return @j_del.java_method(:getBoolean, [Java::int.java_class]).call(param_1)
  elsif param_1.class == String && !block_given?
    return @j_del.java_method(:getBoolean, [Java::java.lang.String.java_class]).call(param_1)
  end
  raise ArgumentError, "Invalid arguments when calling get_boolean?(#{param_1})"
end

- (Hash) getBox(pos) - (Hash) getBox(name)

Get value at pos.

Overloads:

  • - (Hash) getBox(pos)

    Parameters:

    • pos (Fixnum)
      the position
  • - (Hash) getBox(name)

    Parameters:

    • name (String)
      the column

Returns:

  • (Hash)
    the value or null

Raises:

  • (ArgumentError)


209
210
211
212
213
214
215
216
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 209

def get_box(param_1=nil)
  if param_1.class == Fixnum && !block_given?
    return @j_del.java_method(:getBox, [Java::int.java_class]).call(param_1) != nil ? JSON.parse(@j_del.java_method(:getBox, [Java::int.java_class]).call(param_1).toJson.encode) : nil
  elsif param_1.class == String && !block_given?
    return @j_del.java_method(:getBox, [Java::java.lang.String.java_class]).call(param_1) != nil ? JSON.parse(@j_del.java_method(:getBox, [Java::java.lang.String.java_class]).call(param_1).toJson.encode) : nil
  end
  raise ArgumentError, "Invalid arguments when calling get_box(#{param_1})"
end

- (::Vertx::Buffer) getBuffer(pos) - (::Vertx::Buffer) getBuffer(name)

Get a buffer value at pos.

Overloads:

  • - (::Vertx::Buffer) getBuffer(pos)

    Parameters:

    • pos (Fixnum)
      the position
  • - (::Vertx::Buffer) getBuffer(name)

    Parameters:

    • name (String)
      the column

Returns:

  • (::Vertx::Buffer)
    the value or null

Raises:

  • (ArgumentError)


279
280
281
282
283
284
285
286
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 279

def get_buffer(param_1=nil)
  if param_1.class == Fixnum && !block_given?
    return ::Vertx::Util::Utils.safe_create(@j_del.java_method(:getBuffer, [Java::int.java_class]).call(param_1),::Vertx::Buffer)
  elsif param_1.class == String && !block_given?
    return ::Vertx::Util::Utils.safe_create(@j_del.java_method(:getBuffer, [Java::java.lang.String.java_class]).call(param_1),::Vertx::Buffer)
  end
  raise ArgumentError, "Invalid arguments when calling get_buffer(#{param_1})"
end

- (Hash) getCircle(pos) - (Hash) getCircle(name)

Get value at pos.

Overloads:

  • - (Hash) getCircle(pos)

    Parameters:

    • pos (Fixnum)
      the position
  • - (Hash) getCircle(name)

    Parameters:

    • name (String)
      the column

Returns:

  • (Hash)
    the value or null

Raises:

  • (ArgumentError)


251
252
253
254
255
256
257
258
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 251

def get_circle(param_1=nil)
  if param_1.class == Fixnum && !block_given?
    return @j_del.java_method(:getCircle, [Java::int.java_class]).call(param_1) != nil ? JSON.parse(@j_del.java_method(:getCircle, [Java::int.java_class]).call(param_1).toJson.encode) : nil
  elsif param_1.class == String && !block_given?
    return @j_del.java_method(:getCircle, [Java::java.lang.String.java_class]).call(param_1) != nil ? JSON.parse(@j_del.java_method(:getCircle, [Java::java.lang.String.java_class]).call(param_1).toJson.encode) : nil
  end
  raise ArgumentError, "Invalid arguments when calling get_circle(#{param_1})"
end

- (String) get_column_name(pos = nil)

Get a column name at pos.

Parameters:

  • pos (Fixnum) (defaults to: nil)
    the position

Returns:

  • (String)
    the column name or null

Raises:

  • (ArgumentError)


484
485
486
487
488
489
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 484

def get_column_name(pos=nil)
  if pos.class == Fixnum && !block_given?
    return @j_del.java_method(:getColumnName, [Java::int.java_class]).call(pos)
  end
  raise ArgumentError, "Invalid arguments when calling get_column_name(#{pos})"
end

- (Float) getDouble(pos) - (Float) getDouble(name)

Get a double value at pos.

Overloads:

  • - (Float) getDouble(pos)

    Parameters:

    • pos (Fixnum)
      the position
  • - (Float) getDouble(name)

    Parameters:

    • name (String)
      the column

Returns:

  • (Float)
    the value or null

Raises:

  • (ArgumentError)


125
126
127
128
129
130
131
132
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 125

def get_double(param_1=nil)
  if param_1.class == Fixnum && !block_given?
    return @j_del.java_method(:getDouble, [Java::int.java_class]).call(param_1)
  elsif param_1.class == String && !block_given?
    return @j_del.java_method(:getDouble, [Java::java.lang.String.java_class]).call(param_1)
  end
  raise ArgumentError, "Invalid arguments when calling get_double(#{param_1})"
end

- (Float) getFloat(pos) - (Float) getFloat(name)

Get a float value at pos.

Overloads:

  • - (Float) getFloat(pos)

    Parameters:

    • pos (Fixnum)
      the position
  • - (Float) getFloat(name)

    Parameters:

    • name (String)
      the column

Returns:

  • (Float)
    the value or null

Raises:

  • (ArgumentError)


111
112
113
114
115
116
117
118
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 111

def get_float(param_1=nil)
  if param_1.class == Fixnum && !block_given?
    return @j_del.java_method(:getFloat, [Java::int.java_class]).call(param_1)
  elsif param_1.class == String && !block_given?
    return @j_del.java_method(:getFloat, [Java::java.lang.String.java_class]).call(param_1)
  end
  raise ArgumentError, "Invalid arguments when calling get_float(#{param_1})"
end

- (Fixnum) getInteger(pos) - (Fixnum) getInteger(name)

Get an integer value at pos.

Overloads:

  • - (Fixnum) getInteger(pos)

    Parameters:

    • pos (Fixnum)
      the position
  • - (Fixnum) getInteger(name)

    Parameters:

    • name (String)
      the column

Returns:

  • (Fixnum)
    the value or null

Raises:

  • (ArgumentError)


83
84
85
86
87
88
89
90
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 83

def get_integer(param_1=nil)
  if param_1.class == Fixnum && !block_given?
    return @j_del.java_method(:getInteger, [Java::int.java_class]).call(param_1)
  elsif param_1.class == String && !block_given?
    return @j_del.java_method(:getInteger, [Java::java.lang.String.java_class]).call(param_1)
  end
  raise ArgumentError, "Invalid arguments when calling get_integer(#{param_1})"
end

- (Hash) getInterval(pos) - (Hash) getInterval(name)

Get value at pos.

Overloads:

  • - (Hash) getInterval(pos)

    Parameters:

    • pos (Fixnum)
      the position
  • - (Hash) getInterval(name)

    Parameters:

    • name (String)
      the column

Returns:

  • (Hash)
    the value or null

Raises:

  • (ArgumentError)


265
266
267
268
269
270
271
272
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 265

def get_interval(param_1=nil)
  if param_1.class == Fixnum && !block_given?
    return @j_del.java_method(:getInterval, [Java::int.java_class]).call(param_1) != nil ? JSON.parse(@j_del.java_method(:getInterval, [Java::int.java_class]).call(param_1).toJson.encode) : nil
  elsif param_1.class == String && !block_given?
    return @j_del.java_method(:getInterval, [Java::java.lang.String.java_class]).call(param_1) != nil ? JSON.parse(@j_del.java_method(:getInterval, [Java::java.lang.String.java_class]).call(param_1).toJson.encode) : nil
  end
  raise ArgumentError, "Invalid arguments when calling get_interval(#{param_1})"
end

- (::ReactivePgClient::Json) getJson(pos) - (::ReactivePgClient::Json) getJson(name)

Get a json value at pos.

Overloads:

Returns:

Raises:

  • (ArgumentError)


153
154
155
156
157
158
159
160
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 153

def get_json(param_1=nil)
  if param_1.class == Fixnum && !block_given?
    return ::Vertx::Util::Utils.safe_create(@j_del.java_method(:getJson, [Java::int.java_class]).call(param_1),::ReactivePgClient::Json)
  elsif param_1.class == String && !block_given?
    return ::Vertx::Util::Utils.safe_create(@j_del.java_method(:getJson, [Java::java.lang.String.java_class]).call(param_1),::ReactivePgClient::Json)
  end
  raise ArgumentError, "Invalid arguments when calling get_json(#{param_1})"
end

- (Hash) getLine(pos) - (Hash) getLine(name)

Get value at pos.

Overloads:

  • - (Hash) getLine(pos)

    Parameters:

    • pos (Fixnum)
      the position
  • - (Hash) getLine(name)

    Parameters:

    • name (String)
      the column

Returns:

  • (Hash)
    the value or null

Raises:

  • (ArgumentError)


181
182
183
184
185
186
187
188
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 181

def get_line(param_1=nil)
  if param_1.class == Fixnum && !block_given?
    return @j_del.java_method(:getLine, [Java::int.java_class]).call(param_1) != nil ? JSON.parse(@j_del.java_method(:getLine, [Java::int.java_class]).call(param_1).toJson.encode) : nil
  elsif param_1.class == String && !block_given?
    return @j_del.java_method(:getLine, [Java::java.lang.String.java_class]).call(param_1) != nil ? JSON.parse(@j_del.java_method(:getLine, [Java::java.lang.String.java_class]).call(param_1).toJson.encode) : nil
  end
  raise ArgumentError, "Invalid arguments when calling get_line(#{param_1})"
end

- (Hash) getLineSegment(pos) - (Hash) getLineSegment(name)

Get value at pos.

Overloads:

  • - (Hash) getLineSegment(pos)

    Parameters:

    • pos (Fixnum)
      the position
  • - (Hash) getLineSegment(name)

    Parameters:

    • name (String)
      the column

Returns:

  • (Hash)
    the value or null

Raises:

  • (ArgumentError)


195
196
197
198
199
200
201
202
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 195

def get_line_segment(param_1=nil)
  if param_1.class == Fixnum && !block_given?
    return @j_del.java_method(:getLineSegment, [Java::int.java_class]).call(param_1) != nil ? JSON.parse(@j_del.java_method(:getLineSegment, [Java::int.java_class]).call(param_1).toJson.encode) : nil
  elsif param_1.class == String && !block_given?
    return @j_del.java_method(:getLineSegment, [Java::java.lang.String.java_class]).call(param_1) != nil ? JSON.parse(@j_del.java_method(:getLineSegment, [Java::java.lang.String.java_class]).call(param_1).toJson.encode) : nil
  end
  raise ArgumentError, "Invalid arguments when calling get_line_segment(#{param_1})"
end

- (Fixnum) getLong(pos) - (Fixnum) getLong(name)

Get a long value at pos.

Overloads:

  • - (Fixnum) getLong(pos)

    Parameters:

    • pos (Fixnum)
      the position
  • - (Fixnum) getLong(name)

    Parameters:

    • name (String)
      the column

Returns:

  • (Fixnum)
    the value or null

Raises:

  • (ArgumentError)


97
98
99
100
101
102
103
104
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 97

def get_long(param_1=nil)
  if param_1.class == Fixnum && !block_given?
    return @j_del.java_method(:getLong, [Java::int.java_class]).call(param_1)
  elsif param_1.class == String && !block_given?
    return @j_del.java_method(:getLong, [Java::java.lang.String.java_class]).call(param_1)
  end
  raise ArgumentError, "Invalid arguments when calling get_long(#{param_1})"
end

- (Hash) getPath(pos) - (Hash) getPath(name)

Get value at pos.

Overloads:

  • - (Hash) getPath(pos)

    Parameters:

    • pos (Fixnum)
      the position
  • - (Hash) getPath(name)

    Parameters:

    • name (String)
      the column

Returns:

  • (Hash)
    the value or null

Raises:

  • (ArgumentError)


223
224
225
226
227
228
229
230
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 223

def get_path(param_1=nil)
  if param_1.class == Fixnum && !block_given?
    return @j_del.java_method(:getPath, [Java::int.java_class]).call(param_1) != nil ? JSON.parse(@j_del.java_method(:getPath, [Java::int.java_class]).call(param_1).toJson.encode) : nil
  elsif param_1.class == String && !block_given?
    return @j_del.java_method(:getPath, [Java::java.lang.String.java_class]).call(param_1) != nil ? JSON.parse(@j_del.java_method(:getPath, [Java::java.lang.String.java_class]).call(param_1).toJson.encode) : nil
  end
  raise ArgumentError, "Invalid arguments when calling get_path(#{param_1})"
end

- (Hash) getPoint(pos) - (Hash) getPoint(name)

Get value at pos.

Overloads:

  • - (Hash) getPoint(pos)

    Parameters:

    • pos (Fixnum)
      the position
  • - (Hash) getPoint(name)

    Parameters:

    • name (String)
      the column

Returns:

  • (Hash)
    the value or null

Raises:

  • (ArgumentError)


167
168
169
170
171
172
173
174
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 167

def get_point(param_1=nil)
  if param_1.class == Fixnum && !block_given?
    return @j_del.java_method(:getPoint, [Java::int.java_class]).call(param_1) != nil ? JSON.parse(@j_del.java_method(:getPoint, [Java::int.java_class]).call(param_1).toJson.encode) : nil
  elsif param_1.class == String && !block_given?
    return @j_del.java_method(:getPoint, [Java::java.lang.String.java_class]).call(param_1) != nil ? JSON.parse(@j_del.java_method(:getPoint, [Java::java.lang.String.java_class]).call(param_1).toJson.encode) : nil
  end
  raise ArgumentError, "Invalid arguments when calling get_point(#{param_1})"
end

- (Hash) getPolygon(pos) - (Hash) getPolygon(name)

Get value at pos.

Overloads:

  • - (Hash) getPolygon(pos)

    Parameters:

    • pos (Fixnum)
      the position
  • - (Hash) getPolygon(name)

    Parameters:

    • name (String)
      the column

Returns:

  • (Hash)
    the value or null

Raises:

  • (ArgumentError)


237
238
239
240
241
242
243
244
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 237

def get_polygon(param_1=nil)
  if param_1.class == Fixnum && !block_given?
    return @j_del.java_method(:getPolygon, [Java::int.java_class]).call(param_1) != nil ? JSON.parse(@j_del.java_method(:getPolygon, [Java::int.java_class]).call(param_1).toJson.encode) : nil
  elsif param_1.class == String && !block_given?
    return @j_del.java_method(:getPolygon, [Java::java.lang.String.java_class]).call(param_1) != nil ? JSON.parse(@j_del.java_method(:getPolygon, [Java::java.lang.String.java_class]).call(param_1).toJson.encode) : nil
  end
  raise ArgumentError, "Invalid arguments when calling get_polygon(#{param_1})"
end

- (Fixnum) getShort(pos) - (Fixnum) getShort(name)

Get a short value at pos.

Overloads:

  • - (Fixnum) getShort(pos)

    Parameters:

    • pos (Fixnum)
      the position
  • - (Fixnum) getShort(name)

    Parameters:

    • name (String)
      the column

Returns:

  • (Fixnum)
    the value or null

Raises:

  • (ArgumentError)


69
70
71
72
73
74
75
76
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 69

def get_short(param_1=nil)
  if param_1.class == Fixnum && !block_given?
    return @j_del.java_method(:getShort, [Java::int.java_class]).call(param_1)
  elsif param_1.class == String && !block_given?
    return @j_del.java_method(:getShort, [Java::java.lang.String.java_class]).call(param_1)
  end
  raise ArgumentError, "Invalid arguments when calling get_short(#{param_1})"
end

- (String) getString(pos) - (String) getString(name)

Get a string value at pos.

Overloads:

  • - (String) getString(pos)

    Parameters:

    • pos (Fixnum)
      the position
  • - (String) getString(name)

    Parameters:

    • name (String)
      the column

Returns:

  • (String)
    the value or null

Raises:

  • (ArgumentError)


139
140
141
142
143
144
145
146
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 139

def get_string(param_1=nil)
  if param_1.class == Fixnum && !block_given?
    return @j_del.java_method(:getString, [Java::int.java_class]).call(param_1)
  elsif param_1.class == String && !block_given?
    return @j_del.java_method(:getString, [Java::java.lang.String.java_class]).call(param_1)
  end
  raise ArgumentError, "Invalid arguments when calling get_string(#{param_1})"
end

- (Object) getValue(pos) - (Object) getValue(name)

Get an object value at pos.

Overloads:

  • - (Object) getValue(pos)

    Parameters:

    • pos (Fixnum)
      the position
  • - (Object) getValue(name)

    Parameters:

    • name (String)
      the column

Returns:

  • (Object)
    the value or null

Raises:

  • (ArgumentError)


55
56
57
58
59
60
61
62
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 55

def get_value(param_1=nil)
  if param_1.class == Fixnum && !block_given?
    return ::Vertx::Util::Utils.from_object(@j_del.java_method(:getValue, [Java::int.java_class]).call(param_1))
  elsif param_1.class == String && !block_given?
    return ::Vertx::Util::Utils.from_object(@j_del.java_method(:getValue, [Java::java.lang.String.java_class]).call(param_1))
  end
  raise ArgumentError, "Invalid arguments when calling get_value(#{param_1})"
end

- (Fixnum) size

Returns the tuple size

Returns:

  • (Fixnum)
    the tuple size

Raises:

  • (ArgumentError)


468
469
470
471
472
473
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb', line 468

def size
  if !block_given?
    return @j_del.java_method(:size, []).call()
  end
  raise ArgumentError, "Invalid arguments when calling size()"
end
================================================ FILE: docs/yardoc/ReactivePgClient/Tuple.html ================================================ Class: ReactivePgClient::Tuple — Documentation by YARD 0.8.7.6

Class: ReactivePgClient::Tuple

Inherits:
Object
  • Object
show all
Defined in:
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb

Overview

A general purpose tuple.

Direct Known Subclasses

Row

Constant Summary

@@j_api_type =
Object.new

Class Method Summary (collapse)

Instance Method Summary (collapse)

Class Method Details

+ (Boolean) accept?(obj)

Returns:

  • (Boolean)


19
20
21
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 19

def @@j_api_type.accept?(obj)
  obj.class == Tuple
end

+ (Object) j_api_type



28
29
30
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 28

def self.j_api_type
  @@j_api_type
end

+ (Object) j_class



31
32
33
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 31

def self.j_class
  Java::IoReactiversePgclient::Tuple.java_class
end

+ (::ReactivePgClient::Tuple) of(elt1 = nil, elt2 = nil, elt3 = nil, elt4 = nil, elt5 = nil, elt6 = nil)

Create a tuple of six elements.

Parameters:

  • elt1 (Object) (defaults to: nil)
    the first value
  • elt2 (Object) (defaults to: nil)
    the second valueg
  • elt3 (Object) (defaults to: nil)
    the third value
  • elt4 (Object) (defaults to: nil)
    the fourth value
  • elt5 (Object) (defaults to: nil)
    the fifth value
  • elt6 (Object) (defaults to: nil)
    the sixth value

Returns:

Raises:

  • (ArgumentError)


49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 49

def self.of(elt1=nil,elt2=nil,elt3=nil,elt4=nil,elt5=nil,elt6=nil)
  if ::Vertx::Util::unknown_type.accept?(elt1) && !block_given? && elt2 == nil && elt3 == nil && elt4 == nil && elt5 == nil && elt6 == nil
    return ::Vertx::Util::Utils.safe_create(Java::IoReactiversePgclient::Tuple.java_method(:of, [Java::java.lang.Object.java_class]).call(::Vertx::Util::Utils.to_object(elt1)),::ReactivePgClient::Tuple)
  elsif ::Vertx::Util::unknown_type.accept?(elt1) && ::Vertx::Util::unknown_type.accept?(elt2) && !block_given? && elt3 == nil && elt4 == nil && elt5 == nil && elt6 == nil
    return ::Vertx::Util::Utils.safe_create(Java::IoReactiversePgclient::Tuple.java_method(:of, [Java::java.lang.Object.java_class,Java::java.lang.Object.java_class]).call(::Vertx::Util::Utils.to_object(elt1),::Vertx::Util::Utils.to_object(elt2)),::ReactivePgClient::Tuple)
  elsif ::Vertx::Util::unknown_type.accept?(elt1) && ::Vertx::Util::unknown_type.accept?(elt2) && ::Vertx::Util::unknown_type.accept?(elt3) && !block_given? && elt4 == nil && elt5 == nil && elt6 == nil
    return ::Vertx::Util::Utils.safe_create(Java::IoReactiversePgclient::Tuple.java_method(:of, [Java::java.lang.Object.java_class,Java::java.lang.Object.java_class,Java::java.lang.Object.java_class]).call(::Vertx::Util::Utils.to_object(elt1),::Vertx::Util::Utils.to_object(elt2),::Vertx::Util::Utils.to_object(elt3)),::ReactivePgClient::Tuple)
  elsif ::Vertx::Util::unknown_type.accept?(elt1) && ::Vertx::Util::unknown_type.accept?(elt2) && ::Vertx::Util::unknown_type.accept?(elt3) && ::Vertx::Util::unknown_type.accept?(elt4) && !block_given? && elt5 == nil && elt6 == nil
    return ::Vertx::Util::Utils.safe_create(Java::IoReactiversePgclient::Tuple.java_method(:of, [Java::java.lang.Object.java_class,Java::java.lang.Object.java_class,Java::java.lang.Object.java_class,Java::java.lang.Object.java_class]).call(::Vertx::Util::Utils.to_object(elt1),::Vertx::Util::Utils.to_object(elt2),::Vertx::Util::Utils.to_object(elt3),::Vertx::Util::Utils.to_object(elt4)),::ReactivePgClient::Tuple)
  elsif ::Vertx::Util::unknown_type.accept?(elt1) && ::Vertx::Util::unknown_type.accept?(elt2) && ::Vertx::Util::unknown_type.accept?(elt3) && ::Vertx::Util::unknown_type.accept?(elt4) && ::Vertx::Util::unknown_type.accept?(elt5) && !block_given? && elt6 == nil
    return ::Vertx::Util::Utils.safe_create(Java::IoReactiversePgclient::Tuple.java_method(:of, [Java::java.lang.Object.java_class,Java::java.lang.Object.java_class,Java::java.lang.Object.java_class,Java::java.lang.Object.java_class,Java::java.lang.Object.java_class]).call(::Vertx::Util::Utils.to_object(elt1),::Vertx::Util::Utils.to_object(elt2),::Vertx::Util::Utils.to_object(elt3),::Vertx::Util::Utils.to_object(elt4),::Vertx::Util::Utils.to_object(elt5)),::ReactivePgClient::Tuple)
  elsif ::Vertx::Util::unknown_type.accept?(elt1) && ::Vertx::Util::unknown_type.accept?(elt2) && ::Vertx::Util::unknown_type.accept?(elt3) && ::Vertx::Util::unknown_type.accept?(elt4) && ::Vertx::Util::unknown_type.accept?(elt5) && ::Vertx::Util::unknown_type.accept?(elt6) && !block_given?
    return ::Vertx::Util::Utils.safe_create(Java::IoReactiversePgclient::Tuple.java_method(:of, [Java::java.lang.Object.java_class,Java::java.lang.Object.java_class,Java::java.lang.Object.java_class,Java::java.lang.Object.java_class,Java::java.lang.Object.java_class,Java::java.lang.Object.java_class]).call(::Vertx::Util::Utils.to_object(elt1),::Vertx::Util::Utils.to_object(elt2),::Vertx::Util::Utils.to_object(elt3),::Vertx::Util::Utils.to_object(elt4),::Vertx::Util::Utils.to_object(elt5),::Vertx::Util::Utils.to_object(elt6)),::ReactivePgClient::Tuple)
  end
  raise ArgumentError, "Invalid arguments when calling of(#{elt1},#{elt2},#{elt3},#{elt4},#{elt5},#{elt6})"
end

+ (::ReactivePgClient::Tuple) tuple

Returns a new empty tuple

Returns:

Raises:

  • (ArgumentError)


35
36
37
38
39
40
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 35

def self.tuple
  if !block_given?
    return ::Vertx::Util::Utils.safe_create(Java::IoReactiversePgclient::Tuple.java_method(:tuple, []).call(),::ReactivePgClient::Tuple)
  end
  raise ArgumentError, "Invalid arguments when calling tuple()"
end

+ (Object) unwrap(obj)



25
26
27
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 25

def @@j_api_type.unwrap(obj)
  obj.j_del
end

+ (Object) wrap(obj)



22
23
24
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 22

def @@j_api_type.wrap(obj)
  Tuple.new(obj)
end

Instance Method Details

- (self) add_boolean(value = nil)

Add a boolean value at the end of the tuple.

Parameters:

  • value (true, false) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


230
231
232
233
234
235
236
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 230

def add_boolean(value=nil)
  if (value.class == TrueClass || value.class == FalseClass) && !block_given?
    @j_del.java_method(:addBoolean, [Java::JavaLang::Boolean.java_class]).call(value)
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_boolean(#{value})"
end

- (self) add_box(value = nil)

Add a value at the end of the tuple.

Parameters:

  • value (Hash) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


360
361
362
363
364
365
366
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 360

def add_box(value=nil)
  if value.class == Hash && !block_given?
    @j_del.java_method(:addBox, [Java::IoReactiversePgclientData::Box.java_class]).call(Java::IoReactiversePgclientData::Box.new(::Vertx::Util::Utils.to_json_object(value)))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_box(#{value})"
end

- (self) add_buffer(value = nil)

Add a buffer value at the end of the tuple.

Parameters:

  • value (::Vertx::Buffer) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


320
321
322
323
324
325
326
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 320

def add_buffer(value=nil)
  if value.class.method_defined?(:j_del) && !block_given?
    @j_del.java_method(:addBuffer, [Java::IoVertxCoreBuffer::Buffer.java_class]).call(value.j_del)
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_buffer(#{value})"
end

- (self) add_circle(value = nil)

Add a value at the end of the tuple.

Parameters:

  • value (Hash) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


390
391
392
393
394
395
396
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 390

def add_circle(value=nil)
  if value.class == Hash && !block_given?
    @j_del.java_method(:addCircle, [Java::IoReactiversePgclientData::Circle.java_class]).call(Java::IoReactiversePgclientData::Circle.new(::Vertx::Util::Utils.to_json_object(value)))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_circle(#{value})"
end

- (self) add_double(value = nil)

Add a double value at the end of the tuple.

Parameters:

  • value (Float) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


290
291
292
293
294
295
296
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 290

def add_double(value=nil)
  if value.class == Float && !block_given?
    @j_del.java_method(:addDouble, [Java::JavaLang::Double.java_class]).call(::Vertx::Util::Utils.to_double(value))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_double(#{value})"
end

- (self) add_float(value = nil)

Add a float value at the end of the tuple.

Parameters:

  • value (Float) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


280
281
282
283
284
285
286
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 280

def add_float(value=nil)
  if value.class == Float && !block_given?
    @j_del.java_method(:addFloat, [Java::JavaLang::Float.java_class]).call(::Vertx::Util::Utils.to_float(value))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_float(#{value})"
end

- (self) add_integer(value = nil)

Add an integer value at the end of the tuple.

Parameters:

  • value (Fixnum) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


260
261
262
263
264
265
266
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 260

def add_integer(value=nil)
  if value.class == Fixnum && !block_given?
    @j_del.java_method(:addInteger, [Java::JavaLang::Integer.java_class]).call(::Vertx::Util::Utils.to_integer(value))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_integer(#{value})"
end

- (self) add_interval(value = nil)

Add a value at the end of the tuple.

Parameters:

  • value (Hash) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


400
401
402
403
404
405
406
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 400

def add_interval(value=nil)
  if value.class == Hash && !block_given?
    @j_del.java_method(:addInterval, [Java::IoReactiversePgclientData::Interval.java_class]).call(Java::IoReactiversePgclientData::Interval.new(::Vertx::Util::Utils.to_json_object(value)))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_interval(#{value})"
end

- (self) add_json(value = nil)

Add a json value at the end of the tuple.

Parameters:

Returns:

  • (self)

Raises:

  • (ArgumentError)


310
311
312
313
314
315
316
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 310

def add_json(value=nil)
  if value.class.method_defined?(:j_del) && !block_given?
    @j_del.java_method(:addJson, [Java::IoReactiversePgclientData::Json.java_class]).call(value.j_del)
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_json(#{value})"
end

- (self) add_line(value = nil)

Add a value at the end of the tuple.

Parameters:

  • value (Hash) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


340
341
342
343
344
345
346
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 340

def add_line(value=nil)
  if value.class == Hash && !block_given?
    @j_del.java_method(:addLine, [Java::IoReactiversePgclientData::Line.java_class]).call(Java::IoReactiversePgclientData::Line.new(::Vertx::Util::Utils.to_json_object(value)))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_line(#{value})"
end

- (self) add_line_segment(value = nil)

Add a value at the end of the tuple.

Parameters:

  • value (Hash) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


350
351
352
353
354
355
356
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 350

def add_line_segment(value=nil)
  if value.class == Hash && !block_given?
    @j_del.java_method(:addLineSegment, [Java::IoReactiversePgclientData::LineSegment.java_class]).call(Java::IoReactiversePgclientData::LineSegment.new(::Vertx::Util::Utils.to_json_object(value)))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_line_segment(#{value})"
end

- (self) add_long(value = nil)

Add a long value at the end of the tuple.

Parameters:

  • value (Fixnum) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


270
271
272
273
274
275
276
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 270

def add_long(value=nil)
  if value.class == Fixnum && !block_given?
    @j_del.java_method(:addLong, [Java::JavaLang::Long.java_class]).call(value)
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_long(#{value})"
end

- (self) add_path(value = nil)

Add a value at the end of the tuple.

Parameters:

  • value (Hash) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


370
371
372
373
374
375
376
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 370

def add_path(value=nil)
  if value.class == Hash && !block_given?
    @j_del.java_method(:addPath, [Java::IoReactiversePgclientData::Path.java_class]).call(Java::IoReactiversePgclientData::Path.new(::Vertx::Util::Utils.to_json_object(value)))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_path(#{value})"
end

- (self) add_point(value = nil)

Add a value at the end of the tuple.

Parameters:

  • value (Hash) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


330
331
332
333
334
335
336
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 330

def add_point(value=nil)
  if value.class == Hash && !block_given?
    @j_del.java_method(:addPoint, [Java::IoReactiversePgclientData::Point.java_class]).call(Java::IoReactiversePgclientData::Point.new(::Vertx::Util::Utils.to_json_object(value)))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_point(#{value})"
end

- (self) add_polygon(value = nil)

Add a value at the end of the tuple.

Parameters:

  • value (Hash) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


380
381
382
383
384
385
386
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 380

def add_polygon(value=nil)
  if value.class == Hash && !block_given?
    @j_del.java_method(:addPolygon, [Java::IoReactiversePgclientData::Polygon.java_class]).call(Java::IoReactiversePgclientData::Polygon.new(::Vertx::Util::Utils.to_json_object(value)))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_polygon(#{value})"
end

- (self) add_short(value = nil)

Add a short value at the end of the tuple.

Parameters:

  • value (Fixnum) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


250
251
252
253
254
255
256
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 250

def add_short(value=nil)
  if value.class == Fixnum && !block_given?
    @j_del.java_method(:addShort, [Java::JavaLang::Short.java_class]).call(::Vertx::Util::Utils.to_short(value))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_short(#{value})"
end

- (self) add_string(value = nil)

Add a string value at the end of the tuple.

Parameters:

  • value (String) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


300
301
302
303
304
305
306
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 300

def add_string(value=nil)
  if value.class == String && !block_given?
    @j_del.java_method(:addString, [Java::java.lang.String.java_class]).call(value)
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_string(#{value})"
end

- (self) add_value(value = nil)

Add an object value at the end of the tuple.

Parameters:

  • value (Object) (defaults to: nil)
    the value

Returns:

  • (self)

Raises:

  • (ArgumentError)


240
241
242
243
244
245
246
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 240

def add_value(value=nil)
  if ::Vertx::Util::unknown_type.accept?(value) && !block_given?
    @j_del.java_method(:addValue, [Java::java.lang.Object.java_class]).call(::Vertx::Util::Utils.to_object(value))
    return self
  end
  raise ArgumentError, "Invalid arguments when calling add_value(#{value})"
end

- (void) clear

This method returns an undefined value.

Raises:

  • (ArgumentError)


415
416
417
418
419
420
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 415

def clear
  if !block_given?
    return @j_del.java_method(:clear, []).call()
  end
  raise ArgumentError, "Invalid arguments when calling clear()"
end

- (true, false) get_boolean?(pos = nil)

Get a boolean value at pos.

Parameters:

  • pos (Fixnum) (defaults to: nil)
    the position

Returns:

  • (true, false)
    the value or null

Raises:

  • (ArgumentError)


68
69
70
71
72
73
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 68

def get_boolean?(pos=nil)
  if pos.class == Fixnum && !block_given?
    return @j_del.java_method(:getBoolean, [Java::int.java_class]).call(pos)
  end
  raise ArgumentError, "Invalid arguments when calling get_boolean?(#{pos})"
end

- (Hash) get_box(pos = nil)

Get value at pos.

Parameters:

  • pos (Fixnum) (defaults to: nil)
    the position

Returns:

  • (Hash)
    the value or null

Raises:

  • (ArgumentError)


176
177
178
179
180
181
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 176

def get_box(pos=nil)
  if pos.class == Fixnum && !block_given?
    return @j_del.java_method(:getBox, [Java::int.java_class]).call(pos) != nil ? JSON.parse(@j_del.java_method(:getBox, [Java::int.java_class]).call(pos).toJson.encode) : nil
  end
  raise ArgumentError, "Invalid arguments when calling get_box(#{pos})"
end

- (::Vertx::Buffer) get_buffer(pos = nil)

Get a buffer value at pos.

Parameters:

  • pos (Fixnum) (defaults to: nil)
    the position

Returns:

  • (::Vertx::Buffer)
    the value or null

Raises:

  • (ArgumentError)


221
222
223
224
225
226
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 221

def get_buffer(pos=nil)
  if pos.class == Fixnum && !block_given?
    return ::Vertx::Util::Utils.safe_create(@j_del.java_method(:getBuffer, [Java::int.java_class]).call(pos),::Vertx::Buffer)
  end
  raise ArgumentError, "Invalid arguments when calling get_buffer(#{pos})"
end

- (Hash) get_circle(pos = nil)

Get value at pos.

Parameters:

  • pos (Fixnum) (defaults to: nil)
    the position

Returns:

  • (Hash)
    the value or null

Raises:

  • (ArgumentError)


203
204
205
206
207
208
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 203

def get_circle(pos=nil)
  if pos.class == Fixnum && !block_given?
    return @j_del.java_method(:getCircle, [Java::int.java_class]).call(pos) != nil ? JSON.parse(@j_del.java_method(:getCircle, [Java::int.java_class]).call(pos).toJson.encode) : nil
  end
  raise ArgumentError, "Invalid arguments when calling get_circle(#{pos})"
end

- (Float) get_double(pos = nil)

Get a double value at pos.

Parameters:

  • pos (Fixnum) (defaults to: nil)
    the position

Returns:

  • (Float)
    the value or null

Raises:

  • (ArgumentError)


122
123
124
125
126
127
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 122

def get_double(pos=nil)
  if pos.class == Fixnum && !block_given?
    return @j_del.java_method(:getDouble, [Java::int.java_class]).call(pos)
  end
  raise ArgumentError, "Invalid arguments when calling get_double(#{pos})"
end

- (Float) get_float(pos = nil)

Get a float value at pos.

Parameters:

  • pos (Fixnum) (defaults to: nil)
    the position

Returns:

  • (Float)
    the value or null

Raises:

  • (ArgumentError)


113
114
115
116
117
118
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 113

def get_float(pos=nil)
  if pos.class == Fixnum && !block_given?
    return @j_del.java_method(:getFloat, [Java::int.java_class]).call(pos)
  end
  raise ArgumentError, "Invalid arguments when calling get_float(#{pos})"
end

- (Fixnum) get_integer(pos = nil)

Get an integer value at pos.

Parameters:

  • pos (Fixnum) (defaults to: nil)
    the position

Returns:

  • (Fixnum)
    the value or null

Raises:

  • (ArgumentError)


95
96
97
98
99
100
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 95

def get_integer(pos=nil)
  if pos.class == Fixnum && !block_given?
    return @j_del.java_method(:getInteger, [Java::int.java_class]).call(pos)
  end
  raise ArgumentError, "Invalid arguments when calling get_integer(#{pos})"
end

- (Hash) get_interval(pos = nil)

Get value at pos.

Parameters:

  • pos (Fixnum) (defaults to: nil)
    the position

Returns:

  • (Hash)
    the value or null

Raises:

  • (ArgumentError)


212
213
214
215
216
217
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 212

def get_interval(pos=nil)
  if pos.class == Fixnum && !block_given?
    return @j_del.java_method(:getInterval, [Java::int.java_class]).call(pos) != nil ? JSON.parse(@j_del.java_method(:getInterval, [Java::int.java_class]).call(pos).toJson.encode) : nil
  end
  raise ArgumentError, "Invalid arguments when calling get_interval(#{pos})"
end

- (::ReactivePgClient::Json) get_json(pos = nil)

Get a json value at pos.

Parameters:

  • pos (Fixnum) (defaults to: nil)
    the position

Returns:

Raises:

  • (ArgumentError)


140
141
142
143
144
145
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 140

def get_json(pos=nil)
  if pos.class == Fixnum && !block_given?
    return ::Vertx::Util::Utils.safe_create(@j_del.java_method(:getJson, [Java::int.java_class]).call(pos),::ReactivePgClient::Json)
  end
  raise ArgumentError, "Invalid arguments when calling get_json(#{pos})"
end

- (Hash) get_line(pos = nil)

Get value at pos.

Parameters:

  • pos (Fixnum) (defaults to: nil)
    the position

Returns:

  • (Hash)
    the value or null

Raises:

  • (ArgumentError)


158
159
160
161
162
163
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 158

def get_line(pos=nil)
  if pos.class == Fixnum && !block_given?
    return @j_del.java_method(:getLine, [Java::int.java_class]).call(pos) != nil ? JSON.parse(@j_del.java_method(:getLine, [Java::int.java_class]).call(pos).toJson.encode) : nil
  end
  raise ArgumentError, "Invalid arguments when calling get_line(#{pos})"
end

- (Hash) get_line_segment(pos = nil)

Get value at pos.

Parameters:

  • pos (Fixnum) (defaults to: nil)
    the position

Returns:

  • (Hash)
    the value or null

Raises:

  • (ArgumentError)


167
168
169
170
171
172
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 167

def get_line_segment(pos=nil)
  if pos.class == Fixnum && !block_given?
    return @j_del.java_method(:getLineSegment, [Java::int.java_class]).call(pos) != nil ? JSON.parse(@j_del.java_method(:getLineSegment, [Java::int.java_class]).call(pos).toJson.encode) : nil
  end
  raise ArgumentError, "Invalid arguments when calling get_line_segment(#{pos})"
end

- (Fixnum) get_long(pos = nil)

Get a long value at pos.

Parameters:

  • pos (Fixnum) (defaults to: nil)
    the position

Returns:

  • (Fixnum)
    the value or null

Raises:

  • (ArgumentError)


104
105
106
107
108
109
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 104

def get_long(pos=nil)
  if pos.class == Fixnum && !block_given?
    return @j_del.java_method(:getLong, [Java::int.java_class]).call(pos)
  end
  raise ArgumentError, "Invalid arguments when calling get_long(#{pos})"
end

- (Hash) get_path(pos = nil)

Get value at pos.

Parameters:

  • pos (Fixnum) (defaults to: nil)
    the position

Returns:

  • (Hash)
    the value or null

Raises:

  • (ArgumentError)


185
186
187
188
189
190
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 185

def get_path(pos=nil)
  if pos.class == Fixnum && !block_given?
    return @j_del.java_method(:getPath, [Java::int.java_class]).call(pos) != nil ? JSON.parse(@j_del.java_method(:getPath, [Java::int.java_class]).call(pos).toJson.encode) : nil
  end
  raise ArgumentError, "Invalid arguments when calling get_path(#{pos})"
end

- (Hash) get_point(pos = nil)

Get value at pos.

Parameters:

  • pos (Fixnum) (defaults to: nil)
    the position

Returns:

  • (Hash)
    the value or null

Raises:

  • (ArgumentError)


149
150
151
152
153
154
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 149

def get_point(pos=nil)
  if pos.class == Fixnum && !block_given?
    return @j_del.java_method(:getPoint, [Java::int.java_class]).call(pos) != nil ? JSON.parse(@j_del.java_method(:getPoint, [Java::int.java_class]).call(pos).toJson.encode) : nil
  end
  raise ArgumentError, "Invalid arguments when calling get_point(#{pos})"
end

- (Hash) get_polygon(pos = nil)

Get value at pos.

Parameters:

  • pos (Fixnum) (defaults to: nil)
    the position

Returns:

  • (Hash)
    the value or null

Raises:

  • (ArgumentError)


194
195
196
197
198
199
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 194

def get_polygon(pos=nil)
  if pos.class == Fixnum && !block_given?
    return @j_del.java_method(:getPolygon, [Java::int.java_class]).call(pos) != nil ? JSON.parse(@j_del.java_method(:getPolygon, [Java::int.java_class]).call(pos).toJson.encode) : nil
  end
  raise ArgumentError, "Invalid arguments when calling get_polygon(#{pos})"
end

- (Fixnum) get_short(pos = nil)

Get a short value at pos.

Parameters:

  • pos (Fixnum) (defaults to: nil)
    the position

Returns:

  • (Fixnum)
    the value or null

Raises:

  • (ArgumentError)


86
87
88
89
90
91
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 86

def get_short(pos=nil)
  if pos.class == Fixnum && !block_given?
    return @j_del.java_method(:getShort, [Java::int.java_class]).call(pos)
  end
  raise ArgumentError, "Invalid arguments when calling get_short(#{pos})"
end

- (String) get_string(pos = nil)

Get a string value at pos.

Parameters:

  • pos (Fixnum) (defaults to: nil)
    the position

Returns:

  • (String)
    the value or null

Raises:

  • (ArgumentError)


131
132
133
134
135
136
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 131

def get_string(pos=nil)
  if pos.class == Fixnum && !block_given?
    return @j_del.java_method(:getString, [Java::int.java_class]).call(pos)
  end
  raise ArgumentError, "Invalid arguments when calling get_string(#{pos})"
end

- (Object) get_value(pos = nil)

Get an object value at pos.

Parameters:

  • pos (Fixnum) (defaults to: nil)
    the position

Returns:

  • (Object)
    the value or null

Raises:

  • (ArgumentError)


77
78
79
80
81
82
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 77

def get_value(pos=nil)
  if pos.class == Fixnum && !block_given?
    return ::Vertx::Util::Utils.from_object(@j_del.java_method(:getValue, [Java::int.java_class]).call(pos))
  end
  raise ArgumentError, "Invalid arguments when calling get_value(#{pos})"
end

- (Fixnum) size

Returns the tuple size

Returns:

  • (Fixnum)
    the tuple size

Raises:

  • (ArgumentError)


408
409
410
411
412
413
# File '/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb', line 408

def size
  if !block_given?
    return @j_del.java_method(:size, []).call()
  end
  raise ArgumentError, "Invalid arguments when calling size()"
end
================================================ FILE: docs/yardoc/ReactivePgClient.html ================================================ Module: ReactivePgClient — Documentation by YARD 0.8.7.6

Module: ReactivePgClient

Defined in:
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/row.rb,
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/json.rb,
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/tuple.rb,
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_pool.rb,
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_cursor.rb,
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_result.rb,
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_stream.rb,
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_client.rb,
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_row_set.rb,
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_channel.rb,
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_iterator.rb,
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_connection.rb,
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_subscriber.rb,
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_transaction.rb,
/Users/julien/java/reactive-pg-client/target/classes/reactive-pg-client/pg_prepared_query.rb

Overview

Generated from io.reactiverse.pgclient.PgPreparedQuery

Defined Under Namespace

Classes: Json, PgChannel, PgClient, PgConnection, PgCursor, PgIterator, PgPool, PgPreparedQuery, PgResult, PgRowSet, PgStream, PgSubscriber, PgTransaction, Row, Tuple

================================================ FILE: docs/yardoc/_index.html ================================================ Documentation by YARD 0.8.7.6

Documentation by YARD 0.8.7.6

Alphabetic Index

File Listing

Namespace Listing A-Z

  • J
    • Json (ReactivePgClient)
  • T
    • Tuple (ReactivePgClient)
================================================ FILE: docs/yardoc/class_list.html ================================================ Class List

Class List

================================================ FILE: docs/yardoc/css/common.css ================================================ /* Override this file with custom rules */ ================================================ FILE: docs/yardoc/css/full_list.css ================================================ body { margin: 0; font-family: "Lucida Sans", "Lucida Grande", Verdana, Arial, sans-serif; font-size: 13px; height: 101%; overflow-x: hidden; } h1 { padding: 12px 10px; padding-bottom: 0; margin: 0; font-size: 1.4em; } .clear { clear: both; } #search { position: absolute; right: 5px; top: 9px; padding-left: 24px; } #content.insearch #search, #content.insearch #noresults { background: url(data:image/gif;base64,R0lGODlhEAAQAPYAAP///wAAAPr6+pKSkoiIiO7u7sjIyNjY2J6engAAAI6OjsbGxjIyMlJSUuzs7KamppSUlPLy8oKCghwcHLKysqSkpJqamvT09Pj4+KioqM7OzkRERAwMDGBgYN7e3ujo6Ly8vCoqKjY2NkZGRtTU1MTExDw8PE5OTj4+PkhISNDQ0MrKylpaWrS0tOrq6nBwcKysrLi4uLq6ul5eXlxcXGJiYoaGhuDg4H5+fvz8/KKiohgYGCwsLFZWVgQEBFBQUMzMzDg4OFhYWBoaGvDw8NbW1pycnOLi4ubm5kBAQKqqqiQkJCAgIK6urnJyckpKSjQ0NGpqatLS0sDAwCYmJnx8fEJCQlRUVAoKCggICLCwsOTk5ExMTPb29ra2tmZmZmhoaNzc3KCgoBISEiIiIgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCAAAACwAAAAAEAAQAAAHaIAAgoMgIiYlg4kACxIaACEJCSiKggYMCRselwkpghGJBJEcFgsjJyoAGBmfggcNEx0flBiKDhQFlIoCCA+5lAORFb4AJIihCRbDxQAFChAXw9HSqb60iREZ1omqrIPdJCTe0SWI09GBACH5BAkIAAAALAAAAAAQABAAAAdrgACCgwc0NTeDiYozCQkvOTo9GTmDKy8aFy+NOBA7CTswgywJDTIuEjYFIY0JNYMtKTEFiRU8Pjwygy4ws4owPyCKwsMAJSTEgiQlgsbIAMrO0dKDGMTViREZ14kYGRGK38nHguHEJcvTyIEAIfkECQgAAAAsAAAAABAAEAAAB2iAAIKDAggPg4iJAAMJCRUAJRIqiRGCBI0WQEEJJkWDERkYAAUKEBc4Po1GiKKJHkJDNEeKig4URLS0ICImJZAkuQAhjSi/wQyNKcGDCyMnk8u5rYrTgqDVghgZlYjcACTA1sslvtHRgQAh+QQJCAAAACwAAAAAEAAQAAAHZ4AAgoOEhYaCJSWHgxGDJCQARAtOUoQRGRiFD0kJUYWZhUhKT1OLhR8wBaaFBzQ1NwAlkIszCQkvsbOHL7Y4q4IuEjaqq0ZQD5+GEEsJTDCMmIUhtgk1lo6QFUwJVDKLiYJNUd6/hoEAIfkECQgAAAAsAAAAABAAEAAAB2iAAIKDhIWGgiUlh4MRgyQkjIURGRiGGBmNhJWHm4uen4ICCA+IkIsDCQkVACWmhwSpFqAABQoQF6ALTkWFnYMrVlhWvIKTlSAiJiVVPqlGhJkhqShHV1lCW4cMqSkAR1ofiwsjJyqGgQAh+QQJCAAAACwAAAAAEAAQAAAHZ4AAgoOEhYaCJSWHgxGDJCSMhREZGIYYGY2ElYebi56fhyWQniSKAKKfpaCLFlAPhl0gXYNGEwkhGYREUywag1wJwSkHNDU3D0kJYIMZQwk8MjPBLx9eXwuETVEyAC/BOKsuEjYFhoEAIfkECQgAAAAsAAAAABAAEAAAB2eAAIKDhIWGgiUlh4MRgyQkjIURGRiGGBmNhJWHm4ueICImip6CIQkJKJ4kigynKaqKCyMnKqSEK05StgAGQRxPYZaENqccFgIID4KXmQBhXFkzDgOnFYLNgltaSAAEpxa7BQoQF4aBACH5BAkIAAAALAAAAAAQABAAAAdogACCg4SFggJiPUqCJSWGgkZjCUwZACQkgxGEXAmdT4UYGZqCGWQ+IjKGGIUwPzGPhAc0NTewhDOdL7Ykji+dOLuOLhI2BbaFETICx4MlQitdqoUsCQ2vhKGjglNfU0SWmILaj43M5oEAOwAAAAAAAAAAAA==) no-repeat center left; } #full_list { padding: 0; list-style: none; margin-left: 0; } #full_list ul { padding: 0; } #full_list li { padding: 5px; padding-left: 12px; margin: 0; font-size: 1.1em; list-style: none; } #noresults { padding: 7px 12px; } #content.insearch #noresults { margin-left: 7px; } ul.collapsed ul, ul.collapsed li { display: none; } ul.collapsed.search_uncollapsed { display: block; } ul.collapsed.search_uncollapsed li { display: list-item; } li a.toggle { cursor: default; position: relative; left: -5px; top: 4px; text-indent: -999px; width: 10px; height: 9px; margin-left: -10px; display: block; float: left; background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAASCAYAAABb0P4QAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAK8AAACvABQqw0mAAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTM5jWRgMAAAAVdEVYdENyZWF0aW9uIFRpbWUAMy8xNC8wOeNZPpQAAAE2SURBVDiNrZTBccIwEEXfelIAHUA6CZ24BGaWO+FuzZAK4k6gg5QAdGAq+Bxs2Yqx7BzyL7Llp/VfzZeQhCTc/ezuGzKKnKSzpCxXJM8fwNXda3df5RZETlIt6YUzSQDs93sl8w3wBZxCCE10GM1OcWbWjB2mWgEH4Mfdyxm3PSepBHibgQE2wLe7r4HjEidpnXMYdQPKEMJcsZ4zs2POYQOcaPfwMVOo58zsAdMt18BuoVDPxUJRacELbXv3hUIX2vYmOUvi8C8ydz/ThjXrqKqqLbDIAdsCKBd+Wo7GWa7o9qzOQHVVVXeAbs+yHHCH4aTsaCOQqunmUy1yBUAXkdMIfMlgF5EXLo2OpV/c/Up7jG4hhHcYLgWzAZXUc2b2ixsfvc/RmNNfOXD3Q/oeL9axJE1yT9IOoUu6MGUkAAAAAElFTkSuQmCC) no-repeat bottom left; } li.collapsed a.toggle { opacity: 0.5; cursor: default; background-position: top left; } li { color: #888; cursor: pointer; } li.deprecated { text-decoration: line-through; font-style: italic; } li.r1 { background: #f0f0f0; } li.r2 { background: #fafafa; } li:hover { background: #ddd; } li small:before { content: "("; } li small:after { content: ")"; } li small.search_info { display: none; } a:link, a:visited { text-decoration: none; color: #05a; } li.clicked { background: #05a; color: #ccc; } li.clicked a:link, li.clicked a:visited { color: #eee; } li.clicked a.toggle { opacity: 0.5; background-position: bottom right; } li.collapsed.clicked a.toggle { background-position: top right; } #search input { border: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } #nav { margin-left: 10px; font-size: 0.9em; display: none; color: #aaa; } #nav a:link, #nav a:visited { color: #358; } #nav a:hover { background: transparent; color: #5af; } .frames #nav span:after { content: ' | '; } .frames #nav span:last-child:after { content: ''; } .frames #content h1 { margin-top: 0; } .frames li { white-space: nowrap; cursor: normal; } .frames li small { display: block; font-size: 0.8em; } .frames li small:before { content: ""; } .frames li small:after { content: ""; } .frames li small.search_info { display: none; } .frames #search { width: 170px; position: static; margin: 3px; margin-left: 10px; font-size: 0.9em; color: #888; padding-left: 0; padding-right: 24px; } .frames #content.insearch #search { background-position: center right; } .frames #search input { width: 110px; } .frames #nav { display: block; } #full_list.insearch li { display: none; } #full_list.insearch li.found { display: list-item; padding-left: 10px; } #full_list.insearch li a.toggle { display: none; } #full_list.insearch li small.search_info { display: block; } ================================================ FILE: docs/yardoc/css/style.css ================================================ body { padding: 0 20px; font-family: "Lucida Sans", "Lucida Grande", Verdana, Arial, sans-serif; font-size: 13px; } body.frames { padding: 0 5px; } h1 { font-size: 25px; margin: 1em 0 0.5em; padding-top: 4px; border-top: 1px dotted #d5d5d5; } h1.noborder { border-top: 0px; margin-top: 0; padding-top: 4px; } h1.title { margin-bottom: 10px; } h1.alphaindex { margin-top: 0; font-size: 22px; } h2 { padding: 0; padding-bottom: 3px; border-bottom: 1px #aaa solid; font-size: 1.4em; margin: 1.8em 0 0.5em; } h2 small { font-weight: normal; font-size: 0.7em; display: block; float: right; } .clear { clear: both; } .inline { display: inline; } .inline p:first-child { display: inline; } .docstring h1, .docstring h2, .docstring h3, .docstring h4 { padding: 0; border: 0; border-bottom: 1px dotted #bbb; } .docstring h1 { font-size: 1.2em; } .docstring h2 { font-size: 1.1em; } .docstring h3, .docstring h4 { font-size: 1em; border-bottom: 0; padding-top: 10px; } .summary_desc .object_link, .docstring .object_link { font-family: monospace; } .rdoc-term { padding-right: 25px; font-weight: bold; } .rdoc-list p { margin: 0; padding: 0; margin-bottom: 4px; } /* style for */ #filecontents table, .docstring table { border-collapse: collapse; } #filecontents table th, #filecontents table td, .docstring table th, .docstring table td { border: 1px solid #ccc; padding: 8px; padding-right: 17px; } #filecontents table tr:nth-child(odd), .docstring table tr:nth-child(odd) { background: #eee; } #filecontents table tr:nth-child(even), .docstring table tr:nth-child(even) { background: #fff; } #filecontents table th, .docstring table th { background: #fff; } /* style for
    */ #filecontents li > p, .docstring li > p { margin: 0px; } #filecontents ul, .docstring ul { padding-left: 20px; } /* style for
    */ #filecontents dl, .docstring dl { border: 1px solid #ccc; } #filecontents dt, .docstring dt { background: #ddd; font-weight: bold; padding: 3px 5px; } #filecontents dd, .docstring dd { padding: 5px 0px; margin-left: 18px; } #filecontents dd > p, .docstring dd > p { margin: 0px; } .note { color: #222; -moz-border-radius: 3px; -webkit-border-radius: 3px; background: #e3e4e3; border: 1px solid #d5d5d5; padding: 7px 10px; display: block; } .note.todo { background: #ffffc5; border-color: #ececaa; } .note.returns_void { background: #efefef; } .note.deprecated { background: #ffe5e5; border-color: #e9dada; } .note.private { background: #ffffc5; border-color: #ececaa; } .note.title { padding: 1px 5px; font-size: 0.9em; font-family: "Lucida Sans", "Lucida Grande", Verdana, Arial, sans-serif; display: inline; } .summary_signature + .note.title { margin-left: 7px; } h1 .note.title { font-size: 0.5em; font-weight: normal; padding: 3px 5px; position: relative; top: -3px; text-transform: capitalize; } .note.title.constructor { color: #fff; background: #6a98d6; border-color: #6689d6; } .note.title.writeonly { color: #fff; background: #45a638; border-color: #2da31d; } .note.title.readonly { color: #fff; background: #6a98d6; border-color: #6689d6; } .note.title.private { background: #d5d5d5; border-color: #c5c5c5; } .note.title.not_defined_here { background: transparent; border: none; font-style: italic; } .discussion .note { margin-top: 6px; } .discussion .note:first-child { margin-top: 0; } h3.inherited { font-style: italic; font-family: "Lucida Sans", "Lucida Grande", Verdana, Arial, sans-serif; font-weight: normal; padding: 0; margin: 0; margin-top: 12px; margin-bottom: 3px; font-size: 13px; } p.inherited { padding: 0; margin: 0; margin-left: 25px; } #filecontents dl.box, dl.box { border: 0; width: 520px; font-size: 1em; } #filecontents dl.box dt, dl.box dt { float: left; display: block; width: 100px; margin: 0; text-align: right; font-weight: bold; background: transparent; border: 1px solid #aaa; border-width: 1px 0px 0px 1px; padding: 6px 0; padding-right: 10px; } #filecontents dl.box dd, dl.box dd { float: left; display: block; width: 380px; margin: 0; padding: 6px 0; padding-right: 20px; border: 1px solid #aaa; border-width: 1px 1px 0 0; } #filecontents dl.box .last, dl.box .last { border-bottom: 1px solid #aaa; } #filecontents dl.box .r1, dl.box .r1 { background: #eee; } ul.toplevel { list-style: none; padding-left: 0; font-size: 1.1em; } .index_inline_list { padding-left: 0; font-size: 1.1em; } .index_inline_list li { list-style: none; display: inline; padding: 7px 12px; line-height: 35px; } dl.constants { margin-left: 40px; } dl.constants dt { font-weight: bold; font-size: 1.1em; margin-bottom: 5px; } dl.constants dd { width: 75%; white-space: pre; font-family: monospace; margin-bottom: 18px; } .summary_desc { margin-left: 32px; display: block; font-family: sans-serif; } .summary_desc tt { font-size: 0.9em; } dl.constants .note { padding: 2px 6px; padding-right: 12px; margin-top: 6px; } dl.constants .docstring { margin-left: 32px; font-size: 0.9em; font-weight: normal; } dl.constants .tags { padding-left: 32px; font-size: 0.9em; line-height: 0.8em; } dl.constants .discussion *:first-child { margin-top: 0; } dl.constants .discussion *:last-child { margin-bottom: 0; } .method_details { border-top: 1px dotted #aaa; margin-top: 15px; padding-top: 0; } .method_details.first { border: 0; } p.signature, h3.signature { font-size: 1.1em; font-weight: normal; font-family: Monaco, Consolas, Courier, monospace; padding: 6px 10px; margin-top: 18px; background: #e5e8ff; border: 1px solid #d8d8e5; -moz-border-radius: 3px; -webkit-border-radius: 3px; } p.signature tt, h3.signature tt { font-family: Monaco, Consolas, Courier, monospace; } p.signature .overload, h3.signature .overload { display: block; } p.signature .extras, h3.signature .extras { font-weight: normal; font-family: sans-serif; color: #444; font-size: 1em; } p.signature .not_defined_here, h3.signature .not_defined_here, p.signature .aliases, h3.signature .aliases { display: block; font-weight: normal; font-size: 0.9em; font-family: sans-serif; margin-top: 0px; color: #555; } p.signature .aliases .names, h3.signature .aliases .names { font-family: Monaco, Consolas, Courier, monospace; font-weight: bold; color: #000; font-size: 1.2em; } .tags .tag_title { font-size: 1em; margin-bottom: 0; font-weight: bold; } .tags ul { margin-top: 5px; padding-left: 30px; list-style: square; } .tags ul li { margin-bottom: 3px; } .tags ul .name { font-family: monospace; font-weight: bold; } .tags ul .note { padding: 3px 6px; } .tags { margin-bottom: 12px; } .tags .examples .tag_title { margin-bottom: 10px; font-weight: bold; } .tags .examples .inline p { padding: 0; margin: 0; margin-left: 15px; font-weight: bold; font-size: 0.9em; } .tags .overload .overload_item { list-style: none; margin-bottom: 25px; } .tags .overload .overload_item .signature { padding: 2px 8px; background: #e5e8ff; border: 1px solid #d8d8e5; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .tags .overload .signature { margin-left: -15px; font-family: monospace; display: block; font-size: 1.1em; } .tags .overload .docstring { margin-top: 15px; } .defines { display: none; } #method_missing_details .notice.this { position: relative; top: -8px; color: #888; padding: 0; margin: 0; } .showSource { font-size: 0.9em; } .showSource a:link, .showSource a:visited { text-decoration: none; color: #666; } #content a:link, #content a:visited { text-decoration: none; color: #05a; } #content a:hover { background: #ffffa5; } div.docstring, p.docstring { margin-right: 6em; } ul.summary { list-style: none; font-family: monospace; font-size: 1em; line-height: 1.5em; } ul.summary a:link, ul.summary a:visited { text-decoration: none; font-size: 1.1em; } ul.summary li { margin-bottom: 5px; } .summary .summary_signature { padding: 1px 10px; background: #eaeaff; border: 1px solid #dfdfe5; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .summary_signature:hover { background: #eeeeff; cursor: pointer; } ul.summary.compact li { display: inline-block; margin: 0px 5px 0px 0px; line-height: 2.6em;} ul.summary.compact .summary_signature { padding: 5px 7px; padding-right: 4px; } #content .summary_signature:hover a:link, #content .summary_signature:hover a:visited { background: transparent; color: #48f; } p.inherited a { font-family: monospace; font-size: 0.9em; } p.inherited { word-spacing: 5px; font-size: 1.2em; } p.children { font-size: 1.2em; } p.children a { font-size: 0.9em; } p.children strong { font-size: 0.8em; } p.children strong.modules { padding-left: 5px; } ul.fullTree { display: none; padding-left: 0; list-style: none; margin-left: 0; margin-bottom: 10px; } ul.fullTree ul { margin-left: 0; padding-left: 0; list-style: none; } ul.fullTree li { text-align: center; padding-top: 18px; padding-bottom: 12px; background: url(data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzABhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/phCJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+Q8cwwOgYBzPEbDAuxsNCsTgsCZNjy7EirAyrxhqwVqwDu4n1Y8+xdwQSgUXACTYEd0IgYR5BSFhMWE7YSKggHCQ0EdoJNwkDhFHCJyKTqEu0JroR+cQYYjIxh1hILCPWEo8TLxB7iEPENyQSiUMyJ7mQAkmxpFTSEtJG0m5SI+ksqZs0SBojk8naZGuyBzmULCAryIXkneTD5DPkG+Qh8lsKnWJAcaT4U+IoUspqShnlEOU05QZlmDJBVaOaUt2ooVQRNY9aQq2htlKvUYeoEzR1mjnNgxZJS6WtopXTGmgXaPdpr+h0uhHdlR5Ol9BX0svpR+iX6AP0dwwNhhWDx4hnKBmbGAcYZxl3GK+YTKYZ04sZx1QwNzHrmOeZD5lvVVgqtip8FZHKCpVKlSaVGyovVKmqpqreqgtV81XLVI+pXlN9rkZVM1PjqQnUlqtVqp1Q61MbU2epO6iHqmeob1Q/pH5Z/YkGWcNMw09DpFGgsV/jvMYgC2MZs3gsIWsNq4Z1gTXEJrHN2Xx2KruY/R27iz2qqaE5QzNKM1ezUvOUZj8H45hx+Jx0TgnnKKeX836K3hTvKeIpG6Y0TLkxZVxrqpaXllirSKtRq0frvTau7aedpr1Fu1n7gQ5Bx0onXCdHZ4/OBZ3nU9lT3acKpxZNPTr1ri6qa6UbobtEd79up+6Ynr5egJ5Mb6feeb3n+hx9L/1U/W36p/VHDFgGswwkBtsMzhg8xTVxbzwdL8fb8VFDXcNAQ6VhlWGX4YSRudE8o9VGjUYPjGnGXOMk423GbcajJgYmISZLTepN7ppSTbmmKaY7TDtMx83MzaLN1pk1mz0x1zLnm+eb15vft2BaeFostqi2uGVJsuRaplnutrxuhVo5WaVYVVpds0atna0l1rutu6cRp7lOk06rntZnw7Dxtsm2qbcZsOXYBtuutm22fWFnYhdnt8Wuw+6TvZN9un2N/T0HDYfZDqsdWh1+c7RyFDpWOt6azpzuP33F9JbpL2dYzxDP2DPjthPLKcRpnVOb00dnF2e5c4PziIuJS4LLLpc+Lpsbxt3IveRKdPVxXeF60vWdm7Obwu2o26/uNu5p7ofcn8w0nymeWTNz0MPIQ+BR5dE/C5+VMGvfrH5PQ0+BZ7XnIy9jL5FXrdewt6V3qvdh7xc+9j5yn+M+4zw33jLeWV/MN8C3yLfLT8Nvnl+F30N/I/9k/3r/0QCngCUBZwOJgUGBWwL7+Hp8Ib+OPzrbZfay2e1BjKC5QRVBj4KtguXBrSFoyOyQrSH355jOkc5pDoVQfujW0Adh5mGLw34MJ4WHhVeGP45wiFga0TGXNXfR3ENz30T6RJZE3ptnMU85ry1KNSo+qi5qPNo3ujS6P8YuZlnM1VidWElsSxw5LiquNm5svt/87fOH4p3iC+N7F5gvyF1weaHOwvSFpxapLhIsOpZATIhOOJTwQRAqqBaMJfITdyWOCnnCHcJnIi/RNtGI2ENcKh5O8kgqTXqS7JG8NXkkxTOlLOW5hCepkLxMDUzdmzqeFpp2IG0yPTq9MYOSkZBxQqohTZO2Z+pn5mZ2y6xlhbL+xW6Lty8elQfJa7OQrAVZLQq2QqboVFoo1yoHsmdlV2a/zYnKOZarnivN7cyzytuQN5zvn//tEsIS4ZK2pYZLVy0dWOa9rGo5sjxxedsK4xUFK4ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1dT1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aXDm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3SPVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKaRptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfVP1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i/suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAgY0hSTQAAeiUAAICDAAD5/wAAgOkAAHUwAADqYAAAOpgAABdvkl/FRgAAAHtJREFUeNqMzrEJAkEURdGzuhgZbSoYWcAWoBVsB4JgZAGmphsZCZYzTQgWNCYrDN9RvMmHx+X916SUBFbo8CzD1idXrLErw1mQttgXtyrOcQ/Ny5p4Qh+2XqLYYazsPWNTiuMkRxa4vcV+evuNAUOLIx5+c2hyzv7hNQC67Q+/HHmlEwAAAABJRU5ErkJggg==) no-repeat top center; } ul.fullTree li:first-child { padding-top: 0; background: transparent; } ul.fullTree li:last-child { padding-bottom: 0; } .showAll ul.fullTree { display: block; } .showAll .inheritName { display: none; } #search { position: absolute; right: 14px; top: 0px; } #search a:link, #search a:visited { display: block; float: left; margin-right: 4px; padding: 8px 10px; text-decoration: none; color: #05a; border: 1px solid #d8d8e5; -moz-border-radius-bottomleft: 3px; -moz-border-radius-bottomright: 3px; -webkit-border-bottom-left-radius: 3px; -webkit-border-bottom-right-radius: 3px; background: #eaf0ff; -webkit-box-shadow: -1px 1px 3px #ddd; } #search a:hover { background: #f5faff; color: #06b; } #search a.active { background: #568; padding-bottom: 20px; color: #fff; border: 1px solid #457; -moz-border-radius-topleft: 5px; -moz-border-radius-topright: 5px; -webkit-border-top-left-radius: 5px; -webkit-border-top-right-radius: 5px; } #search a.inactive { color: #999; } .frames #search { display: none; } .inheritanceTree, .toggleDefines { float: right; } #menu { font-size: 1.3em; color: #bbb; top: -5px; position: relative; } #menu .title, #menu a { font-size: 0.7em; } #menu .title a { font-size: 1em; } #menu .title { color: #555; } #menu a:link, #menu a:visited { color: #333; text-decoration: none; border-bottom: 1px dotted #bbd; } #menu a:hover { color: #05a; } #menu .noframes { display: inline; } .frames #menu .noframes { display: inline; float: right; } #footer { margin-top: 15px; border-top: 1px solid #ccc; text-align: center; padding: 7px 0; color: #999; } #footer a:link, #footer a:visited { color: #444; text-decoration: none; border-bottom: 1px dotted #bbd; } #footer a:hover { color: #05a; } #listing ul.alpha { font-size: 1.1em; } #listing ul.alpha { margin: 0; padding: 0; padding-bottom: 10px; list-style: none; } #listing ul.alpha li.letter { font-size: 1.4em; padding-bottom: 10px; } #listing ul.alpha ul { margin: 0; padding-left: 15px; } #listing ul small { color: #666; font-size: 0.7em; } li.r1 { background: #f0f0f0; } li.r2 { background: #fafafa; } #search_frame { z-index: 9999; background: #fff; display: none; position: absolute; top: 36px; right: 18px; width: 500px; height: 80%; overflow-y: scroll; border: 1px solid #999; border-collapse: collapse; -webkit-box-shadow: -7px 5px 25px #aaa; -moz-box-shadow: -7px 5px 25px #aaa; -moz-border-radius: 2px; -webkit-border-radius: 2px; } #content ul.summary li.deprecated .summary_signature a:link, #content ul.summary li.deprecated .summary_signature a:visited { text-decoration: line-through; font-style: italic; } #toc { padding: 20px; padding-right: 30px; border: 1px solid #ddd; float: right; background: #fff; margin-left: 20px; margin-bottom: 20px; max-width: 300px; -webkit-box-shadow: -2px 2px 6px #bbb; -moz-box-shadow: -2px 2px 6px #bbb; z-index: 5000; position: relative; overflow-x: auto; } #toc.nofloat { float: none; max-width: none; border: none; padding: 0; margin: 20px 0; -webkit-box-shadow: none; -moz-box-shadow: none; } #toc.nofloat.hidden { padding: 0; background: 0; margin-bottom: 5px; } #toc .title { margin: 0; } #toc ol { padding-left: 1.8em; } #toc li { font-size: 1.1em; line-height: 1.7em; } #toc > ol > li { font-size: 1.1em; font-weight: bold; } #toc ol > ol { font-size: 0.9em; } #toc ol ol > ol { padding-left: 2.3em; } #toc ol + li { margin-top: 0.3em; } #toc.hidden { padding: 10px; background: #f6f6f6; -webkit-box-shadow: none; -moz-box-shadow: none; } #filecontents h1 + #toc.nofloat { margin-top: 0; } /* syntax highlighting */ .source_code { display: none; padding: 3px 8px; border-left: 8px solid #ddd; margin-top: 5px; } #filecontents pre.code, .docstring pre.code, .source_code pre { font-family: monospace; } #filecontents pre.code, .docstring pre.code { display: block; } .source_code .lines { padding-right: 12px; color: #555; text-align: right; } #filecontents pre.code, .docstring pre.code, .tags pre.example { padding: 5px 12px; margin-top: 4px; border: 1px solid #eef; background: #f5f5ff; } pre.code { color: #000; } pre.code .info.file { color: #555; } pre.code .val { color: #036A07; } pre.code .tstring_content, pre.code .heredoc_beg, pre.code .heredoc_end, pre.code .qwords_beg, pre.code .qwords_end, pre.code .tstring, pre.code .dstring { color: #036A07; } pre.code .fid, pre.code .rubyid_new, pre.code .rubyid_to_s, pre.code .rubyid_to_sym, pre.code .rubyid_to_f, pre.code .dot + pre.code .id, pre.code .rubyid_to_i pre.code .rubyid_each { color: #0085FF; } pre.code .comment { color: #0066FF; } pre.code .const, pre.code .constant { color: #585CF6; } pre.code .label, pre.code .symbol { color: #C5060B; } pre.code .kw, pre.code .rubyid_require, pre.code .rubyid_extend, pre.code .rubyid_include { color: #0000FF; } pre.code .ivar { color: #318495; } pre.code .gvar, pre.code .rubyid_backref, pre.code .rubyid_nth_ref { color: #6D79DE; } pre.code .regexp, .dregexp { color: #036A07; } pre.code a { border-bottom: 1px dotted #bbf; } ================================================ FILE: docs/yardoc/file.README.html ================================================ File: README — Documentation by YARD 0.8.7.6

    Build Status

    • Simple API focusing on scalability and low overhead.

    • Reactive and non blocking which able to handle many database connections with a single thread.

    • Ranked #1 in the TechEmpower Benchmark Round 15 Single query benchmark.

    Features

    • Event driven

    • Lightweight

    • Built-in connection pooling

    • Prepared queries caching

    • Publish / subscribe using Postgres LISTEN/NOTIFY

    • Batch and cursor support

    • Row streaming

    • java.util.stream.Collector row set transformation

    • Command pipeling

    • RxJava 1 and RxJava 2

    • Direct memory to object without unnecessary copies

    • Java 8 Date and Time

    • SSL/TLS

    • Unix domain socket

    • HTTP/1.x CONNECT, SOCKS4a or SOCKS5 proxy

    • Request cancellation

    Usage

    Latest release is 0.11.1.

    To use the client, add the following dependency to the dependencies section of your build descriptor:

    • Maven (in your pom.xml) for Vert.x 3.6.x:

    <dependency>
      <groupId>io.reactiverse</groupId>
      <artifactId>reactive-pg-client</artifactId>
      <version>0.11.1</version>
    </dependency>
    • Gradle (in your build.gradle file) for Vert.x 3.6.x:

    dependencies {
      compile 'io.reactiverse:reactive-pg-client:0.11.1'
    }

    If you are using Vertx 3.5.x you should use instead 0.10.9

    Then the code is quite straightforward:

    // Pool options
    PgPoolOptions options = new PgPoolOptions()
      .setPort(5432)
      .setHost("the-host")
      .setDatabase("the-db")
      .setUser("user")
      .setPassword("secret")
      .setMaxSize(5);
    
    // Create the client pool
    PgPool client = PgClient.pool(options);
    
    // A simple query
    client.query("SELECT * FROM users WHERE id='julien'", ar -> {
      if (ar.succeeded()) {
        PgResult<Row> result = ar.result();
        System.out.println("Got " + result.size() + " results ");
      } else {
        System.out.println("Failure: " + ar.cause().getMessage());
      }
    
      // Now close the pool
      client.close();
    });

    Integration / Usages

    • vertx-jooq: writing type safe queries and let them run at high speed using jOOQ, vertx and the reactive-pg-client.

    • Micronaut: supports reactive and non-blocking client to connect to Postgres using reactive-pg-client, allowing to handle many database connections with a single thread.

    Javadoc

    Supported Data Types

    The Reactive Postgres Client currently supports the following data types

_ Value Array

Postgres

Java

Supported

JAVA

Supported

BOOLEAN

j.l.Boolean

j.l.Boolean[]

INT2

j.l.Short

j.l.Short[]

INT4

j.l.Integer

j.l.Integer[]

INT8

j.l.Long

j.l.Long[]

FLOAT4

j.l.Float

j.l.Float[]

FLOAT8

j.l.Double

j.l.Double[]

CHAR

j.l.Character

j.l.Character[]

VARCHAR

j.l.String

j.l.String[]

TEXT

j.l.String

j.l.String[]

ENUM

j.l.String

j.l.String[]

NAME

j.l.String

j.l.String[]

SERIAL2

j.l.Short

invalid type

SERIAL4

j.l.Integer

invalid type

SERIAL8

j.l.Long

invalid type

NUMERIC

i.r.p.data.Numeric

i.r.p.data.Numeric[]

UUID

j.u.UUID

j.u.UUID[]

DATE

j.t.LocalDate

j.t.LocalDate[]

TIME

j.t.LocalTime

j.t.LocalTime[]

TIMETZ

j.t.OffsetTime

j.t.OffsetTime[]

TIMESTAMP

j.t.LocalDateTime

j.t.LocalDateTime[]

TIMESTAMPTZ

j.t.OffsetDateTime

j.t.OffsetDateTime[]

INTERVAL

i.r.p.data.Interval

i.r.p.data.Interval[]

BYTEA

i.v.c.b.Buffer

i.v.c.b.Buffer[]

JSON

i.r.p.data.Json

i.r.p.data.Json[]

JSONB

i.r.p.data.Json

i.r.p.data.Json[]

POINT

i.r.p.data.Point

i.r.p.data.Point[]

LINE

i.r.p.data.Line

i.r.p.data.Line[]

LSEG

i.r.p.data.LineSegment

i.r.p.data.LineSegment[]

BOX

i.r.p.data.Box

i.r.p.data.Box[]

PATH

i.r.p.data.Path

i.r.p.data.Path[]

POLYGON

i.r.p.data.Polygon

i.r.p.data.Polygon[]

CIRCLE

i.r.p.data.Circle

i.r.p.data.Circle[]

UNKNOWN

j.l.String

j.l.String[]

The following types

MONEY, BIT, VARBIT, MACADDR, INET, CIDR, MACADDR8, XML, HSTORE, OID, VOID, TSQUERY, TSVECTOR

are not implemented yet (PR are welcome).

Snapshots

License

Apache License - Version 2.0

Developers

Testing

Out of the box, the test suite runs an embedded Postgres by default.

You can change the version of the embedded Postgres by passing a property embedded.postgres.version like this:

> mvn test -Dembedded.postgres.version=9.6

The following versions of embedded Postgres are supported:

  • 9.6

  • 10.6 (default)

  • 11.1 (not supported on Linux)

Testing with an external database

You can run tests with an external database:

  • the script docker/postgres/resources/create-postgres.sql creates the test data

  • the TLSTest expects the database to be configured with SSL with docker/postgres/resources/server.key / docker/postgres/resources/server.cert`

You need to add some properties for testing:

> mvn test -Dconnection.uri=postgres://$username:$password@$host:$port/$database -Dtls.connection.uri=postgres://$username:$password@$host:$port/$database -Dunix.socket.directory=$path
  • connection.uri(mandatory): configure the client to connect the specified database

  • tls.connection.uri(mandatory): configure the client to run TLSTest with the specified Postgres with SSL enabled

  • unix.socket.directory(optional): the single unix socket directory(multiple socket directories are not supported) to test Unix domain socket with a specified database, domain socket tests will be skipped if this property is not specified (Note: Make sure you can access the unix domain socket with this directory under your host machine)

  • unix.socket.port(optional): unix socket file is named .s.PGSQL.nnnn and nnnn is the server’s port number, this property is mostly used when you test with Docker, when you publish your Postgres container port other than 5432 in your host but Postgres may actually listen on a different port in the container, you will then need this property to help you connect the Postgres with Unix domain socket

Testing with Docker

Run the Postgres containers with docker-compose:

> cd docker/postgres
> docker-compose up --build -V

Run tests:

> mvn test -Dconnection.uri=postgres://$username:$password@$host:$port/$database -Dtls.connection.uri=postgres://$username:$password@$host:$port/$database -Dunix.socket.directory=$path -Dunix.socket.port=$port

Documentation

The online and published documentation is in /docs and is served by GitHub pages with Jekyll.

You can find the actual guide source in [src/main/docs/index.md](src/main/docs/index.md). At compilation time, this source generates the jekyll/guide/java/index.md.

The current documentation is in /jekyll and can be preview using Docker and your browser

  • generate the documentation

    • mvn compile to generate jekyll/guide/java/index.md

    • mvn site to generate the javadoc in jekyll/apidocs

  • run Jekyll

    • cd jekyll

    • docker-compose up

  • open your browser at http://localhost:4000

================================================ FILE: docs/yardoc/file_list.html ================================================ File List ================================================ FILE: docs/yardoc/frames.html ================================================ Documentation by YARD 0.8.7.6 ================================================ FILE: docs/yardoc/index.html ================================================ File: README — Documentation by YARD 0.8.7.6

Build Status

  • Simple API focusing on scalability and low overhead.

  • Reactive and non blocking which able to handle many database connections with a single thread.

  • Ranked #1 in the TechEmpower Benchmark Round 15 Single query benchmark.

Features

  • Event driven

  • Lightweight

  • Built-in connection pooling

  • Prepared queries caching

  • Publish / subscribe using Postgres LISTEN/NOTIFY

  • Batch and cursor support

  • Row streaming

  • java.util.stream.Collector row set transformation

  • Command pipeling

  • RxJava 1 and RxJava 2

  • Direct memory to object without unnecessary copies

  • Java 8 Date and Time

  • SSL/TLS

  • Unix domain socket

  • HTTP/1.x CONNECT, SOCKS4a or SOCKS5 proxy

  • Request cancellation

Usage

Latest release is 0.11.1.

To use the client, add the following dependency to the dependencies section of your build descriptor:

  • Maven (in your pom.xml) for Vert.x 3.6.x:

<dependency>
  <groupId>io.reactiverse</groupId>
  <artifactId>reactive-pg-client</artifactId>
  <version>0.11.1</version>
</dependency>
  • Gradle (in your build.gradle file) for Vert.x 3.6.x:

dependencies {
  compile 'io.reactiverse:reactive-pg-client:0.11.1'
}

If you are using Vertx 3.5.x you should use instead 0.10.9

Then the code is quite straightforward:

// Pool options
PgPoolOptions options = new PgPoolOptions()
  .setPort(5432)
  .setHost("the-host")
  .setDatabase("the-db")
  .setUser("user")
  .setPassword("secret")
  .setMaxSize(5);

// Create the client pool
PgPool client = PgClient.pool(options);

// A simple query
client.query("SELECT * FROM users WHERE id='julien'", ar -> {
  if (ar.succeeded()) {
    PgResult<Row> result = ar.result();
    System.out.println("Got " + result.size() + " results ");
  } else {
    System.out.println("Failure: " + ar.cause().getMessage());
  }

  // Now close the pool
  client.close();
});

Integration / Usages

  • vertx-jooq: writing type safe queries and let them run at high speed using jOOQ, vertx and the reactive-pg-client.

  • Micronaut: supports reactive and non-blocking client to connect to Postgres using reactive-pg-client, allowing to handle many database connections with a single thread.

Javadoc

Supported Data Types

The Reactive Postgres Client currently supports the following data types

_ Value Array

Postgres

Java

Supported

JAVA

Supported

BOOLEAN

j.l.Boolean

j.l.Boolean[]

INT2

j.l.Short

j.l.Short[]

INT4

j.l.Integer

j.l.Integer[]

INT8

j.l.Long

j.l.Long[]

FLOAT4

j.l.Float

j.l.Float[]

FLOAT8

j.l.Double

j.l.Double[]

CHAR

j.l.Character

j.l.Character[]

VARCHAR

j.l.String

j.l.String[]

TEXT

j.l.String

j.l.String[]

ENUM

j.l.String

j.l.String[]

NAME

j.l.String

j.l.String[]

SERIAL2

j.l.Short

invalid type

SERIAL4

j.l.Integer

invalid type

SERIAL8

j.l.Long

invalid type

NUMERIC

i.r.p.data.Numeric

i.r.p.data.Numeric[]

UUID

j.u.UUID

j.u.UUID[]

DATE

j.t.LocalDate

j.t.LocalDate[]

TIME

j.t.LocalTime

j.t.LocalTime[]

TIMETZ

j.t.OffsetTime

j.t.OffsetTime[]

TIMESTAMP

j.t.LocalDateTime

j.t.LocalDateTime[]

TIMESTAMPTZ

j.t.OffsetDateTime

j.t.OffsetDateTime[]

INTERVAL

i.r.p.data.Interval

i.r.p.data.Interval[]

BYTEA

i.v.c.b.Buffer

i.v.c.b.Buffer[]

JSON

i.r.p.data.Json

i.r.p.data.Json[]

JSONB

i.r.p.data.Json

i.r.p.data.Json[]

POINT

i.r.p.data.Point

i.r.p.data.Point[]

LINE

i.r.p.data.Line

i.r.p.data.Line[]

LSEG

i.r.p.data.LineSegment

i.r.p.data.LineSegment[]

BOX

i.r.p.data.Box

i.r.p.data.Box[]

PATH

i.r.p.data.Path

i.r.p.data.Path[]

POLYGON

i.r.p.data.Polygon

i.r.p.data.Polygon[]

CIRCLE

i.r.p.data.Circle

i.r.p.data.Circle[]

UNKNOWN

j.l.String

j.l.String[]

The following types

MONEY, BIT, VARBIT, MACADDR, INET, CIDR, MACADDR8, XML, HSTORE, OID, VOID, TSQUERY, TSVECTOR

are not implemented yet (PR are welcome).

Snapshots

License

Apache License - Version 2.0

Developers

Testing

Out of the box, the test suite runs an embedded Postgres by default.

You can change the version of the embedded Postgres by passing a property embedded.postgres.version like this:

> mvn test -Dembedded.postgres.version=9.6

The following versions of embedded Postgres are supported:

  • 9.6

  • 10.6 (default)

  • 11.1 (not supported on Linux)

Testing with an external database

You can run tests with an external database:

  • the script docker/postgres/resources/create-postgres.sql creates the test data

  • the TLSTest expects the database to be configured with SSL with docker/postgres/resources/server.key / docker/postgres/resources/server.cert`

You need to add some properties for testing:

> mvn test -Dconnection.uri=postgres://$username:$password@$host:$port/$database -Dtls.connection.uri=postgres://$username:$password@$host:$port/$database -Dunix.socket.directory=$path
  • connection.uri(mandatory): configure the client to connect the specified database

  • tls.connection.uri(mandatory): configure the client to run TLSTest with the specified Postgres with SSL enabled

  • unix.socket.directory(optional): the single unix socket directory(multiple socket directories are not supported) to test Unix domain socket with a specified database, domain socket tests will be skipped if this property is not specified (Note: Make sure you can access the unix domain socket with this directory under your host machine)

  • unix.socket.port(optional): unix socket file is named .s.PGSQL.nnnn and nnnn is the server’s port number, this property is mostly used when you test with Docker, when you publish your Postgres container port other than 5432 in your host but Postgres may actually listen on a different port in the container, you will then need this property to help you connect the Postgres with Unix domain socket

Testing with Docker

Run the Postgres containers with docker-compose:

> cd docker/postgres
> docker-compose up --build -V

Run tests:

> mvn test -Dconnection.uri=postgres://$username:$password@$host:$port/$database -Dtls.connection.uri=postgres://$username:$password@$host:$port/$database -Dunix.socket.directory=$path -Dunix.socket.port=$port

Documentation

The online and published documentation is in /docs and is served by GitHub pages with Jekyll.

You can find the actual guide source in [src/main/docs/index.md](src/main/docs/index.md). At compilation time, this source generates the jekyll/guide/java/index.md.

The current documentation is in /jekyll and can be preview using Docker and your browser

  • generate the documentation

    • mvn compile to generate jekyll/guide/java/index.md

    • mvn site to generate the javadoc in jekyll/apidocs

  • run Jekyll

    • cd jekyll

    • docker-compose up

  • open your browser at http://localhost:4000

================================================ FILE: docs/yardoc/js/app.js ================================================ function createSourceLinks() { $('.method_details_list .source_code'). before("[View source]"); $('.toggleSource').toggle(function() { $(this).parent().nextAll('.source_code').slideDown(100); $(this).text("Hide source"); }, function() { $(this).parent().nextAll('.source_code').slideUp(100); $(this).text("View source"); }); } function createDefineLinks() { var tHeight = 0; $('.defines').after(" more..."); $('.toggleDefines').toggle(function() { tHeight = $(this).parent().prev().height(); $(this).prev().show(); $(this).parent().prev().height($(this).parent().height()); $(this).text("(less)"); }, function() { $(this).prev().hide(); $(this).parent().prev().height(tHeight); $(this).text("more..."); }); } function createFullTreeLinks() { var tHeight = 0; $('.inheritanceTree').toggle(function() { tHeight = $(this).parent().prev().height(); $(this).parent().toggleClass('showAll'); $(this).text("(hide)"); $(this).parent().prev().height($(this).parent().height()); }, function() { $(this).parent().toggleClass('showAll'); $(this).parent().prev().height(tHeight); $(this).text("show all"); }); } function fixBoxInfoHeights() { $('dl.box dd.r1, dl.box dd.r2').each(function() { $(this).prev().height($(this).height()); }); } function searchFrameLinks() { $('.full_list_link').click(function() { toggleSearchFrame(this, $(this).attr('href')); return false; }); } function toggleSearchFrame(id, link) { var frame = $('#search_frame'); $('#search a').removeClass('active').addClass('inactive'); if (frame.attr('src') == link && frame.css('display') != "none") { frame.slideUp(100); $('#search a').removeClass('active inactive'); } else { $(id).addClass('active').removeClass('inactive'); frame.attr('src', link).slideDown(100); } } function linkSummaries() { $('.summary_signature').click(function() { document.location = $(this).find('a').attr('href'); }); } function framesInit() { if (hasFrames) { document.body.className = 'frames'; $('#menu .noframes a').attr('href', document.location); try { window.top.document.title = $('html head title').text(); } catch(error) { // some browsers will not allow this when serving from file:// // but we don't want to stop the world. } } else { $('#menu .noframes a').text('frames').attr('href', framesUrl); } } function keyboardShortcuts() { if (window.top.frames.main) return; $(document).keypress(function(evt) { if (evt.altKey || evt.ctrlKey || evt.metaKey || evt.shiftKey) return; if (typeof evt.target !== "undefined" && (evt.target.nodeName == "INPUT" || evt.target.nodeName == "TEXTAREA")) return; switch (evt.charCode) { case 67: case 99: $('#class_list_link').click(); break; // 'c' case 77: case 109: $('#method_list_link').click(); break; // 'm' case 70: case 102: $('#file_list_link').click(); break; // 'f' default: break; } }); } function summaryToggle() { $('.summary_toggle').click(function() { if (localStorage) { localStorage.summaryCollapsed = $(this).text(); } $('.summary_toggle').each(function() { $(this).text($(this).text() == "collapse" ? "expand" : "collapse"); var next = $(this).parent().parent().nextAll('ul.summary').first(); if (next.hasClass('compact')) { next.toggle(); next.nextAll('ul.summary').first().toggle(); } else if (next.hasClass('summary')) { var list = $('
    '); list.html(next.html()); list.find('.summary_desc, .note').remove(); list.find('a').each(function() { $(this).html($(this).find('strong').html()); $(this).parent().html($(this)[0].outerHTML); }); next.before(list); next.toggle(); } }); return false; }); if (localStorage) { if (localStorage.summaryCollapsed == "collapse") { $('.summary_toggle').first().click(); } else localStorage.summaryCollapsed = "expand"; } } function fixOutsideWorldLinks() { $('a').each(function() { if (window.location.host != this.host) this.target = '_parent'; }); } function generateTOC() { if ($('#filecontents').length === 0) return; var _toc = $('
      '); var show = false; var toc = _toc; var counter = 0; var tags = ['h2', 'h3', 'h4', 'h5', 'h6']; var i; if ($('#filecontents h1').length > 1) tags.unshift('h1'); for (i = 0; i < tags.length; i++) { tags[i] = '#filecontents ' + tags[i]; } var lastTag = parseInt(tags[0][1], 10); $(tags.join(', ')).each(function() { if ($(this).parents('.method_details .docstring').length != 0) return; if (this.id == "filecontents") return; show = true; var thisTag = parseInt(this.tagName[1], 10); if (this.id.length === 0) { var proposedId = $(this).attr('toc-id'); if (typeof(proposedId) != "undefined") this.id = proposedId; else { var proposedId = $(this).text().replace(/[^a-z0-9-]/ig, '_'); if ($('#' + proposedId).length > 0) { proposedId += counter; counter++; } this.id = proposedId; } } if (thisTag > lastTag) { for (i = 0; i < thisTag - lastTag; i++) { var tmp = $('
        '); toc.append(tmp); toc = tmp; } } if (thisTag < lastTag) { for (i = 0; i < lastTag - thisTag; i++) toc = toc.parent(); } var title = $(this).attr('toc-title'); if (typeof(title) == "undefined") title = $(this).text(); toc.append('
      1. ' + title + '
      2. '); lastTag = thisTag; }); if (!show) return; html = ''; $('#content').prepend(html); $('#toc').append(_toc); $('#toc .hide_toc').toggle(function() { $('#toc .top').slideUp('fast'); $('#toc').toggleClass('hidden'); $('#toc .title small').toggle(); }, function() { $('#toc .top').slideDown('fast'); $('#toc').toggleClass('hidden'); $('#toc .title small').toggle(); }); $('#toc .float_toc').toggle(function() { $(this).text('float'); $('#toc').toggleClass('nofloat'); }, function() { $(this).text('left'); $('#toc').toggleClass('nofloat'); }); } $(framesInit); $(createSourceLinks); $(createDefineLinks); $(createFullTreeLinks); $(fixBoxInfoHeights); $(searchFrameLinks); $(linkSummaries); $(keyboardShortcuts); $(summaryToggle); $(fixOutsideWorldLinks); $(generateTOC); ================================================ FILE: docs/yardoc/js/full_list.js ================================================ var inSearch = null; var searchIndex = 0; var searchCache = []; var searchString = ''; var regexSearchString = ''; var caseSensitiveMatch = false; var ignoreKeyCodeMin = 8; var ignoreKeyCodeMax = 46; var commandKey = 91; RegExp.escape = function(text) { return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); } function fullListSearch() { // generate cache searchCache = []; $('#full_list li').each(function() { var link = $(this).find('.object_link a'); if (link.length === 0) return; var fullName = link.attr('title').split(' ')[0]; searchCache.push({name:link.text(), fullName:fullName, node:$(this), link:link}); }); $('#search input').keyup(function(event) { if ((event.keyCode > ignoreKeyCodeMin && event.keyCode < ignoreKeyCodeMax) || event.keyCode == commandKey) return; searchString = this.value; caseSensitiveMatch = searchString.match(/[A-Z]/) != null; regexSearchString = RegExp.escape(searchString); if (caseSensitiveMatch) { regexSearchString += "|" + $.map(searchString.split(''), function(e) { return RegExp.escape(e); }). join('.+?'); } if (searchString === "") { clearTimeout(inSearch); inSearch = null; $('ul .search_uncollapsed').removeClass('search_uncollapsed'); $('#full_list, #content').removeClass('insearch'); $('#full_list li').removeClass('found').each(function() { var link = $(this).find('.object_link a'); if (link.length > 0) link.text(link.text()); }); if (clicked) { clicked.parents('ul').each(function() { $(this).removeClass('collapsed').prev().removeClass('collapsed'); }); } highlight(); } else { if (inSearch) clearTimeout(inSearch); searchIndex = 0; lastRowClass = ''; $('#full_list, #content').addClass('insearch'); $('#noresults').text(''); searchItem(); } }); $('#search input').focus(); $('#full_list').after("
        "); } var lastRowClass = ''; function searchItem() { for (var i = 0; i < searchCache.length / 50; i++) { var item = searchCache[searchIndex]; var searchName = (searchString.indexOf('::') != -1 ? item.fullName : item.name); var matchString = regexSearchString; var matchRegexp = new RegExp(matchString, caseSensitiveMatch ? "" : "i"); if (searchName.match(matchRegexp) == null) { item.node.removeClass('found'); } else { item.node.css('padding-left', '10px').addClass('found'); item.node.parents().addClass('search_uncollapsed'); item.node.removeClass(lastRowClass).addClass(lastRowClass == 'r1' ? 'r2' : 'r1'); lastRowClass = item.node.hasClass('r1') ? 'r1' : 'r2'; item.link.html(item.name.replace(matchRegexp, "$&")); } if (searchCache.length === searchIndex + 1) { searchDone(); return; } else { searchIndex++; } } inSearch = setTimeout('searchItem()', 0); } function searchDone() { highlight(true); if ($('#full_list li:visible').size() === 0) { $('#noresults').text('No results were found.').hide().fadeIn(); } else { $('#noresults').text(''); } $('#content').removeClass('insearch'); clearTimeout(inSearch); inSearch = null; } clicked = null; function linkList() { $('#full_list li, #full_list li a:last').click(function(evt) { if ($(this).hasClass('toggle')) return true; if (this.tagName.toLowerCase() == "li") { if ($(this).find('.object_link a').length === 0) { $(this).children('a.toggle').click(); return false; } var toggle = $(this).children('a.toggle'); if (toggle.size() > 0 && evt.pageX < toggle.offset().left) { toggle.click(); return false; } } if (clicked) clicked.removeClass('clicked'); var win; try { win = window.top.frames.main ? window.top.frames.main : window.parent; } catch (e) { win = window.parent; } if (this.tagName.toLowerCase() == "a") { clicked = $(this).parents('li').addClass('clicked'); win.location = this.href; } else { clicked = $(this).addClass('clicked'); win.location = $(this).find('a:last').attr('href'); } return false; }); } function collapse() { if (!$('#full_list').hasClass('class')) return; $('#full_list.class a.toggle').click(function() { $(this).parent().toggleClass('collapsed').next().toggleClass('collapsed'); highlight(); return false; }); $('#full_list.class ul').each(function() { $(this).addClass('collapsed').prev().addClass('collapsed'); }); $('#full_list.class').children().removeClass('collapsed'); highlight(); } function highlight(no_padding) { var n = 1; $('#full_list li:visible').each(function() { var next = n == 1 ? 2 : 1; $(this).removeClass("r" + next).addClass("r" + n); if (!no_padding && $('#full_list').hasClass('class')) { $(this).css('padding-left', (10 + $(this).parents('ul').size() * 15) + 'px'); } n = next; }); } function escapeShortcut() { $(document).keydown(function(evt) { if (evt.which == 27) { $('#search_frame', window.top.document).slideUp(100); $('#search a', window.top.document).removeClass('active inactive'); $(window.top).focus(); } }); } $(escapeShortcut); $(fullListSearch); $(linkList); $(collapse); ================================================ FILE: docs/yardoc/js/jquery.js ================================================ /*! jQuery v1.7.1 jquery.com | jquery.org/license */ (function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cv(a){if(!ck[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){cl||(cl=c.createElement("iframe"),cl.frameBorder=cl.width=cl.height=0),b.appendChild(cl);if(!cm||!cl.createElement)cm=(cl.contentWindow||cl.contentDocument).document,cm.write((c.compatMode==="CSS1Compat"?"":"")+""),cm.close();d=cm.createElement(a),cm.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cl)}ck[a]=e}return ck[a]}function cu(a,b){var c={};f.each(cq.concat.apply([],cq.slice(0,b)),function(){c[this]=a});return c}function ct(){cr=b}function cs(){setTimeout(ct,0);return cr=f.now()}function cj(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ci(){try{return new a.XMLHttpRequest}catch(b){}}function cc(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g0){if(c!=="border")for(;g=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?parseFloat(d):j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.1",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c
        a",d=q.getElementsByTagName("*"),e=q.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=q.getElementsByTagName("input")[0],b={leadingWhitespace:q.firstChild.nodeType===3,tbody:!q.getElementsByTagName("tbody").length,htmlSerialize:!!q.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:q.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete q.test}catch(s){b.deleteExpando=!1}!q.addEventListener&&q.attachEvent&&q.fireEvent&&(q.attachEvent("onclick",function(){b.noCloneEvent=!1}),q.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),q.appendChild(i),k=c.createDocumentFragment(),k.appendChild(q.lastChild),b.checkClone=k.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,k.removeChild(i),k.appendChild(q),q.innerHTML="",a.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",q.style.width="2px",q.appendChild(j),b.reliableMarginRight=(parseInt((a.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(q.attachEvent)for(o in{submit:1,change:1,focusin:1})n="on"+o,p=n in q,p||(q.setAttribute(n,"return;"),p=typeof q[n]=="function"),b[o+"Bubbles"]=p;k.removeChild(q),k=g=h=j=q=i=null,f(function(){var a,d,e,g,h,i,j,k,m,n,o,r=c.getElementsByTagName("body")[0];!r||(j=1,k="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",m="visibility:hidden;border:0;",n="style='"+k+"border:5px solid #000;padding:0;'",o="
        "+""+"
        ",a=c.createElement("div"),a.style.cssText=m+"width:0;height:0;position:static;top:0;margin-top:"+j+"px",r.insertBefore(a,r.firstChild),q=c.createElement("div"),a.appendChild(q),q.innerHTML="
        t
        ",l=q.getElementsByTagName("td"),p=l[0].offsetHeight===0,l[0].style.display="",l[1].style.display="none",b.reliableHiddenOffsets=p&&l[0].offsetHeight===0,q.innerHTML="",q.style.width=q.style.paddingLeft="1px",f.boxModel=b.boxModel=q.offsetWidth===2,typeof q.style.zoom!="undefined"&&(q.style.display="inline",q.style.zoom=1,b.inlineBlockNeedsLayout=q.offsetWidth===2,q.style.display="",q.innerHTML="
        ",b.shrinkWrapBlocks=q.offsetWidth!==2),q.style.cssText=k+m,q.innerHTML=o,d=q.firstChild,e=d.firstChild,h=d.nextSibling.firstChild.firstChild,i={doesNotAddBorder:e.offsetTop!==5,doesAddBorderForTableAndCells:h.offsetTop===5},e.style.position="fixed",e.style.top="20px",i.fixedPosition=e.offsetTop===20||e.offsetTop===15,e.style.position=e.style.top="",d.style.overflow="hidden",d.style.position="relative",i.subtractsBorderForOverflowNotVisible=e.offsetTop===-5,i.doesNotIncludeMarginInBodyOffset=r.offsetTop!==j,r.removeChild(a),q=a=null,f.extend(b,i))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.nodeName.toLowerCase()]||f.valHooks[g.type];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;h=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/\bhover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function(a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")}; f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;le&&i.push({elem:this,matches:d.slice(e)});for(j=0;j0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return bc[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="

        ";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="
        ";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h0)for(h=g;h=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/",""],legend:[1,"
        ","
        "],thead:[1,"","
        "],tr:[2,"","
        "],td:[3,"","
        "],col:[2,"","
        "],area:[1,"",""],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div
        ","
        "]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function() {for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1>");try{for(var c=0,d=this.length;c1&&l0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||!bc.test("<"+a.nodeName)?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!_.test(k))k=b.createTextNode(k);else{k=k.replace(Y,"<$1>");var l=(Z.exec(k)||["",""])[1].toLowerCase(),m=bg[l]||bg._default,n=m[0],o=b.createElement("div");b===c?bh.appendChild(o):U(b).appendChild(o),o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=$.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]===""&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&X.test(k)&&o.insertBefore(b.createTextNode(X.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return br.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bq,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bq.test(g)?g.replace(bq,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bz(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bA=function(a,b){var c,d,e;b=b.replace(bs,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b)));return c}),c.documentElement.currentStyle&&(bB=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f===null&&g&&(e=g[b])&&(f=e),!bt.test(f)&&bu.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f||0,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),bz=bA||bB,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bD=/%20/g,bE=/\[\]$/,bF=/\r?\n/g,bG=/#.*$/,bH=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bI=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bJ=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bK=/^(?:GET|HEAD)$/,bL=/^\/\//,bM=/\?/,bN=/)<[^<]*)*<\/script>/gi,bO=/^(?:select|textarea)/i,bP=/\s+/,bQ=/([?&])_=[^&]*/,bR=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bS=f.fn.load,bT={},bU={},bV,bW,bX=["*/"]+["*"];try{bV=e.href}catch(bY){bV=c.createElement("a"),bV.href="",bV=bV.href}bW=bR.exec(bV.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bS)return bS.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("
        ").append(c.replace(bN,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bO.test(this.nodeName)||bI.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bF,"\r\n")}}):{name:b.name,value:c.replace(bF,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b_(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b_(a,b);return a},ajaxSettings:{url:bV,isLocal:bJ.test(bW[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bX},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bZ(bT),ajaxTransport:bZ(bU),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?cb(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cc(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bH.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bG,"").replace(bL,bW[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bP),d.crossDomain==null&&(r=bR.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bW[1]&&r[2]==bW[2]&&(r[3]||(r[1]==="http:"?80:443))==(bW[3]||(bW[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),b$(bT,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bK.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bM.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bQ,"$1_="+x);d.url=y+(y===d.url?(bM.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bX+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=b$(bU,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)ca(g,a[g],c,e);return d.join("&").replace(bD,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cd=f.now(),ce=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cd++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(ce.test(b.url)||e&&ce.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(ce,l),b.url===j&&(e&&(k=k.replace(ce,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var cf=a.ActiveXObject?function(){for(var a in ch)ch[a](0,1)}:!1,cg=0,ch;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ci()||cj()}:ci,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,cf&&delete ch[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cg,cf&&(ch||(ch={},f(a).unload(cf)),ch[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var ck={},cl,cm,cn=/^(?:toggle|show|hide)$/,co=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cp,cq=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cr;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cu("show",3),a,b,c);for(var g=0,h=this.length;g=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cy(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cy(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,d,"padding")):this[d]():null},f.fn["outer"+c]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,d,a?"margin":"border")):this[d]():null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var i=f.css(e,d),j=parseFloat(i);return f.isNumeric(j)?j:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window); ================================================ FILE: docs/yardoc/method_list.html ================================================ Method List

        Method List

        ================================================ FILE: docs/yardoc/top-level-namespace.html ================================================ Top Level Namespace — Documentation by YARD 0.8.7.6

        Top Level Namespace

        Defined Under Namespace

        Modules: ReactivePgClient

        ================================================ FILE: jekyll/README.md ================================================ # The Reactive Postgres Client * Simple API focusing on scalability and low overhead. * Reactive and non blocking which able to handle many database connections with a single thread. * Ranked *#1* in the [TechEmpower Benchmark Round 15](https://www.techempower.com/benchmarks/#section=data-r15&hw=ph&test=db) _Single query_ benchmark. ## Features * Event driven * Lightweight * Built-in connection pooling * Prepared queries caching * Publish / subscribe using Postgres `LISTEN/NOTIFY` * Batch and cursor support * Row streaming * Command pipeling * RxJava 1 and RxJava 2 support * Direct memory to object without unnecessary copies * Java 8 Date and Time support * SSL/TLS support * HTTP/1.x CONNECT, SOCKS4a or SOCKS5 proxy support ## Documentation * [Java](guide/java/index.md) * [Kotlin](guide/kotlin/index.md) * [Groovy](guide/groovy/index.md) * [JavaScript](guide/js/index.md) * [Ruby](guide/ruby/index.md) ================================================ FILE: jekyll/_config.yml ================================================ theme: jekyll-theme-minimal repository: reactiverse/reactive-pg-client ================================================ FILE: jekyll/docker-compose.yml ================================================ jekyll: image: jekyll/jekyll:pages command: jekyll serve --watch --incremental ports: - 4000:4000 volumes: - .:/srv/jekyll ================================================ FILE: jitwatch.properties ================================================ #Thu Dec 14 09:48:37 CET 2017 sandbox.on.stack.replacement=0 Sources=/Users/julien/java/vertx-pg-client/src/main/java,/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home/src.zip,/Users/julien/java/vertx-pg-client/src/benchmark/java,/Users/julien/java/vertx-pg-client/src/test/java HideInterfaces=true sandbox.disable.inlining=false sandbox.intel.mode=false sandbox.print.assembly=true JitOnlyClasses=false Classes=/Users/julien/java/vertx-pg-client/target/classes,/Users/julien/java/vertx-pg-client/target/test-classes sandbox.compressed.oops.mode=0 triview.local_asm_labels=true sandbox.tiered.mode=0 sandbox.compiler.threshold=10000 ShowNothingMounted=true sandbox.background.compilation=2 sandbox.freq.inline.size=35 sandbox.extra.vm.switches= LastLogDir=/Users/julien/java/vertx-pg-client last.profile=Default triview.mouse_follow=false sandbox.max.inline.size=325 LastSandboxEditorPanes= JitOnly=true ================================================ FILE: jitwatch.sh ================================================ java -XX:+UnlockDiagnosticVMOptions -XX:+TraceClassLoading -XX:+LogCompilation -jar target/vertx-pg-client-0.3.1-SNAPSHOT-benchmarks.jar ================================================ FILE: pom.xml ================================================ 4.0.0 io.vertx vertx-parent 12 io.reactiverse reactive-pg-client 0.11.5-SNAPSHOT Reactive Postgres Client https://github.com/reactiverse/reactive-pg-client The reactive Postgres client The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt repo scm:git:git@github.com:vietj/reactive-pg-client.git scm:git:git@github.com:vietj/reactive-pg-client.git git@github.com:vietj/reactive-pg-client.git Julien Viet julien@julienviet.com Emad Alblueshi emad.albloushi@gmail.com 3.7.1 1.19 ${project.basedir}/src/main/docs ${project.basedir}/src/main/generated true 1.3.0 io.vertx vertx-dependencies ${stack.version} pom import io.vertx vertx-core io.vertx vertx-codegen provided io.vertx vertx-docgen 0.9.0 provided io.vertx vertx-codetrans provided io.vertx vertx-rx-java true io.vertx vertx-rx-java-gen ${stack.version} true io.vertx vertx-rx-java2 true io.vertx vertx-rx-java2-gen ${stack.version} true io.vertx vertx-lang-js true io.vertx vertx-lang-ruby true io.vertx vertx-lang-groovy true io.vertx vertx-lang-kotlin true io.vertx vertx-lang-kotlin-coroutines true io.vertx vertx-lang-kotlin-gen ${stack.version} true junit junit 4.12 test io.vertx vertx-unit test io.netty netty-transport-native-epoll linux-x86_64 test io.netty netty-transport-native-kqueue osx-x86_64 test ru.yandex.qatools.embed postgresql-embedded 2.10 test org.postgresql postgresql 42.1.1 test org.openjdk.jmh jmh-core ${jmh.version} test org.openjdk.jmh jmh-generator-annprocess ${jmh.version} test maven-clean-plugin default-clean ${generated.dir} maven-compiler-plugin default-compile io.vertx.codegen.CodeGenProcessor io.vertx.docgen.JavaDocGenProcessor io.vertx.docgen.DocGenProcessor -Acodegen.output=${project.basedir}/src/main -Adocgen.source=${docs.dir}/*.md -Adocgen.output=${project.basedir}/jekyll/guide/$lang -Adocgen.syntax=markdown -Amaven.groupId=${project.groupId} -Amaven.artifactId=${project.artifactId} -Amaven.version=${project.version} maven-surefire-plugin -Xmx1024M ${project.build.directory} ${embedded.postgres.version} ${connection.uri} ${tls.connection.uri} ${unix.socket.directory} ${unix.socket.port} io/reactiverse/pgclient/it/** org.codehaus.mojo build-helper-maven-plugin 3.0.0 add-source generate-sources add-source ${generated.dir} add-test-source add-test-source ${project.basedir}/src/benchmark/java maven-failsafe-plugin 2.21.0 env-test integration-test integration-test io/reactiverse/pgclient/it/EnvTest.java test_host test_database 1234 test_user test_password require maven-javadoc-plugin ${project.build.sourceDirectory};${project.build.directory}/generated-sources/annotations io/reactiverse/**/*.java io/reactiverse/groovy/**/*.java **/package-info.java **/impl/** http://vertx.io/docs/apidocs/ http://reactivex.io/RxJava/1.x/javadoc/ http://reactivex.io/RxJava/javadoc/ http://fasterxml.github.com/jackson-annotations/javadoc/2.9/ http://fasterxml.github.io/jackson-core/javadoc/2.9/ http://fasterxml.github.io/jackson-databind/javadoc/2.9/ kotlin-maven-plugin org.jetbrains.kotlin ${kotlin.version} 1.8 ${basedir}/src/main/kotlin compile compile maven-assembly-plugin package-sources package single true src/assembly/sources.xml benchmark maven-assembly-plugin package-benchmark package single io.reactiverse.pgclient.RawBenchmark src/assembly/benchmark.xml false jitwatch com.chrisnewland jitwatch 1.0.0 org.codehaus.mojo exec-maven-plugin default-cli java org.adoptopenjdk.jitwatch.launch.LaunchUI false compile site-gen !skipSite rubygems-releases http://rubygems-proxy.torquebox.org/releases rubygems-releases http://rubygems-proxy.torquebox.org/releases org.apache.maven.plugins maven-site-plugin 3.4 true true maven-javadoc-plugin site false ${project.basedir}/jekyll javadoc de.saumya.mojo gem-maven-plugin 1.1.4 exec site ${project.build.directory}/rubygems/bin/yardoc --no-private -m html -o ${project.basedir}/jekyll/yardoc ${project.build.outputDirectory}/**/*.rb rubygems yard 0.8.7.6 gem rubygems asciidoctor 1.5.6 gem com.phasebash.jsdoc jsdoc3-maven-plugin site jsdoc3 true ${project.build.outputDirectory} ${project.basedir}/jekyll/jsdoc ================================================ FILE: src/assembly/benchmark.xml ================================================ benchmark jar false ${project.build.testOutputDirectory} / / true test ================================================ FILE: src/assembly/sources.xml ================================================ sources jar false ${project.basedir}/src/main/java ./ ${project.build.directory}/generated-sources/annotations ./ ================================================ FILE: src/benchmark/java/io/reactiverse/pgclient/BenchmarkBase.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import org.openjdk.jmh.annotations.*; import java.util.concurrent.TimeUnit; /** * @author Julien Viet */ @Warmup(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 10, time = 2, timeUnit = TimeUnit.SECONDS) @Threads(1) @BenchmarkMode(Mode.Throughput) @Fork(value = 1, jvmArgs = { "-XX:+UseBiasedLocking", "-XX:BiasedLockingStartupDelay=0", "-XX:+AggressiveOpts", }) @OutputTimeUnit(TimeUnit.SECONDS) public abstract class BenchmarkBase { } ================================================ FILE: src/benchmark/java/io/reactiverse/pgclient/LargeSelectBenchmark.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.infra.Blackhole; import java.util.concurrent.CompletableFuture; @State(Scope.Benchmark) @Threads(8) public class LargeSelectBenchmark extends PgBenchmarkBase { @Benchmark public void poolPreparedQuery(Blackhole blackhole) throws Exception { CompletableFuture latch = new CompletableFuture<>(); pool.preparedQuery("SELECT id, randomnumber from WORLD", ar -> { if (ar.succeeded()) { latch.complete(ar.result()); } else { latch.completeExceptionally(ar.cause()); } }); blackhole.consume(latch.get()); } @Benchmark public void pooledConnectionPreparedQuery(Blackhole blackhole) throws Exception { CompletableFuture latch = new CompletableFuture<>(); pool.getConnection(ar1 -> { if (ar1.succeeded()) { PgConnection conn = ar1.result(); conn.preparedQuery("SELECT id, randomnumber from WORLD", ar2 -> { conn.close(); if (ar2.succeeded()) { latch.complete(ar2.result()); } else { latch.completeExceptionally(ar2.cause()); } }); } else { latch.completeExceptionally(ar1.cause()); } }); blackhole.consume(latch.get()); } @Benchmark public void pooledConnectionPreparedStatementQuery(Blackhole blackhole) throws Exception { CompletableFuture latch = new CompletableFuture<>(); pool.getConnection(ar1 -> { if (ar1.succeeded()) { PgConnection conn = ar1.result(); conn.prepare("SELECT id, randomnumber from WORLD", ar2 -> { if (ar2.succeeded()) { PgPreparedQuery ps = ar2.result(); ps.execute(ar3 -> { conn.close(); if (ar3.succeeded()) { latch.complete(ar3.result()); } else { latch.completeExceptionally(ar3.cause()); } }); } else { latch.completeExceptionally(ar2.cause()); } }); } else { latch.completeExceptionally(ar1.cause()); } }); blackhole.consume(latch.get()); } } ================================================ FILE: src/benchmark/java/io/reactiverse/pgclient/Main.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import org.openjdk.jmh.runner.*; import org.openjdk.jmh.runner.options.*; import java.util.Arrays; public class Main { public static void main(String[] argv) throws Exception { PgConnectOptions options = PgTestBase.startPg(); int len = argv.length; argv = Arrays.copyOf(argv, len + 10); argv[len] = "-p"; argv[len + 1] = "host=" + options.getHost(); argv[len + 2] = "-p"; argv[len + 3] = "port=" + options.getPort(); argv[len + 4] = "-p"; argv[len + 5] = "database=" + options.getDatabase(); argv[len + 6] = "-p"; argv[len + 7] = "username=" + options.getUser(); argv[len + 8] = "-p"; argv[len + 9] = "password=" + options.getPassword(); try { CommandLineOptions cmdOptions = new CommandLineOptions(argv); Runner runner = new Runner(cmdOptions); if (cmdOptions.shouldHelp()) { cmdOptions.showHelp(); return; } if (cmdOptions.shouldList()) { runner.list(); return; } if (cmdOptions.shouldListWithParams()) { runner.listWithParams(cmdOptions); return; } if (cmdOptions.shouldListProfilers()) { cmdOptions.listProfilers(); return; } if (cmdOptions.shouldListResultFormats()) { cmdOptions.listResultFormats(); return; } /* Options opt = new OptionsBuilder() .include(SimpleBenchmark.class.getSimpleName()) .warmupIterations(5) .measurementIterations(5) .forks(1) .build(); new Runner(opt).run(); */ try { runner.run(); } catch (NoBenchmarksException e) { System.err.println("No matching benchmarks. Miss-spelled regexp?"); if (cmdOptions.verbosity().orElse(Defaults.VERBOSITY) != VerboseMode.EXTRA) { System.err.println("Use " + VerboseMode.EXTRA + " verbose mode to debug the pattern matching."); } else { runner.list(); } // System.exit(1); } catch (ProfilersFailedException e) { // This is not exactly an error, set non-zero exit code System.err.println(e.getMessage()); // System.exit(1); } catch (RunnerException e) { System.err.print("ERROR: "); e.printStackTrace(System.err); // System.exit(1); } } catch (CommandLineOptionException e) { System.err.println("Error parsing command line:"); System.err.println(" " + e.getMessage()); // System.exit(1); } finally { PgTestBase.stopPg(); } } } ================================================ FILE: src/benchmark/java/io/reactiverse/pgclient/PgBenchmarkBase.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.vertx.core.Vertx; import org.openjdk.jmh.annotations.*; import java.util.concurrent.CountDownLatch; @State(Scope.Thread) public abstract class PgBenchmarkBase extends BenchmarkBase { @Param("localhost") String host; @Param("8081") int port; @Param("postgres") String database; @Param("postgres") String username; @Param("postgres") String password; @Param("1") int pipeliningLimit; Vertx vertx; PgPool pool; @Setup public void setup() throws Exception { vertx = Vertx.vertx(); pool = PgClient.pool(vertx, new PgPoolOptions() .setHost(host) .setPort(port) .setDatabase(database) .setUser(username) .setPassword(password) .setCachePreparedStatements(true) .setPipeliningLimit(pipeliningLimit) .setMaxSize(1)); } @TearDown public void tearDown() throws Exception { CountDownLatch latch = new CountDownLatch(1); vertx.close(ar -> { latch.countDown(); }); latch.await(); } } ================================================ FILE: src/benchmark/java/io/reactiverse/pgclient/PipelineBenchmark.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.infra.Blackhole; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; public class PipelineBenchmark extends PgBenchmarkBase { public static final int ITER = 25; Tuple args; @Override public void setup() throws Exception { super.setup(); args = Tuple.of(1); } @Benchmark public void test1(Blackhole blackhole) throws Exception { CompletableFuture latch = new CompletableFuture<>(); AtomicInteger count = new AtomicInteger(); for (int i = 0;i < ITER;i++) { pool.query("SELECT id, randomnumber from WORLD where id=1", ar -> { if (ar.succeeded()) { if (count.incrementAndGet() == ITER) { latch.complete(ar.result()); } } else { latch.completeExceptionally(ar.cause()); } }); } blackhole.consume(latch.get()); } @Benchmark public void test2(Blackhole blackhole) throws Exception { CompletableFuture latch = new CompletableFuture<>(); doSingle(0, latch); blackhole.consume(latch.get()); } private void doSingle(int count, CompletableFuture latch) { pool.query("SELECT id, randomnumber from WORLD where id=1", ar -> { if (ar.succeeded()) { if (count + 1 == ITER) { latch.complete(ar.result()); } else { doSingle(count + 1, latch); } } else { latch.completeExceptionally(ar.cause()); } }); } } ================================================ FILE: src/benchmark/java/io/reactiverse/pgclient/RawBenchmark.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.vertx.core.Vertx; import org.postgresql.PGProperty; import java.sql.*; import java.util.Properties; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; public class RawBenchmark { private static final Tuple args = Tuple.of(1); public static void main(String[] args) throws Exception { PgConnectOptions options = PgTestBase.startPg(); /* PgConnectOptions options = new PgConnectOptions() .setHost("localhost") .setPort(5432) .setDatabase("postgres") .setUser("postgres") .setPassword("postgres"); */ largeSelectJDBC(options, 5_000); largeSelect(options, 5_000); singleSelectJDBC(options, 200_000); singleSelect(options, 200_000); } interface Benchmark { void run(Connection conn) throws Exception; } private static void singleSelectJDBC(PgConnectOptions options, int reps) throws Exception { benchmark("Single select jdbc", options, conn -> { PreparedStatement ps = conn.prepareStatement("select id, randomnumber from WORLD where id=(?)"); for (int i = 0;i < reps;i++) { ps.setInt(1, 1); ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { resultSet.getInt(1); } resultSet.close(); } }); } private static void largeSelectJDBC(PgConnectOptions options, int reps) throws Exception { benchmark("Large select jdbc", options, conn -> { PreparedStatement ps = conn.prepareStatement("SELECT id, randomnumber from WORLD"); for (int i = 0;i < reps;i++) { ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { resultSet.getInt(1); } resultSet.close(); } }); } private static void benchmark(String name, PgConnectOptions options, Benchmark benchmark) throws Exception { Properties props = new Properties(); PGProperty.PREPARE_THRESHOLD.set(props, -1); PGProperty.BINARY_TRANSFER.set(props, "true"); // PGProperty.BINARY_TRANSFER_ENABLE.set(props, "true"); PGProperty.USER.set(props, "postgres"); PGProperty.PASSWORD.set(props, "postgres"); Connection conn = DriverManager.getConnection("jdbc:postgresql://" + options.getHost() + ":" + options.getPort() + "/postgres", props); long now = System.currentTimeMillis(); benchmark.run(conn); System.out.println(name + ": " + (System.currentTimeMillis() - now)); } private static void singleSelect(PgConnectOptions options, int reps) throws Exception { benchmark("Single select", options, (conn, latch) -> doSingleQuery(conn, reps, latch)); } private static void largeSelect(PgConnectOptions options, int reps) throws Exception { benchmark("Large select", options, (conn, latch) -> doLargeQuery(conn, reps, latch)); } private static void doSingleQuery(PgConnection conn, int remaining, CompletableFuture latch) { if (remaining > 0) { conn.preparedQuery("SELECT id, randomnumber from WORLD where id=$1", args, ar -> { if (ar.succeeded()) { doSingleQuery(conn, remaining -1, latch); } else { latch.completeExceptionally(ar.cause()); } }); } else { latch.complete(null); } } private static void doLargeQuery(PgConnection conn, int remaining, CompletableFuture latch) { if (remaining > 0) { conn.preparedQuery("SELECT id, randomnumber from WORLD", ar -> { if (ar.succeeded()) { doLargeQuery(conn, remaining -1, latch); PgRowSet result = ar.result(); for (Tuple tuple : result) { int val = tuple.getInteger(0); } } else { latch.completeExceptionally(ar.cause()); } }); } else { latch.complete(null); } } private static void benchmark(String name, PgConnectOptions options, BiConsumer> benchmark) throws Exception { Vertx vertx = Vertx.vertx(); PgPool client = PgClient.pool(vertx, new PgPoolOptions() .setHost(options.getHost()) .setPort(options.getPort()) .setDatabase(options.getDatabase()) .setUser(options.getUser()) .setPassword(options.getPassword()) .setCachePreparedStatements(true) ); CompletableFuture latch = new CompletableFuture<>(); long now = System.currentTimeMillis(); client.getConnection(ar -> { if (ar.succeeded()) { benchmark.accept(ar.result(), latch); } else { latch.completeExceptionally(ar.cause()); } }); latch.get(2, TimeUnit.MINUTES); System.out.println(name + ": " + (System.currentTimeMillis() - now)); } } ================================================ FILE: src/benchmark/java/io/reactiverse/pgclient/SingleSelectBenchmark.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Threads; import org.openjdk.jmh.infra.Blackhole; import java.util.concurrent.CompletableFuture; @Threads(8) public class SingleSelectBenchmark extends PgBenchmarkBase { Tuple args; @Override public void setup() throws Exception { super.setup(); args = Tuple.of(1); } @Benchmark public void poolPreparedQuery(Blackhole blackhole) throws Exception { CompletableFuture latch = new CompletableFuture<>(); pool.preparedQuery("SELECT id, randomnumber from WORLD where id=$1", args, ar -> { if (ar.succeeded()) { latch.complete(ar.result()); } else { latch.completeExceptionally(ar.cause()); } }); blackhole.consume(latch.get()); } @Benchmark public void pooledConnectionPreparedQuery(Blackhole blackhole) throws Exception { CompletableFuture latch = new CompletableFuture<>(); pool.getConnection(ar1 -> { if (ar1.succeeded()) { PgConnection conn = ar1.result(); conn.preparedQuery("SELECT id, randomnumber from WORLD where id=$1", args, ar2 -> { conn.close(); if (ar2.succeeded()) { latch.complete(ar2.result()); } else { latch.completeExceptionally(ar2.cause()); } }); } else { latch.completeExceptionally(ar1.cause()); } }); blackhole.consume(latch.get()); } @Benchmark public void pooledConnectionPreparedStatementQuery(Blackhole blackhole) throws Exception { CompletableFuture latch = new CompletableFuture<>(); pool.getConnection(ar1 -> { if (ar1.succeeded()) { PgConnection conn = ar1.result(); conn.prepare("SELECT id, randomnumber from WORLD where id=$1", ar2 -> { if (ar2.succeeded()) { PgPreparedQuery ps = ar2.result(); ps.execute(args, ar3 -> { conn.close(); if (ar3.succeeded()) { latch.complete(ar3.result()); } else { latch.completeExceptionally(ar3.cause()); } }); } else { latch.completeExceptionally(ar2.cause()); } }); } else { latch.completeExceptionally(ar1.cause()); } }); blackhole.consume(latch.get()); } } ================================================ FILE: src/benchmark/java/io/reactiverse/pgclient/UpdateBenchmark.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Threads; import org.openjdk.jmh.infra.Blackhole; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.CompletableFuture; @Threads(8) public class UpdateBenchmark extends PgBenchmarkBase { List batch; @Override public void setup() throws Exception { super.setup(); int len = 10; batch = new ArrayList<>(); Random random = new Random(); for (int id = 0;id < len;id++) { batch.add(Tuple.of(1 + random.nextInt(10000), id)); } } @Benchmark public void poolPreparedBatchUpdate(Blackhole blackhole) throws Exception { CompletableFuture> latch = new CompletableFuture<>(); pool.preparedBatch("UPDATE world SET randomnumber=$1 WHERE id=$2", batch, ar -> { if (ar.succeeded()) { latch.complete(ar.result()); } else { latch.completeExceptionally(ar.cause()); } }); blackhole.consume(latch.get()); } } ================================================ FILE: src/main/asciidoc/dataobjects.adoc ================================================ = Cheatsheets [[Box]] == Box ++++ Rectangular box data type in Postgres represented by pairs of links that are opposite corners of the box. ++++ ''' [cols=">25%,25%,50%"] [frame="topbot"] |=== ^|Name | Type ^| Description |[[lowerLeftCorner]]`@lowerLeftCorner`|`link:dataobjects.html#Point[Point]`|- |[[upperRightCorner]]`@upperRightCorner`|`link:dataobjects.html#Point[Point]`|- |=== [[Circle]] == Circle ++++ Circle data type in Postgres represented by a center link and radius. ++++ ''' [cols=">25%,25%,50%"] [frame="topbot"] |=== ^|Name | Type ^| Description |[[centerPoint]]`@centerPoint`|`link:dataobjects.html#Point[Point]`|- |[[radius]]`@radius`|`Number (double)`|- |=== [[Interval]] == Interval ++++ Postgres Interval is date and time based such as 120 years 3 months 332 days 20 hours 20 minutes 20.999999 seconds ++++ ''' [cols=">25%,25%,50%"] [frame="topbot"] |=== ^|Name | Type ^| Description |[[days]]`@days`|`Number (int)`|- |[[hours]]`@hours`|`Number (int)`|- |[[microseconds]]`@microseconds`|`Number (int)`|- |[[minutes]]`@minutes`|`Number (int)`|- |[[months]]`@months`|`Number (int)`|- |[[seconds]]`@seconds`|`Number (int)`|- |[[years]]`@years`|`Number (int)`|- |=== [[Line]] == Line ++++ Line data type in Postgres represented by the linear equation Ax + By + C = 0, where A and B are not both zero. ++++ ''' [cols=">25%,25%,50%"] [frame="topbot"] |=== ^|Name | Type ^| Description |[[a]]`@a`|`Number (double)`|- |[[b]]`@b`|`Number (double)`|- |[[c]]`@c`|`Number (double)`|- |=== [[LineSegment]] == LineSegment ++++ Finite line segment data type in Postgres represented by pairs of links that are the endpoints of the segment. ++++ ''' [cols=">25%,25%,50%"] [frame="topbot"] |=== ^|Name | Type ^| Description |[[p1]]`@p1`|`link:dataobjects.html#Point[Point]`|- |[[p2]]`@p2`|`link:dataobjects.html#Point[Point]`|- |=== [[Path]] == Path ++++ Path data type in Postgres represented by lists of connected points. Paths can be open, where the first and last points in the list are considered not connected, or closed, where the first and last points are considered connected. ++++ ''' [cols=">25%,25%,50%"] [frame="topbot"] |=== ^|Name | Type ^| Description |[[open]]`@open`|`Boolean`|- |[[points]]`@points`|`Array of link:dataobjects.html#Point[Point]`|- |=== [[PgConnectOptions]] == PgConnectOptions ++++ ++++ ''' [cols=">25%,25%,50%"] [frame="topbot"] |=== ^|Name | Type ^| Description |[[cachePreparedStatements]]`@cachePreparedStatements`|`Boolean`|- |[[connectTimeout]]`@connectTimeout`|`Number (int)`|- |[[crlPaths]]`@crlPaths`|`Array of String`|- |[[crlValues]]`@crlValues`|`Array of Buffer`|- |[[database]]`@database`|`String`|- |[[enabledCipherSuites]]`@enabledCipherSuites`|`Array of String`|- |[[enabledSecureTransportProtocols]]`@enabledSecureTransportProtocols`|`Array of String`|- |[[host]]`@host`|`String`|- |[[hostnameVerificationAlgorithm]]`@hostnameVerificationAlgorithm`|`String`|- |[[idleTimeout]]`@idleTimeout`|`Number (int)`|- |[[idleTimeoutUnit]]`@idleTimeoutUnit`|`link:enums.html#TimeUnit[TimeUnit]`|- |[[jdkSslEngineOptions]]`@jdkSslEngineOptions`|`link:dataobjects.html#JdkSSLEngineOptions[JdkSSLEngineOptions]`|- |[[keyStoreOptions]]`@keyStoreOptions`|`link:dataobjects.html#JksOptions[JksOptions]`|- |[[localAddress]]`@localAddress`|`String`|- |[[logActivity]]`@logActivity`|`Boolean`|- |[[metricsName]]`@metricsName`|`String`|- |[[openSslEngineOptions]]`@openSslEngineOptions`|`link:dataobjects.html#OpenSSLEngineOptions[OpenSSLEngineOptions]`|- |[[password]]`@password`|`String`|- |[[pemKeyCertOptions]]`@pemKeyCertOptions`|`link:dataobjects.html#PemKeyCertOptions[PemKeyCertOptions]`|- |[[pemTrustOptions]]`@pemTrustOptions`|`link:dataobjects.html#PemTrustOptions[PemTrustOptions]`|- |[[pfxKeyCertOptions]]`@pfxKeyCertOptions`|`link:dataobjects.html#PfxOptions[PfxOptions]`|- |[[pfxTrustOptions]]`@pfxTrustOptions`|`link:dataobjects.html#PfxOptions[PfxOptions]`|- |[[pipeliningLimit]]`@pipeliningLimit`|`Number (int)`|- |[[port]]`@port`|`Number (int)`|- |[[proxyOptions]]`@proxyOptions`|`link:dataobjects.html#ProxyOptions[ProxyOptions]`|- |[[receiveBufferSize]]`@receiveBufferSize`|`Number (int)`|- |[[reconnectAttempts]]`@reconnectAttempts`|`Number (int)`|- |[[reconnectInterval]]`@reconnectInterval`|`Number (long)`|- |[[reuseAddress]]`@reuseAddress`|`Boolean`|- |[[reusePort]]`@reusePort`|`Boolean`|- |[[sendBufferSize]]`@sendBufferSize`|`Number (int)`|- |[[soLinger]]`@soLinger`|`Number (int)`|- |[[ssl]]`@ssl`|`Boolean`|- |[[sslHandshakeTimeout]]`@sslHandshakeTimeout`|`Number (long)`|- |[[sslHandshakeTimeoutUnit]]`@sslHandshakeTimeoutUnit`|`link:enums.html#TimeUnit[TimeUnit]`|- |[[sslMode]]`@sslMode`|`link:enums.html#SslMode[SslMode]`|+++ Set link for the client, this option can be used to provide different levels of secure protection. +++ |[[tcpCork]]`@tcpCork`|`Boolean`|- |[[tcpFastOpen]]`@tcpFastOpen`|`Boolean`|- |[[tcpKeepAlive]]`@tcpKeepAlive`|`Boolean`|- |[[tcpNoDelay]]`@tcpNoDelay`|`Boolean`|- |[[tcpQuickAck]]`@tcpQuickAck`|`Boolean`|- |[[trafficClass]]`@trafficClass`|`Number (int)`|- |[[trustAll]]`@trustAll`|`Boolean`|- |[[trustStoreOptions]]`@trustStoreOptions`|`link:dataobjects.html#JksOptions[JksOptions]`|- |[[useAlpn]]`@useAlpn`|`Boolean`|- |[[usePooledBuffers]]`@usePooledBuffers`|`Boolean`|- |[[user]]`@user`|`String`|- |[[usingDomainSocket]]`@usingDomainSocket`|`Boolean`|- |=== [[PgNotification]] == PgNotification ++++ A notification emited by Postgres. ++++ ''' [cols=">25%,25%,50%"] [frame="topbot"] |=== ^|Name | Type ^| Description |[[channel]]`@channel`|`String`|+++ Set the channel value. +++ |[[payload]]`@payload`|`String`|+++ Set the payload value. +++ |[[processId]]`@processId`|`Number (int)`|+++ Set the process id. +++ |=== [[PgPoolOptions]] == PgPoolOptions ++++ The options for configuring a connection pool. ++++ ''' [cols=">25%,25%,50%"] [frame="topbot"] |=== ^|Name | Type ^| Description |[[cachePreparedStatements]]`@cachePreparedStatements`|`Boolean`|- |[[connectTimeout]]`@connectTimeout`|`Number (int)`|- |[[crlPaths]]`@crlPaths`|`Array of String`|- |[[crlValues]]`@crlValues`|`Array of Buffer`|- |[[database]]`@database`|`String`|- |[[enabledCipherSuites]]`@enabledCipherSuites`|`Array of String`|- |[[enabledSecureTransportProtocols]]`@enabledSecureTransportProtocols`|`Array of String`|- |[[host]]`@host`|`String`|- |[[hostnameVerificationAlgorithm]]`@hostnameVerificationAlgorithm`|`String`|- |[[idleTimeout]]`@idleTimeout`|`Number (int)`|- |[[idleTimeoutUnit]]`@idleTimeoutUnit`|`link:enums.html#TimeUnit[TimeUnit]`|- |[[jdkSslEngineOptions]]`@jdkSslEngineOptions`|`link:dataobjects.html#JdkSSLEngineOptions[JdkSSLEngineOptions]`|- |[[keyStoreOptions]]`@keyStoreOptions`|`link:dataobjects.html#JksOptions[JksOptions]`|- |[[localAddress]]`@localAddress`|`String`|- |[[logActivity]]`@logActivity`|`Boolean`|- |[[maxSize]]`@maxSize`|`Number (int)`|+++ Set the maximum pool size +++ |[[maxWaitQueueSize]]`@maxWaitQueueSize`|`Number (int)`|+++ Set the maximum connection request allowed in the wait queue, any requests beyond the max size will result in an failure. If the value is set to a negative number then the queue will be unbounded. +++ |[[metricsName]]`@metricsName`|`String`|- |[[openSslEngineOptions]]`@openSslEngineOptions`|`link:dataobjects.html#OpenSSLEngineOptions[OpenSSLEngineOptions]`|- |[[password]]`@password`|`String`|- |[[pemKeyCertOptions]]`@pemKeyCertOptions`|`link:dataobjects.html#PemKeyCertOptions[PemKeyCertOptions]`|- |[[pemTrustOptions]]`@pemTrustOptions`|`link:dataobjects.html#PemTrustOptions[PemTrustOptions]`|- |[[pfxKeyCertOptions]]`@pfxKeyCertOptions`|`link:dataobjects.html#PfxOptions[PfxOptions]`|- |[[pfxTrustOptions]]`@pfxTrustOptions`|`link:dataobjects.html#PfxOptions[PfxOptions]`|- |[[pipeliningLimit]]`@pipeliningLimit`|`Number (int)`|- |[[port]]`@port`|`Number (int)`|- |[[proxyOptions]]`@proxyOptions`|`link:dataobjects.html#ProxyOptions[ProxyOptions]`|- |[[receiveBufferSize]]`@receiveBufferSize`|`Number (int)`|- |[[reconnectAttempts]]`@reconnectAttempts`|`Number (int)`|- |[[reconnectInterval]]`@reconnectInterval`|`Number (long)`|- |[[reuseAddress]]`@reuseAddress`|`Boolean`|- |[[reusePort]]`@reusePort`|`Boolean`|- |[[sendBufferSize]]`@sendBufferSize`|`Number (int)`|- |[[soLinger]]`@soLinger`|`Number (int)`|- |[[ssl]]`@ssl`|`Boolean`|- |[[sslHandshakeTimeout]]`@sslHandshakeTimeout`|`Number (long)`|- |[[sslHandshakeTimeoutUnit]]`@sslHandshakeTimeoutUnit`|`link:enums.html#TimeUnit[TimeUnit]`|- |[[sslMode]]`@sslMode`|`link:enums.html#SslMode[SslMode]`|+++ Set link for the client, this option can be used to provide different levels of secure protection. +++ |[[tcpCork]]`@tcpCork`|`Boolean`|- |[[tcpFastOpen]]`@tcpFastOpen`|`Boolean`|- |[[tcpKeepAlive]]`@tcpKeepAlive`|`Boolean`|- |[[tcpNoDelay]]`@tcpNoDelay`|`Boolean`|- |[[tcpQuickAck]]`@tcpQuickAck`|`Boolean`|- |[[trafficClass]]`@trafficClass`|`Number (int)`|- |[[trustAll]]`@trustAll`|`Boolean`|- |[[trustStoreOptions]]`@trustStoreOptions`|`link:dataobjects.html#JksOptions[JksOptions]`|- |[[useAlpn]]`@useAlpn`|`Boolean`|- |[[usePooledBuffers]]`@usePooledBuffers`|`Boolean`|- |[[user]]`@user`|`String`|- |[[usingDomainSocket]]`@usingDomainSocket`|`Boolean`|- |=== [[Point]] == Point ++++ A Postgresql point. ++++ ''' [cols=">25%,25%,50%"] [frame="topbot"] |=== ^|Name | Type ^| Description |[[x]]`@x`|`Number (double)`|- |[[y]]`@y`|`Number (double)`|- |=== [[Polygon]] == Polygon ++++ Polygon data type in Postgres represented by lists of points (the vertexes of the polygon). Polygons are very similar to closed paths, but are stored differently and have their own set of support routines. ++++ ''' [cols=">25%,25%,50%"] [frame="topbot"] |=== ^|Name | Type ^| Description |[[points]]`@points`|`Array of link:dataobjects.html#Point[Point]`|- |=== ================================================ FILE: src/main/docs/index.md ================================================ # Reactive Postgres Client The Reactive Postgres Client is a client for Postgres with a straightforward API focusing on scalability and low overhead. The client is reactive and non blocking, allowing to handle many database connections with a single thread. * Event driven * Lightweight * Built-in connection pooling * Prepared queries caching * Publish / subscribe using Postgres `NOTIFY/LISTEN` * Batch and cursor * Row streaming * Command pipeling * RxJava 1 and RxJava 2 * Direct memory to object without unnecessary copies * Java 8 Date and Time * SSL/TLS * Unix domain socket * HTTP/1.x CONNECT, SOCKS4a or SOCKS5 proxy support ## Usage To use the Reactive Postgres Client add the following dependency to the _dependencies_ section of your build descriptor: * Maven (in your `pom.xml`): ```xml ${maven.groupId} ${maven.artifactId} ${maven.version} ``` * Gradle (in your `build.gradle` file): ```groovy dependencies { compile '${maven.groupId}:${maven.artifactId}:${maven.version}' } ``` ## Getting started Here is the simplest way to connect, query and disconnect ```$lang {@link examples.Examples#gettingStarted()} ``` ## Connecting to Postgres Most of the time you will use a pool to connect to Postgres: ```$lang {@link examples.Examples#connecting01} ``` The pooled client uses a connection pool and any operation will borrow a connection from the pool to execute the operation and release it to the pool. If you are running with Vert.x you can pass it your Vertx instance: ```$lang {@link examples.Examples#connecting02} ``` You need to release the pool when you don't need it anymore: ```$lang {@link examples.Examples#connecting03} ``` When you need to execute several operations on the same connection, you need to use a client {@link io.reactiverse.pgclient.PgConnection connection}. You can easily get one from the pool: ```$lang {@link examples.Examples#connecting04} ``` Once you are done with the connection you must close it to release it to the pool, so it can be reused. Sometimes you want to improve performance via Unix domain socket connection, we achieve this with Vert.x Native transports. Make sure you have added the required `netty-transport-native` dependency in your classpath and enabled the Unix domain socket option. ```$lang {@link examples.Examples#connecting06} ``` More information can be found in the [Vert.x documentation](https://vertx.io/docs/vertx-core/java/#_native_transports). ## Configuration There are several options for you to configure the client. Apart from configuring with a `PgPoolOptions` data object, We also provide you an alternative way to connect when you want to configure with a connection URI: ```$lang {@link examples.Examples#configureFromUri(io.vertx.core.Vertx)} ``` More information about connection string formats can be found in the [PostgreSQL Manuals](https://www.postgresql.org/docs/9.6/static/libpq-connect.html#LIBPQ-CONNSTRING). You can also use environment variables to set default connection setting values, this is useful when you want to avoid hard-coding database connection information. You can refer to the [official documentation](https://www.postgresql.org/docs/9.6/static/libpq-envars.html) for more details. The following parameters are supported: * `PGHOST` * `PGHOSTADDR` * `PGPORT` * `PGDATABASE` * `PGUSER` * `PGPASSWORD` * `PGSSLMODE` If you don't specify a data object or a connection URI string to connect, environment variables will take precedence over them. ``` $ PGUSER=user \ PGHOST=the-host \ PGPASSWORD=secret \ PGDATABASE=the-db \ PGPORT=5432 \ PGSSLMODE=DISABLE ``` ```$lang {@link examples.Examples#configureFromEnv(io.vertx.core.Vertx)} ``` ## Running queries When you don't need a transaction or run single queries, you can run queries directly on the pool; the pool will use one of its connection to run the query and return the result to you. Here is how to run simple queries: ```$lang {@link examples.Examples#queries01(io.reactiverse.pgclient.PgClient)} ``` You can do the same with prepared queries. The SQL string can refer to parameters by position, using `$1`, `$2`, etc…​ ```$lang {@link examples.Examples#queries02(io.reactiverse.pgclient.PgClient)} ``` Query methods provides an asynchronous {@link io.reactiverse.pgclient.PgRowSet} instance that works for _SELECT_ queries ```$lang {@link examples.Examples#queries03(io.reactiverse.pgclient.PgClient)} ``` or _UPDATE_/_INSERT_ queries: ```$lang {@link examples.Examples#queries04(io.reactiverse.pgclient.PgClient)} ``` The {@link io.reactiverse.pgclient.Row} gives you access to your data by index ```$lang {@link examples.Examples#queries05(Row)} ``` or by name ```$lang {@link examples.Examples#queries06(Row)} ``` You can access a wide variety of of types ```$lang {@link examples.Examples#queries07(Row)} ``` You can execute prepared batch ```$lang {@link examples.Examples#queries08(io.reactiverse.pgclient.PgClient)} ``` You can cache prepared queries: ```$lang {@link examples.Examples#queries09(io.vertx.core.Vertx, PgPoolOptions)} ``` You can fetch generated keys with a 'RETURNING' clause in your query: ```$lang {@link examples.Examples#queries10(io.reactiverse.pgclient.PgClient)} ``` ## Using connections When you need to execute sequential queries (without a transaction), you can create a new connection or borrow one from the pool: ```$lang {@link examples.Examples#usingConnections01(io.vertx.core.Vertx, io.reactiverse.pgclient.PgPool)} ``` Prepared queries can be created: ```$lang {@link examples.Examples#usingConnections02(io.reactiverse.pgclient.PgConnection)} ``` NOTE: prepared query caching depends on the {@link io.reactiverse.pgclient.PgConnectOptions#setCachePreparedStatements(boolean)} and does not depend on whether you are creating prepared queries or use {@link io.reactiverse.pgclient.PgClient#preparedQuery(java.lang.String, io.vertx.core.Handler) direct prepared queries} {@link io.reactiverse.pgclient.PgPreparedQuery} can perform efficient batching: ```$lang {@link examples.Examples#usingConnections03(io.reactiverse.pgclient.PgConnection)} ``` ## Using transactions ### Transactions with connections You can execute transaction using SQL `BEGIN`/`COMMIT`/`ROLLBACK`, if you do so you must use a {@link io.reactiverse.pgclient.PgConnection} and manage it yourself. Or you can use the transaction API of {@link io.reactiverse.pgclient.PgConnection}: ```$lang {@link examples.Examples#transaction01(io.reactiverse.pgclient.PgPool)} ``` When Postgres reports the current transaction is failed (e.g the infamous _current transaction is aborted, commands ignored until end of transaction block_), the transaction is rollbacked and the {@link io.reactiverse.pgclient.PgTransaction#abortHandler(io.vertx.core.Handler)} is called: ```$lang {@link examples.Examples#transaction02(io.reactiverse.pgclient.PgPool)} ``` ### Simplified transaction API When you use a pool, you can start a transaction directly on the pool. It borrows a connection from the pool, begins the transaction and releases the connection to the pool when the transaction ends. ```$lang {@link examples.Examples#transaction03(io.reactiverse.pgclient.PgPool)} ``` ## Cursors and streaming By default prepared query execution fetches all rows, you can use a {@link io.reactiverse.pgclient.PgCursor} to control the amount of rows you want to read: ```$lang {@link examples.Examples#usingCursors01(io.reactiverse.pgclient.PgConnection)} ``` PostreSQL destroys cursors at the end of a transaction, so the cursor API shall be used within a transaction, otherwise you will likely get the `34000` PostgreSQL error. Cursors shall be closed when they are released prematurely: ```$lang {@link examples.Examples#usingCursors02(io.reactiverse.pgclient.PgCursor)} ``` A stream API is also available for cursors, which can be more convenient, specially with the Rxified version. ```$lang {@link examples.Examples#usingCursors03(io.reactiverse.pgclient.PgConnection)} ``` The stream read the rows by batch of `50` and stream them, when the rows have been passed to the handler, a new batch of `50` is read and so on. The stream can be resumed or paused, the loaded rows will remain in memory until they are delivered and the cursor will stop iterating. ## Postgres type mapping Currently the client supports the following Postgres types * BOOLEAN (`java.lang.Boolean`) * INT2 (`java.lang.Short`) * INT4 (`java.lang.Integer`) * INT8 (`java.lang.Long`) * FLOAT4 (`java.lang.Float`) * FLOAT8 (`java.lang.Double`) * CHAR (`java.lang.String`) * VARCHAR (`java.lang.String`) * TEXT (`java.lang.String`) * ENUM (`java.lang.String`) * NAME (`java.lang.String`) * SERIAL2 (`java.lang.Short`) * SERIAL4 (`java.lang.Integer`) * SERIAL8 (`java.lang.Long`) * NUMERIC (`io.reactiverse.pgclient.data.Numeric`) * UUID (`java.util.UUID`) * DATE (`java.time.LocalDate`) * TIME (`java.time.LocalTime`) * TIMETZ (`java.time.OffsetTime`) * TIMESTAMP (`java.time.LocalDateTime`) * TIMESTAMPTZ (`java.time.OffsetDateTime`) * INTERVAL (`io.reactiverse.pgclient.data.Interval`) * BYTEA (`io.vertx.core.buffer.Buffer`) * JSON (`io.reactiverse.pgclient.data.Json`) * JSONB (`io.reactiverse.pgclient.data.Json`) * POINT (`io.reactiverse.pgclient.data.Point`) * LINE (`io.reactiverse.pgclient.data.Line`) * LSEG (`io.reactiverse.pgclient.data.LineSegment`) * BOX (`io.reactiverse.pgclient.data.Box`) * PATH (`io.reactiverse.pgclient.data.Path`) * POLYGON (`io.reactiverse.pgclient.data.Polygon`) * CIRCLE (`io.reactiverse.pgclient.data.Circle`) Tuple decoding uses the above types when storing values, it also performs on the flu conversion the actual value when possible: ```$lang {@link examples.Examples#typeMapping01} ``` Tuple encoding uses the above type mapping for encoding, unless the type is numeric in which case `java.lang.Number` is used instead: ```$lang {@link examples.Examples#typeMapping02} ``` Arrays of these types are supported. ### Handling JSON The {@link io.reactiverse.pgclient.data.Json} Java type is used to represent the Postgres `JSON` and `JSONB` type. The main reason of this type is handling `null` JSON values. ```$lang {@link examples.Examples#jsonExample()} ``` ### Handling NUMERIC The {@link io.reactiverse.pgclient.data.Numeric} Java type is used to represent the Postgres `NUMERIC` type. ```$lang {@link examples.Examples#numericExample} ``` ## Handling arrays Arrays are available on {@link io.reactiverse.pgclient.Tuple} and {@link io.reactiverse.pgclient.Row}: ```$lang {@link examples.Examples#arrayExample} ``` ## Handling custom types Strings are used to represent custom types, both sent to and returned from Postgres. You can read from Postgres and get the custom type as a string ```$lang {@link examples.Examples#customType01Example} ``` You can also write to Postgres by providing a string ```$lang {@link examples.Examples#customType02Example} ``` ## Collector queries You can use Java collectors with the query API: ```$lang {@link examples.Examples#collector01Example} ``` The collector processing must not keep a reference on the {@link io.reactiverse.pgclient.Row} as there is a single row used for processing the entire set. The Java `Collectors` provides many interesting predefined collectors, for example you can create easily create a string directly from the row set: ```$lang {@link examples.Examples#collector02Example} ``` ## RxJava support The rxified API supports RxJava 1 and RxJava 2, the following examples use RxJava 2. Most asynchronous constructs are available as methods prefixed by `rx`: ```$lang {@link examples.RxExamples#simpleQuery01Example} ``` ### Streaming RxJava 2 supports `Observable` and `Flowable` types, these are exposed using the {@link io.reactiverse.reactivex.pgclient.PgStream} that you can get from a {@link io.reactiverse.reactivex.pgclient.PgPreparedQuery}: ```$lang {@link examples.RxExamples#streamingQuery01Example} ``` The same example using `Flowable`: ```$lang {@link examples.RxExamples#streamingQuery02Example} ``` ### Transaction The simplified transaction API allows to easily write transactional asynchronous flows: ```$lang {@link examples.RxExamples#transaction01Example} ``` ## Pub/sub Postgres supports pub/sub communication channels. You can set a {@link io.reactiverse.pgclient.PgConnection#notificationHandler(io.vertx.core.Handler)} to receive Postgres notifications: ```$lang {@link examples.Examples#pubsub01(io.reactiverse.pgclient.PgConnection)} ``` The {@link io.reactiverse.pgclient.pubsub.PgSubscriber} is a channel manager managing a single connection that provides per channel subscription: ```$lang {@link examples.Examples#pubsub02(io.vertx.core.Vertx)} ``` The channel name that is given to the channel method will be the exact name of the channel as held by Postgres for sending notifications. Note this is different than the representation of the channel name in SQL, and internally {@link io.reactiverse.pgclient.pubsub.PgSubscriber} will prepare the submitted channel name as a quoted identifier: ```$lang {@link examples.Examples#pubsub03(io.vertx.core.Vertx)} ``` You can provide a reconnect policy as a function that takes the number of `retries` as argument and returns an `amountOfTime` value: * when `amountOfTime < 0`: the subscriber is closed and there is no retry * when `amountOfTime = 0`: the subscriber retries to connect immediately * when `amountOfTime > 0`: the subscriber retries after `amountOfTime` milliseconds ```$lang {@link examples.Examples#pubsub04(io.vertx.core.Vertx)} ``` The default policy is to not reconnect. ## Cancelling Request Postgres supports cancellation of requests in progress. You can cancel inflight requests using {@link io.reactiverse.pgclient.PgConnection#cancelRequest}. Cancelling a request opens a new connection to the server and cancels the request and then close the connection. ```$lang {@link examples.Examples#cancelRequest(io.reactiverse.pgclient.PgConnection)} ``` > The cancellation signal might or might not have any effect — for example, if it arrives after the backend has finished processing the query, then it will have no effect. If the cancellation is effective, it results in the current command being terminated early with an error message. More information can be found in the [official documentation](https://www.postgresql.org/docs/11/protocol-flow.html#id-1.10.5.7.9). ## Using SSL/TLS To configure the client to use SSL connection, you can configure the {@link io.reactiverse.pgclient.PgConnectOptions} like a Vert.x `NetClient`. All [SSL modes](https://www.postgresql.org/docs/current/libpq-ssl.html#LIBPQ-SSL-PROTECTION) are supported and you are able to configure `sslmode`. The client is in `DISABLE` SSL mode by default. `ssl` parameter is kept as a mere shortcut for setting `sslmode`. `setSsl(true)` is equivalent to `setSslMode(VERIFY_CA)` and `setSsl(false)` is equivalent to `setSslMode(DISABLE)`. ```$lang {@link examples.Examples#ex10} ``` More information can be found in the [Vert.x documentation](http://vertx.io/docs/vertx-core/java/#ssl). ## Using a proxy You can also configure the client to use an HTTP/1.x CONNECT, SOCKS4a or SOCKS5 proxy. More information can be found in the [Vert.x documentation](http://vertx.io/docs/vertx-core/java/#_using_a_proxy_for_client_connections). ================================================ FILE: src/main/java/examples/Examples.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 examples; import io.reactiverse.pgclient.*; import io.reactiverse.pgclient.data.Json; import io.reactiverse.pgclient.data.Numeric; import io.reactiverse.pgclient.pubsub.PgSubscriber; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; import io.vertx.core.net.PemTrustOptions; import io.vertx.docgen.Source; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collector; import java.util.stream.Collectors; /** * @author Julien Viet */ @Source public class Examples { public void gettingStarted() { // Pool options PgPoolOptions options = new PgPoolOptions() .setPort(5432) .setHost("the-host") .setDatabase("the-db") .setUser("user") .setPassword("secret") .setMaxSize(5); // Create the client pool PgPool client = PgClient.pool(options); // A simple query client.query("SELECT * FROM users WHERE id='julien'", ar -> { if (ar.succeeded()) { PgRowSet result = ar.result(); System.out.println("Got " + result.size() + " rows "); } else { System.out.println("Failure: " + ar.cause().getMessage()); } // Now close the pool client.close(); }); } public void configureFromEnv(Vertx vertx) { // Create the pool from the environment variables PgPool pool = PgClient.pool(); // Create the connection from the environment variables PgClient.connect(vertx, res -> { // Handling your connection }); } public void configureFromUri(Vertx vertx) { // Connection URI String connectionUri = "postgresql://dbuser:secretpassword@database.server.com:3211/mydb"; // Create the pool from the connection URI PgPool pool = PgClient.pool(connectionUri); // Create the connection from the connection URI PgClient.connect(vertx, connectionUri, res -> { // Handling your connection }); } public void connecting01() { // Pool options PgPoolOptions options = new PgPoolOptions() .setPort(5432) .setHost("the-host") .setDatabase("the-db") .setUser("user") .setPassword("secret") .setMaxSize(5); // Create the pooled client PgPool client = PgClient.pool(options); } public void connecting02(Vertx vertx) { // Pool options PgPoolOptions options = new PgPoolOptions() .setPort(5432) .setHost("the-host") .setDatabase("the-db") .setUser("user") .setPassword("secret") .setMaxSize(5); // Create the pooled client PgPool client = PgClient.pool(vertx, options); } public void connecting03(PgPool pool) { // Close the pool and all the associated resources pool.close(); } public void connecting04(Vertx vertx) { // Pool options PgPoolOptions options = new PgPoolOptions() .setPort(5432) .setHost("the-host") .setDatabase("the-db") .setUser("user") .setPassword("secret") .setMaxSize(5); // Create the pooled client PgPool client = PgClient.pool(vertx, options); // Get a connection from the pool client.getConnection(ar1 -> { if (ar1.succeeded()) { System.out.println("Connected"); // Obtain our connection PgConnection conn = ar1.result(); // All operations execute on the same connection conn.query("SELECT * FROM users WHERE id='julien'", ar2 -> { if (ar2.succeeded()) { conn.query("SELECT * FROM users WHERE id='emad'", ar3 -> { // Release the connection to the pool conn.close(); }); } else { // Release the connection to the pool conn.close(); } }); } else { System.out.println("Could not connect: " + ar1.cause().getMessage()); } }); } public void connecting05(Vertx vertx) { // Pool options PgConnectOptions options = new PgConnectOptions() .setPort(5432) .setHost("the-host") .setDatabase("the-db") .setUser("user") .setPassword("secret"); // Connect to Postgres PgClient.connect(vertx, options, res -> { if (res.succeeded()) { System.out.println("Connected"); // Obtain our connection PgConnection conn = res.result(); // All operations execute on the same connection conn.query("SELECT * FROM users WHERE id='julien'", ar2 -> { if (ar2.succeeded()) { conn.query("SELECT * FROM users WHERE id='emad'", ar3 -> { // Close the connection conn.close(); }); } else { // Close the connection conn.close(); } }); } else { System.out.println("Could not connect: " + res.cause().getMessage()); } }); } public void connecting06(Vertx vertx) { // Pool Options // Socket file name will be /var/run/postgresql/.s.PGSQL.5432 PgPoolOptions options = new PgPoolOptions() .setHost("/var/run/postgresql") .setPort(5432) .setDatabase("the-db"); // Create the pooled client PgPool client = PgClient.pool(options); // Create the pooled client with a vertx instance // Make sure the vertx instance has enabled native transports PgPool client2 = PgClient.pool(vertx, options); } public void queries01(PgClient client) { client.query("SELECT * FROM users WHERE id='julien'", ar -> { if (ar.succeeded()) { PgRowSet result = ar.result(); System.out.println("Got " + result.size() + " rows "); } else { System.out.println("Failure: " + ar.cause().getMessage()); } }); } public void queries02(PgClient client) { client.preparedQuery("SELECT * FROM users WHERE id=$1", Tuple.of("julien"), ar -> { if (ar.succeeded()) { PgRowSet rows = ar.result(); System.out.println("Got " + rows.size() + " rows "); } else { System.out.println("Failure: " + ar.cause().getMessage()); } }); } public void queries03(PgClient client) { client.preparedQuery("SELECT first_name, last_name FROM users", ar -> { if (ar.succeeded()) { PgRowSet rows = ar.result(); for (Row row : rows) { System.out.println("User " + row.getString(0) + " " + row.getString(1)); } } else { System.out.println("Failure: " + ar.cause().getMessage()); } }); } public void queries04(PgClient client) { client.preparedQuery("INSERT INTO users (first_name, last_name) VALUES ($1, $2)", Tuple.of("Julien", "Viet"), ar -> { if (ar.succeeded()) { PgRowSet rows = ar.result(); System.out.println(rows.rowCount()); } else { System.out.println("Failure: " + ar.cause().getMessage()); } }); } public void queries05(Row row) { System.out.println("User " + row.getString(0) + " " + row.getString(1)); } public void queries06(Row row) { System.out.println("User " + row.getString("first_name") + " " + row.getString("last_name")); } public void queries07(Row row) { String firstName = row.getString("first_name"); Boolean male = row.getBoolean("male"); Integer age = row.getInteger("age"); // ... } public void queries08(PgClient client) { // Add commands to the batch List batch = new ArrayList<>(); batch.add(Tuple.of("julien", "Julien Viet")); batch.add(Tuple.of("emad", "Emad Alblueshi")); // Execute the prepared batch client.preparedBatch("INSERT INTO USERS (id, name) VALUES ($1, $2)", batch, res -> { if (res.succeeded()) { // Process rows PgRowSet rows = res.result(); } else { System.out.println("Batch failed " + res.cause()); } }); } public void queries09(Vertx vertx, PgPoolOptions options) { // Enable prepare statements options.setCachePreparedStatements(true); PgPool client = PgClient.pool(vertx, options); } public void queries10(PgClient client) { client.preparedQuery("INSERT INTO color (color_name) VALUES ($1), ($2), ($3) RETURNING color_id", Tuple.of("white", "red", "blue"), ar -> { if (ar.succeeded()) { PgRowSet rows = ar.result(); System.out.println(rows.rowCount()); for (Row row : rows) { System.out.println("generated key: " + row.getInteger("color_id")); } } else { System.out.println("Failure: " + ar.cause().getMessage()); } }); } public void usingConnections01(Vertx vertx, PgPool pool) { pool.getConnection(ar1 -> { if (ar1.succeeded()) { PgConnection connection = ar1.result(); connection.query("SELECT * FROM users WHERE id='julien'", ar2 -> { if (ar1.succeeded()) { connection.query("SELECT * FROM users WHERE id='paulo'", ar3 -> { // Do something with rows and return the connection to the pool connection.close(); }); } else { // Return the connection to the pool connection.close(); } }); } }); } public void usingConnections02(PgConnection connection) { connection.prepare("SELECT * FROM users WHERE first_name LIKE $1", ar1 -> { if (ar1.succeeded()) { PgPreparedQuery pq = ar1.result(); pq.execute(Tuple.of("julien"), ar2 -> { if (ar2.succeeded()) { // All rows PgRowSet rows = ar2.result(); } }); } }); } public void usingConnections03(PgConnection connection) { connection.prepare("INSERT INTO USERS (id, name) VALUES ($1, $2)", ar1 -> { if (ar1.succeeded()) { PgPreparedQuery prepared = ar1.result(); // Create a query : bind parameters List batch = new ArrayList(); // Add commands to the createBatch batch.add(Tuple.of("julien", "Julien Viet")); batch.add(Tuple.of("emad", "Emad Alblueshi")); prepared.batch(batch, res -> { if (res.succeeded()) { // Process rows PgRowSet rows = res.result(); } else { System.out.println("Batch failed " + res.cause()); } }); } }); } public void transaction01(PgPool pool) { pool.getConnection(res -> { if (res.succeeded()) { // Transaction must use a connection PgConnection conn = res.result(); // Begin the transaction PgTransaction tx = conn.begin(); // Various statements conn.query("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')", ar -> {}); conn.query("INSERT INTO Users (first_name,last_name) VALUES ('Emad','Alblueshi')", ar -> {}); // Commit the transaction tx.commit(ar -> { if (ar.succeeded()) { System.out.println("Transaction succeeded"); } else { System.out.println("Transaction failed " + ar.cause().getMessage()); } // Return the connection to the pool conn.close(); }); } }); } public void transaction02(PgPool pool) { pool.getConnection(res -> { if (res.succeeded()) { // Transaction must use a connection PgConnection conn = res.result(); // Begin the transaction PgTransaction tx = conn .begin() .abortHandler(v -> { System.out.println("Transaction failed => rollbacked"); }); conn.query("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')", ar -> { // Works fine of course if (ar.succeeded()) { } else { tx.rollback(); conn.close(); } }); conn.query("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')", ar -> { // Fails and triggers transaction aborts }); // Attempt to commit the transaction tx.commit(ar -> { // But transaction abortion fails it // Return the connection to the pool conn.close(); }); } }); } public void transaction03(PgPool pool) { // Acquire a transaction and begin the transaction pool.begin(res -> { if (res.succeeded()) { // Get the transaction PgTransaction tx = res.result(); // Various statements tx.query("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')", ar -> {}); tx.query("INSERT INTO Users (first_name,last_name) VALUES ('Emad','Alblueshi')", ar -> {}); // Commit the transaction and return the connection to the pool tx.commit(ar -> { if (ar.succeeded()) { System.out.println("Transaction succeeded"); } else { System.out.println("Transaction failed " + ar.cause().getMessage()); } }); } }); } public void usingCursors01(PgConnection connection) { connection.prepare("SELECT * FROM users WHERE first_name LIKE $1", ar1 -> { if (ar1.succeeded()) { PgPreparedQuery pq = ar1.result(); // Cursors require to run within a transaction PgTransaction tx = connection.begin(); // Create a cursor PgCursor cursor = pq.cursor(Tuple.of("julien")); // Read 50 rows cursor.read(50, ar2 -> { if (ar2.succeeded()) { PgRowSet rows = ar2.result(); // Check for more ? if (cursor.hasMore()) { // Repeat the process... } else { // No more rows - commit the transaction tx.commit(); } } }); } }); } public void usingCursors02(PgCursor cursor) { cursor.read(50, ar2 -> { if (ar2.succeeded()) { // Close the cursor cursor.close(); } }); } public void usingCursors03(PgConnection connection) { connection.prepare("SELECT * FROM users WHERE first_name LIKE $1", ar1 -> { if (ar1.succeeded()) { PgPreparedQuery pq = ar1.result(); // Streams require to run within a transaction PgTransaction tx = connection.begin(); // Fetch 50 rows at a time PgStream stream = pq.createStream(50, Tuple.of("julien")); // Use the stream stream.exceptionHandler(err -> { System.out.println("Error: " + err.getMessage()); }); stream.endHandler(v -> { tx.commit(); System.out.println("End of stream"); }); stream.handler(row -> { System.out.println("User: " + row.getString("last_name")); }); } }); } public void typeMapping01(PgPool pool) { pool.query("SELECT 1::BIGINT \"VAL\"", ar -> { PgRowSet rowSet = ar.result(); Row row = rowSet.iterator().next(); // Stored as java.lang.Long Object value = row.getValue(0); // Convert to java.lang.Integer Integer intValue = row.getInteger(0); }); } public void typeMapping02(PgPool pool) { pool.query("SELECT 1::BIGINT \"VAL\"", ar -> { PgRowSet rowSet = ar.result(); Row row = rowSet.iterator().next(); // Stored as java.lang.Long Object value = row.getValue(0); // Convert to java.lang.Integer Integer intValue = row.getInteger(0); }); } public void pubsub01(PgConnection connection) { connection.notificationHandler(notification -> { System.out.println("Received " + notification.getPayload() + " on channel " + notification.getChannel()); }); connection.query("LISTEN some-channel", ar -> { System.out.println("Subscribed to channel"); }); } public void pubsub02(Vertx vertx) { PgSubscriber subscriber = PgSubscriber.subscriber(vertx, new PgConnectOptions() .setPort(5432) .setHost("the-host") .setDatabase("the-db") .setUser("user") .setPassword("secret") ); // You can set the channel before connect subscriber.channel("channel1").handler(payload -> { System.out.println("Received " + payload); }); subscriber.connect(ar -> { if (ar.succeeded()) { // Or you can set the channel after connect subscriber.channel("channel2").handler(payload -> { System.out.println("Received " + payload); }); } }); } public void pubsub03(Vertx vertx) { PgSubscriber subscriber = PgSubscriber.subscriber(vertx, new PgConnectOptions() .setPort(5432) .setHost("the-host") .setDatabase("the-db") .setUser("user") .setPassword("secret") ); subscriber.connect(ar -> { if (ar.succeeded()) { // Complex channel name - name in PostgreSQL requires a quoted ID subscriber.channel("Complex.Channel.Name").handler(payload -> { System.out.println("Received " + payload); }); subscriber.channel("Complex.Channel.Name").subscribeHandler(subscribed -> { subscriber.actualConnection().query( "NOTIFY \"Complex.Channel.Name\", 'msg'", notified -> { System.out.println("Notified \"Complex.Channel.Name\""); }); }); // PostgreSQL simple ID's are forced lower-case subscriber.channel("simple_channel").handler(payload -> { System.out.println("Received " + payload); }); subscriber.channel("simple_channel").subscribeHandler(subscribed -> { // The following simple channel identifier is forced to lower case subscriber.actualConnection().query( "NOTIFY Simple_CHANNEL, 'msg'", notified -> { System.out.println("Notified simple_channel"); }); }); // The following channel name is longer than the current // (NAMEDATALEN = 64) - 1 == 63 character limit and will be truncated subscriber.channel( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbb" ).handler(payload -> { System.out.println("Received " + payload); }); } }); } public void pubsub04(Vertx vertx) { PgSubscriber subscriber = PgSubscriber.subscriber(vertx, new PgConnectOptions() .setPort(5432) .setHost("the-host") .setDatabase("the-db") .setUser("user") .setPassword("secret") ); // Reconnect at most 10 times after 100 ms each subscriber.reconnectPolicy(retries -> { if (retries < 10) { return 100L; } else { return -1L; } }); } public void ex10(Vertx vertx) { PgConnectOptions options = new PgConnectOptions() .setPort(5432) .setHost("the-host") .setDatabase("the-db") .setUser("user") .setPassword("secret") .setSslMode(SslMode.VERIFY_CA) .setPemTrustOptions(new PemTrustOptions().addCertPath("/path/to/cert.pem")); PgClient.connect(vertx, options, res -> { if (res.succeeded()) { // Connected with SSL } else { System.out.println("Could not connect " + res.cause()); } }); } public void jsonExample() { // Create a tuple Tuple tuple = Tuple.of( Json.create(Json.create(null)), Json.create(Json.create(new JsonObject().put("foo", "bar"))), Json.create(Json.create(null))); // Retrieving json Object value = tuple.getJson(0).value(); // Expect null // value = tuple.getJson(1).value(); // Expect JSON object // value = tuple.getJson(3).value(); // Expect 3 } public void numericExample(Row row) { Numeric numeric = row.getNumeric("value"); if (numeric.isNaN()) { // Handle NaN } else { BigDecimal value = numeric.bigDecimalValue(); } } public void arrayExample() { // Create a tuple with a single array Tuple tuple = Tuple.of(new String[]{ "a", "tuple", "with", "arrays" }); // Add a string array to the tuple tuple.addStringArray(new String[]{"another", "array"}); // Get the first array of string String[] array = tuple.getStringArray(0); } public void customType01Example(PgClient client) { client.preparedQuery("SELECT address, (address).city FROM address_book WHERE id=$1", Tuple.of(3), ar -> { if (ar.succeeded()) { PgRowSet rows = ar.result(); for (Row row : rows) { System.out.println("Full Address " + row.getString(0) + ", City " + row.getString(1)); } } else { System.out.println("Failure: " + ar.cause().getMessage()); } }); } public void customType02Example(PgClient client) { client.preparedQuery("INSERT INTO address_book (id, address) VALUES ($1, $2)", Tuple.of(3, "('Anytown', 'Second Ave', false)"), ar -> { if (ar.succeeded()) { PgRowSet rows = ar.result(); System.out.println(rows.rowCount()); } else { System.out.println("Failure: " + ar.cause().getMessage()); } }); } public void collector01Example(PgClient client) { // Create a collector projecting a row set to a map Collector> collector = Collectors.toMap( row -> row.getLong("id"), row -> row.getString("last_name")); // Run the query with the collector client.query("SELECT * FROM users", collector, ar -> { if (ar.succeeded()) { PgResult> result = ar.result(); // Get the map created by the collector Map map = result.value(); System.out.println("Got " + map); } else { System.out.println("Failure: " + ar.cause().getMessage()); } }); } public void collector02Example(PgClient client) { // Create a collector projecting a row set to a (last_name_1,last_name_2,...) Collector collector = Collectors.mapping( row -> row.getString("last_name"), Collectors.joining(",", "(", ")") ); // Run the query with the collector client.query("SELECT * FROM users", collector, ar -> { if (ar.succeeded()) { PgResult result = ar.result(); // Get the string created by the collector String list = result.value(); System.out.println("Got " + list); } else { System.out.println("Failure: " + ar.cause().getMessage()); } }); } public void cancelRequest(PgConnection connection) { connection.query("SELECT pg_sleep(20)", ar -> { if (ar.succeeded()) { // imagine this is a long query and is still running System.out.println("Query success"); } else { // the server will abort the current query after cancelling request System.out.println("Failed to query due to " + ar.cause().getMessage()); } }); connection.cancelRequest(ar -> { if (ar.succeeded()) { System.out.println("Cancelling request has been sent"); } else { System.out.println("Failed to send cancelling request"); } }); } } ================================================ FILE: src/main/java/examples/RxExamples.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 examples; import io.reactiverse.reactivex.pgclient.*; import io.reactivex.Completable; import io.reactivex.Flowable; import io.reactivex.Observable; import io.reactivex.Single; import io.vertx.docgen.Source; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; @Source public class RxExamples { public void simpleQuery01Example(PgPool pool) { // A simple query Single single = pool.rxQuery("SELECT * FROM users WHERE id='julien'"); // Execute the query single.subscribe(result -> { System.out.println("Got " + result.size() + " rows "); }, err -> { System.out.println("Failure: " + err.getMessage()); }); } public void streamingQuery01Example(PgPool pool) { // Create an Observable Observable observable = pool.rxBegin() // Cursors require a transaction .flatMapObservable(tx -> tx .rxPrepare("SELECT * FROM users WHERE first_name LIKE $1") .flatMapObservable(preparedQuery -> { // Fetch 50 rows at a time PgStream stream = preparedQuery.createStream(50, Tuple.of("julien")); return stream.toObservable(); }) // Commit the transaction after usage .doAfterTerminate(tx::commit)); // Then subscribe observable.subscribe(row -> { System.out.println("User: " + row.getString("last_name")); }, err -> { System.out.println("Error: " + err.getMessage()); }, () -> { System.out.println("End of stream"); }); } public void streamingQuery02Example(PgPool pool) { // Create a Flowable Flowable flowable = pool.rxBegin() // Cursors require a transaction .flatMapPublisher(tx -> tx.rxPrepare("SELECT * FROM users WHERE first_name LIKE $1") .flatMapPublisher(preparedQuery -> { // Fetch 50 rows at a time PgStream stream = preparedQuery.createStream(50, Tuple.of("julien")); return stream.toFlowable(); }) // Commit the transaction after usage .doAfterTerminate(tx::commit)); // Then subscribe flowable.subscribe(new Subscriber() { private Subscription sub; @Override public void onSubscribe(Subscription subscription) { sub = subscription; subscription.request(1); } @Override public void onNext(Row row) { sub.request(1); System.out.println("User: " + row.getString("last_name")); } @Override public void onError(Throwable err) { System.out.println("Error: " + err.getMessage()); } @Override public void onComplete() { System.out.println("End of stream"); } }); } public void transaction01Example(PgPool pool) { Completable completable = pool .rxBegin() .flatMapCompletable(tx -> tx .rxQuery("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')") .flatMap(result -> tx.rxQuery("INSERT INTO Users (first_name,last_name) VALUES ('Emad','Alblueshi')")) .flatMapCompletable(result -> tx.rxCommit())); completable.subscribe(() -> { // Transaction succeeded }, err -> { // Transaction failed }); } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/PgClient.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.reactiverse.pgclient.impl.Connection; import io.reactiverse.pgclient.impl.PgConnectionFactory; import io.reactiverse.pgclient.impl.PgConnectionImpl; import io.reactiverse.pgclient.impl.PgPoolImpl; import io.vertx.codegen.annotations.Fluent; import io.vertx.codegen.annotations.GenIgnore; import io.vertx.codegen.annotations.VertxGen; import io.vertx.core.*; import java.util.List; import java.util.stream.Collector; /** * Defines the client operations with a Postgres Database. * * @author Julien Viet */ @VertxGen public interface PgClient { /** * Like {@link #pool(PgPoolOptions)} with options build from the environment variables. */ static PgPool pool() { return pool(PgPoolOptions.fromEnv()); } /** * Like {@link #pool(PgPoolOptions)} with options build from {@code connectionUri}. */ static PgPool pool(String connectionUri) { return pool(PgPoolOptions.fromUri(connectionUri)); } /** * Like {@link #pool(Vertx, PgPoolOptions)} with options build from the environment variables. */ static PgPool pool(Vertx vertx) { return pool(vertx, PgPoolOptions.fromEnv()); } /** * Like {@link #pool(Vertx, PgPoolOptions)} with options build from {@code connectionUri}. */ static PgPool pool(Vertx vertx, String connectionUri) { return pool(vertx, PgPoolOptions.fromUri(connectionUri)); } /** * Create a connection pool to the database configured with the given {@code options}. * * @param options the options for creating the pool * @return the connection pool */ static PgPool pool(PgPoolOptions options) { if (Vertx.currentContext() != null) { throw new IllegalStateException("Running in a Vertx context => use PgPool#pool(Vertx, PgPoolOptions) instead"); } VertxOptions vertxOptions = new VertxOptions(); if (options.isUsingDomainSocket()) { vertxOptions.setPreferNativeTransport(true); } Vertx vertx = Vertx.vertx(vertxOptions); return new PgPoolImpl(vertx, true, options); } /** * Like {@link #pool(PgPoolOptions)} with a specific {@link Vertx} instance. */ static PgPool pool(Vertx vertx, PgPoolOptions options) { return new PgPoolImpl(vertx, false, options); } /** * Connects to the database and returns the connection if that succeeds. *

        * The connection interracts directly with the database is not a proxy, so closing the * connection will close the underlying connection to the database. * * @param vertx the vertx instance * @param options the connect options * @param handler the handler called with the connection or the failure */ static void connect(Vertx vertx, PgConnectOptions options, Handler> handler) { Context ctx = Vertx.currentContext(); if (ctx != null) { PgConnectionFactory client = new PgConnectionFactory(ctx, false, options); client.create(ar -> { if (ar.succeeded()) { Connection conn = ar.result(); PgConnectionImpl p = new PgConnectionImpl(client, ctx, conn); conn.init(p); handler.handle(Future.succeededFuture(p)); } else { handler.handle(Future.failedFuture(ar.cause())); } }); } else { vertx.runOnContext(v -> { if (options.isUsingDomainSocket() && !vertx.isNativeTransportEnabled()) { handler.handle(Future.failedFuture("Native transport is not available")); } else { connect(vertx, options, handler); } }); } } /** * Like {@link #connect(Vertx, PgConnectOptions, Handler)} with options build from the environment variables. */ static void connect(Vertx vertx, Handler> handler) { connect(vertx, PgConnectOptions.fromEnv(), handler); } /** * Like {@link #connect(Vertx, PgConnectOptions, Handler)} with options build from {@code connectionUri}. */ static void connect(Vertx vertx, String connectionUri, Handler> handler) { connect(vertx, PgConnectOptions.fromUri(connectionUri), handler); } /** * Execute a simple query. * * @param sql the query SQL * @param handler the handler notified with the execution result * @return a reference to this, so the API can be used fluently */ @Fluent PgClient query(String sql, Handler> handler); /** * Execute a simple query. * * @param sql the query SQL * @param collector the collector * @param handler the handler notified with the execution result * @return a reference to this, so the API can be used fluently */ @GenIgnore PgClient query(String sql, Collector collector, Handler>> handler); /** * Prepare and execute a query. * * @param sql the prepared query SQL * @param handler the handler notified with the execution result * @return a reference to this, so the API can be used fluently */ @Fluent PgClient preparedQuery(String sql, Handler> handler); /** * Prepare and execute a query. * * @param sql the prepared query SQL * @param collector the collector * @param handler the handler notified with the execution result * @return a reference to this, so the API can be used fluently */ @GenIgnore PgClient preparedQuery(String sql, Collector collector, Handler>> handler); /** * Prepare and execute a query. * * @param sql the prepared query SQL * @param arguments the list of arguments * @param handler the handler notified with the execution result * @return a reference to this, so the API can be used fluently */ @Fluent PgClient preparedQuery(String sql, Tuple arguments, Handler> handler); /** * Prepare and execute a query. * * @param sql the prepared query SQL * @param arguments the list of arguments * @param collector the collector * @param handler the handler notified with the execution result * @return a reference to this, so the API can be used fluently */ @GenIgnore PgClient preparedQuery(String sql, Tuple arguments, Collector collector, Handler>> handler); /** * Prepare and execute a createBatch. * * @param sql the prepared query SQL * @param batch the batch of tuples * @param handler the handler notified with the execution result * @return a reference to this, so the API can be used fluently */ @Fluent PgClient preparedBatch(String sql, List batch, Handler> handler); /** * Prepare and execute a createBatch. * * @param sql the prepared query SQL * @param batch the batch of tuples * @param collector the collector * @param handler the handler notified with the execution result * @return a reference to this, so the API can be used fluently */ @GenIgnore PgClient preparedBatch(String sql, List batch, Collector collector, Handler>> handler); /** * Close the client and release the associated resources. */ void close(); } ================================================ FILE: src/main/java/io/reactiverse/pgclient/PgConnectOptions.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.reactiverse.pgclient.impl.PgConnectionUriParser; import io.vertx.codegen.annotations.DataObject; import io.vertx.core.buffer.Buffer; import io.vertx.core.json.JsonObject; import io.vertx.core.net.*; import java.util.Set; import static java.lang.Integer.parseInt; import static java.lang.System.getenv; /** * @author Julien Viet * @author Billy Yuan */ @DataObject(generateConverter = true) public class PgConnectOptions extends NetClientOptions { /** * Provide a {@link PgConnectOptions} configured from a connection URI. * * @param connectionUri the connection URI to configure from * @return a {@link PgConnectOptions} parsed from the connection URI * @throws IllegalArgumentException when the {@code connectionUri} is in an invalid format */ public static PgConnectOptions fromUri(String connectionUri) throws IllegalArgumentException { JsonObject parsedConfiguration = PgConnectionUriParser.parse(connectionUri); return new PgConnectOptions(parsedConfiguration); } /** * Provide a {@link PgConnectOptions} configured with environment variables, if the environment variable * is not set, then a default value will take precedence over this. */ public static PgConnectOptions fromEnv() { PgConnectOptions pgConnectOptions = new PgConnectOptions(); if (getenv("PGHOSTADDR") == null) { if (getenv("PGHOST") != null) { pgConnectOptions.setHost(getenv("PGHOST")); } } else { pgConnectOptions.setHost(getenv("PGHOSTADDR")); } if (getenv("PGPORT") != null) { try { pgConnectOptions.setPort(parseInt(getenv("PGPORT"))); } catch (NumberFormatException e) { // port will be set to default } } if (getenv("PGDATABASE") != null) { pgConnectOptions.setDatabase(getenv("PGDATABASE")); } if (getenv("PGUSER") != null) { pgConnectOptions.setUser(getenv("PGUSER")); } if (getenv("PGPASSWORD") != null) { pgConnectOptions.setPassword(getenv("PGPASSWORD")); } if (getenv("PGSSLMODE") != null) { pgConnectOptions.setSslMode(SslMode.of(getenv("PGSSLMODE"))); } return pgConnectOptions; } public static final String DEFAULT_HOST = "localhost"; public static int DEFAULT_PORT = 5432; public static final String DEFAULT_DATABASE = "db"; public static final String DEFAULT_USER = "user"; public static final String DEFAULT_PASSWORD = "pass"; public static final boolean DEFAULT_CACHE_PREPARED_STATEMENTS = false; public static final int DEFAULT_PIPELINING_LIMIT = 256; public static final SslMode DEFAULT_SSLMODE = SslMode.DISABLE; private String host; private int port; private String database; private String user; private String password; private boolean cachePreparedStatements; private int pipeliningLimit; private SslMode sslMode; public PgConnectOptions() { super(); init(); } public PgConnectOptions(JsonObject json) { super(json); init(); PgConnectOptionsConverter.fromJson(json, this); } public PgConnectOptions(PgConnectOptions other) { super(other); host = other.host; port = other.port; database = other.database; user = other.user; password = other.password; pipeliningLimit = other.pipeliningLimit; cachePreparedStatements = other.cachePreparedStatements; sslMode = other.sslMode; } public String getHost() { return host; } public PgConnectOptions setHost(String host) { this.host = host; return this; } public int getPort() { return port; } public PgConnectOptions setPort(int port) { this.port = port; return this; } public String getDatabase() { return database; } public PgConnectOptions setDatabase(String database) { this.database = database; return this; } public String getUser() { return user; } public PgConnectOptions setUser(String user) { this.user = user; return this; } public String getPassword() { return password; } public PgConnectOptions setPassword(String password) { this.password = password; return this; } public int getPipeliningLimit() { return pipeliningLimit; } public PgConnectOptions setPipeliningLimit(int pipeliningLimit) { if (pipeliningLimit < 1) { throw new IllegalArgumentException(); } this.pipeliningLimit = pipeliningLimit; return this; } public boolean getCachePreparedStatements() { return cachePreparedStatements; } public PgConnectOptions setCachePreparedStatements(boolean cachePreparedStatements) { this.cachePreparedStatements = cachePreparedStatements; return this; } /** * @return the value of current sslmode */ public SslMode getSslMode() { return sslMode; } /** * Set {@link SslMode} for the client, this option can be used to provide different levels of secure protection. * * @param sslmode the value of sslmode * @return a reference to this, so the API can be used fluently */ public PgConnectOptions setSslMode(SslMode sslmode) { this.sslMode = sslmode; return this; } @Override public PgConnectOptions setSendBufferSize(int sendBufferSize) { return (PgConnectOptions)super.setSendBufferSize(sendBufferSize); } @Override public PgConnectOptions setReceiveBufferSize(int receiveBufferSize) { return (PgConnectOptions)super.setReceiveBufferSize(receiveBufferSize); } @Override public PgConnectOptions setReuseAddress(boolean reuseAddress) { return (PgConnectOptions)super.setReuseAddress(reuseAddress); } @Override public PgConnectOptions setTrafficClass(int trafficClass) { return (PgConnectOptions)super.setTrafficClass(trafficClass); } @Override public PgConnectOptions setTcpNoDelay(boolean tcpNoDelay) { return (PgConnectOptions)super.setTcpNoDelay(tcpNoDelay); } @Override public PgConnectOptions setTcpKeepAlive(boolean tcpKeepAlive) { return (PgConnectOptions)super.setTcpKeepAlive(tcpKeepAlive); } @Override public PgConnectOptions setSoLinger(int soLinger) { return (PgConnectOptions)super.setSoLinger(soLinger); } @Override public PgConnectOptions setUsePooledBuffers(boolean usePooledBuffers) { return (PgConnectOptions)super.setUsePooledBuffers(usePooledBuffers); } @Override public PgConnectOptions setIdleTimeout(int idleTimeout) { return (PgConnectOptions)super.setIdleTimeout(idleTimeout); } @Override public PgConnectOptions setSsl(boolean ssl) { if (ssl) { setSslMode(SslMode.VERIFY_CA); } else { setSslMode(SslMode.DISABLE); } return this; } @Override public PgConnectOptions setKeyCertOptions(KeyCertOptions options) { return (PgConnectOptions)super.setKeyCertOptions(options); } @Override public PgConnectOptions setKeyStoreOptions(JksOptions options) { return (PgConnectOptions)super.setKeyStoreOptions(options); } @Override public PgConnectOptions setPfxKeyCertOptions(PfxOptions options) { return (PgConnectOptions)super.setPfxKeyCertOptions(options); } @Override public PgConnectOptions setPemKeyCertOptions(PemKeyCertOptions options) { return (PgConnectOptions)super.setPemKeyCertOptions(options); } @Override public PgConnectOptions setTrustOptions(TrustOptions options) { return (PgConnectOptions)super.setTrustOptions(options); } @Override public PgConnectOptions setTrustStoreOptions(JksOptions options) { return (PgConnectOptions)super.setTrustStoreOptions(options); } @Override public PgConnectOptions setPemTrustOptions(PemTrustOptions options) { return (PgConnectOptions)super.setPemTrustOptions(options); } @Override public PgConnectOptions setPfxTrustOptions(PfxOptions options) { return (PgConnectOptions)super.setPfxTrustOptions(options); } @Override public PgConnectOptions addEnabledCipherSuite(String suite) { return (PgConnectOptions)super.addEnabledCipherSuite(suite); } @Override public PgConnectOptions addEnabledSecureTransportProtocol(String protocol) { return (PgConnectOptions)super.addEnabledSecureTransportProtocol(protocol); } @Override public PgConnectOptions addCrlPath(String crlPath) throws NullPointerException { return (PgConnectOptions)super.addCrlPath(crlPath); } @Override public PgConnectOptions addCrlValue(Buffer crlValue) throws NullPointerException { return (PgConnectOptions)super.addCrlValue(crlValue); } @Override public PgConnectOptions setTrustAll(boolean trustAll) { return (PgConnectOptions)super.setTrustAll(trustAll); } @Override public PgConnectOptions setConnectTimeout(int connectTimeout) { return (PgConnectOptions)super.setConnectTimeout(connectTimeout); } @Override public PgConnectOptions setMetricsName(String metricsName) { return (PgConnectOptions)super.setMetricsName(metricsName); } @Override public PgConnectOptions setReconnectAttempts(int attempts) { return (PgConnectOptions)super.setReconnectAttempts(attempts); } @Override public PgConnectOptions setHostnameVerificationAlgorithm(String hostnameVerificationAlgorithm) { return (PgConnectOptions)super.setHostnameVerificationAlgorithm(hostnameVerificationAlgorithm); } @Override public PgConnectOptions setLogActivity(boolean logEnabled) { return (PgConnectOptions)super.setLogActivity(logEnabled); } @Override public PgConnectOptions setReconnectInterval(long interval) { return (PgConnectOptions)super.setReconnectInterval(interval); } @Override public PgConnectOptions setProxyOptions(ProxyOptions proxyOptions) { return (PgConnectOptions)super.setProxyOptions(proxyOptions); } @Override public PgConnectOptions setLocalAddress(String localAddress) { return (PgConnectOptions)super.setLocalAddress(localAddress); } @Override public PgConnectOptions setUseAlpn(boolean useAlpn) { return (PgConnectOptions)super.setUseAlpn(useAlpn); } @Override public PgConnectOptions setSslEngineOptions(SSLEngineOptions sslEngineOptions) { return (PgConnectOptions)super.setSslEngineOptions(sslEngineOptions); } @Override public PgConnectOptions setJdkSslEngineOptions(JdkSSLEngineOptions sslEngineOptions) { return (PgConnectOptions)super.setJdkSslEngineOptions(sslEngineOptions); } @Override public PgConnectOptions setOpenSslEngineOptions(OpenSSLEngineOptions sslEngineOptions) { return (PgConnectOptions)super.setOpenSslEngineOptions(sslEngineOptions); } @Override public PgConnectOptions setReusePort(boolean reusePort) { return (PgConnectOptions) super.setReusePort(reusePort); } @Override public PgConnectOptions setTcpFastOpen(boolean tcpFastOpen) { return (PgConnectOptions) super.setTcpFastOpen(tcpFastOpen); } @Override public PgConnectOptions setTcpCork(boolean tcpCork) { return (PgConnectOptions) super.setTcpCork(tcpCork); } @Override public PgConnectOptions setTcpQuickAck(boolean tcpQuickAck) { return (PgConnectOptions) super.setTcpQuickAck(tcpQuickAck); } @Override public PgConnectOptions setEnabledSecureTransportProtocols(Set enabledSecureTransportProtocols) { return (PgConnectOptions) super.setEnabledSecureTransportProtocols(enabledSecureTransportProtocols); } /** * Initialize with the default options. */ private void init() { host = DEFAULT_HOST; port = DEFAULT_PORT; database = DEFAULT_DATABASE; user = DEFAULT_USER; password = DEFAULT_PASSWORD; cachePreparedStatements = DEFAULT_CACHE_PREPARED_STATEMENTS; pipeliningLimit = DEFAULT_PIPELINING_LIMIT; sslMode = DEFAULT_SSLMODE; } @Override public JsonObject toJson() { JsonObject json = super.toJson(); PgConnectOptionsConverter.toJson(this, json); return json; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof PgConnectOptions)) return false; if (!super.equals(o)) return false; PgConnectOptions that = (PgConnectOptions) o; if (!host.equals(that.host)) return false; if (port != that.port) return false; if (!database.equals(that.database)) return false; if (!user.equals(that.user)) return false; if (!password.equals(that.password)) return false; if (cachePreparedStatements != that.cachePreparedStatements) return false; if (pipeliningLimit != that.pipeliningLimit) return false; if (sslMode != that.sslMode) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + host.hashCode(); result = 31 * result + port; result = 31 * result + database.hashCode(); result = 31 * result + user.hashCode(); result = 31 * result + password.hashCode(); result = 31 * result + (cachePreparedStatements ? 1 : 0); result = 31 * result + pipeliningLimit; result = 31 * result + sslMode.hashCode(); return result; } public boolean isUsingDomainSocket() { return this.getHost().startsWith("/"); } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/PgConnection.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.vertx.codegen.annotations.Fluent; import io.vertx.codegen.annotations.GenIgnore; import io.vertx.codegen.annotations.VertxGen; import io.vertx.core.*; import java.util.List; import java.util.stream.Collector; /** * A connection to Postgres. * * @author Julien Viet * @author Emad Alblueshi */ @VertxGen public interface PgConnection extends PgClient { /** * Create a prepared query. * * @param sql the sql * @param handler the handler notified with the prepared query asynchronously */ @Fluent PgConnection prepare(String sql, Handler> handler); /** * Set an handler called with connection errors. * * @param handler the handler * @return a reference to this, so the API can be used fluently */ @Fluent PgConnection exceptionHandler(Handler handler); /** * Set an handler called when the connection is closed. * * @param handler the handler * @return a reference to this, so the API can be used fluently */ @Fluent PgConnection closeHandler(Handler handler); /** * Begin a transaction and returns a {@link PgTransaction} for controlling and tracking * this transaction. *

        * When the connection is explicitely closed, any inflight transaction is rollbacked. * * @return the transaction instance */ PgTransaction begin(); /** * Set an handler called when the connection receives notification on a channel. *

        * The handler is called with the {@link PgNotification} and has access to the channel name * and the notification payload. * * @param handler the handler * @return the transaction instance */ @Fluent PgConnection notificationHandler(Handler handler); /** * @return The process ID of the target backend */ int processId(); /** * @return The secret key for the target backend */ int secretKey(); /** * Send a request cancellation message to tell the server to cancel processing request in this connection. *
        Note: Use this with caution because the cancellation signal may or may not have any effect. * * @param handler the handler notified if cancelling request is sent * @return a reference to this, so the API can be used fluently */ PgConnection cancelRequest(Handler> handler); /** * @return whether the connection uses SSL */ boolean isSSL(); /** * Close the current connection after all the pending commands have been processed. */ void close(); @Override PgConnection preparedQuery(String sql, Handler> handler); @Override @GenIgnore PgConnection preparedQuery(String sql, Collector collector, Handler>> handler); @Override PgConnection query(String sql, Handler> handler); @Override @GenIgnore PgConnection query(String sql, Collector collector, Handler>> handler); @Override PgConnection preparedQuery(String sql, Tuple arguments, Handler> handler); @Override @GenIgnore PgConnection preparedQuery(String sql, Tuple arguments, Collector collector, Handler>> handler); @Override PgConnection preparedBatch(String sql, List batch, Handler> handler); @Override @GenIgnore PgConnection preparedBatch(String sql, List batch, Collector collector, Handler>> handler); } ================================================ FILE: src/main/java/io/reactiverse/pgclient/PgCursor.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.vertx.codegen.annotations.VertxGen; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; /** * A cursor that reads progressively the rows from Postgres, it is usefull for reading very large result. */ @VertxGen public interface PgCursor { /** * Read rows from the cursor, the result is provided asynchronously to the {@code handler}. * * @param count the amount of rows to read * @param handler the handler for the result */ void read(int count, Handler> handler); /** * Returns {@code true} when the cursor has results in progress and the {@link #execute} should be called to retrieve * them. * * @return whether the cursor has more results, */ boolean hasMore(); /** * Release the cursor. *

        * It should be called for prepared queries executed with a fetch size. */ default void close() { close(ar -> {}); } /** * Like {@link #close()} but with a {@code completionHandler} called when the cursor has been released. */ void close(Handler> completionHandler); } ================================================ FILE: src/main/java/io/reactiverse/pgclient/PgException.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.reactiverse.pgclient.impl.codec.decoder.ErrorResponse; /** * @author Julien Viet */ public class PgException extends RuntimeException { private final ErrorResponse error; public PgException(ErrorResponse error) { super(error.getMessage()); this.error = error; } public String getSeverity() { return error.getSeverity(); } public String getCode() { return error.getCode(); } /** * @return the detail error message */ public String getDetail() { return error.getDetail(); } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/PgIterator.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.vertx.codegen.annotations.VertxGen; import java.util.Iterator; /** * An iterator for processing postgres items synchronously. */ @VertxGen public interface PgIterator extends Iterator { @Override boolean hasNext(); @Override Row next(); } ================================================ FILE: src/main/java/io/reactiverse/pgclient/PgNotification.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.vertx.codegen.annotations.DataObject; import io.vertx.core.json.JsonObject; /** * A notification emited by Postgres. */ @DataObject(generateConverter = true) public class PgNotification { private int processId; private String channel; private String payload; public PgNotification() { } public PgNotification(JsonObject json) { PgNotificationConverter.fromJson(json, this); } /** * @return the notification process id */ public int getProcessId() { return processId; } /** * Set the process id. * * @return a reference to this, so the API can be used fluently */ public PgNotification setProcessId(int processId) { this.processId = processId; return this; } /** * @return the notification channel value */ public String getChannel() { return channel; } /** * Set the channel value. * * @return a reference to this, so the API can be used fluently */ public PgNotification setChannel(String channel) { this.channel = channel; return this; } /** * @return the notification payload value */ public String getPayload() { return payload; } /** * Set the payload value. * * @return a reference to this, so the API can be used fluently */ public PgNotification setPayload(String payload) { this.payload = payload; return this; } public JsonObject toJson() { JsonObject json = new JsonObject(); PgNotificationConverter.toJson(this, json); return json; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/PgPool.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.vertx.codegen.annotations.GenIgnore; import io.vertx.codegen.annotations.VertxGen; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import java.util.List; import java.util.stream.Collector; /** * A pool of connection. * * @author Julien Viet */ @VertxGen public interface PgPool extends PgClient { @Override PgPool preparedQuery(String sql, Handler> handler); @Override @GenIgnore PgPool preparedQuery(String sql, Collector collector, Handler>> handler); @Override PgPool query(String sql, Handler> handler); @Override @GenIgnore PgPool query(String sql, Collector collector, Handler>> handler); @Override PgPool preparedQuery(String sql, Tuple arguments, Handler> handler); @Override @GenIgnore PgPool preparedQuery(String sql, Tuple arguments, Collector collector, Handler>> handler); @Override PgPool preparedBatch(String sql, List batch, Handler> handler); @Override @GenIgnore PgPool preparedBatch(String sql, List batch, Collector collector, Handler>> handler); /** * Get a connection from the pool. * * @param handler the handler that will get the connection result */ void getConnection(Handler> handler); /** * Borrow a connection from the pool and begin a transaction, the underlying connection will be returned * to the pool when the transaction ends. * * @return the transaction */ void begin(Handler> handler); /** * Close the pool and release the associated resources. */ void close(); } ================================================ FILE: src/main/java/io/reactiverse/pgclient/PgPoolOptions.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.vertx.codegen.annotations.DataObject; import io.vertx.core.buffer.Buffer; import io.vertx.core.json.JsonObject; import io.vertx.core.net.*; /** * The options for configuring a connection pool. * * @author Julien Viet */ @DataObject(generateConverter = true) public class PgPoolOptions extends PgConnectOptions { /** * Provide a {@link PgPoolOptions} configured from a connection URI. * * @param connectionUri the connection URI to configure from * @return a {@link PgPoolOptions} parsed from the connection URI * @throws IllegalArgumentException when the {@code connectionUri} is in an invalid format */ public static PgPoolOptions fromUri(String connectionUri) throws IllegalArgumentException { return new PgPoolOptions(PgConnectOptions.fromUri(connectionUri)); } /** * Provide a {@link PgPoolOptions} configured with environment variables, if the environment variable * is not set, then a default value will take precedence over this. */ public static PgPoolOptions fromEnv() { return new PgPoolOptions(PgConnectOptions.fromEnv()); } /** * The default maximum number of connections a client will pool = 4 */ public static final int DEFAULT_MAX_SIZE = 4; /** * Default max wait queue size = -1 (unbounded) */ public static final int DEFAULT_MAX_WAIT_QUEUE_SIZE = -1; private int maxSize = DEFAULT_MAX_SIZE; private int maxWaitQueueSize = DEFAULT_MAX_WAIT_QUEUE_SIZE; public PgPoolOptions() { } public PgPoolOptions(JsonObject json) { super(json); PgPoolOptionsConverter.fromJson(json, this); } public PgPoolOptions(PgPoolOptions other) { super(other); maxSize = other.maxSize; maxWaitQueueSize = other.maxWaitQueueSize; } public PgPoolOptions(PgConnectOptions other) { super(other); } /** * @return the maximum pool size */ public int getMaxSize() { return maxSize; } /** * Set the maximum pool size * * @param maxSize the maximum pool size * @return a reference to this, so the API can be used fluently */ public PgPoolOptions setMaxSize(int maxSize) { if (maxSize < 0) { throw new IllegalArgumentException("Max size cannot be negative"); } this.maxSize = maxSize; return this; } /** * @return the maximum wait queue size */ public int getMaxWaitQueueSize() { return maxWaitQueueSize; } /** * Set the maximum connection request allowed in the wait queue, any requests beyond the max size will result in * an failure. If the value is set to a negative number then the queue will be unbounded. * * @param maxWaitQueueSize the maximum number of waiting requests * @return a reference to this, so the API can be used fluently */ public PgPoolOptions setMaxWaitQueueSize(int maxWaitQueueSize) { this.maxWaitQueueSize = maxWaitQueueSize; return this; } @Override public PgPoolOptions setHost(String host) { return (PgPoolOptions) super.setHost(host); } @Override public PgPoolOptions setPort(int port) { return (PgPoolOptions) super.setPort(port); } @Override public PgPoolOptions setDatabase(String database) { return (PgPoolOptions) super.setDatabase(database); } @Override public PgPoolOptions setUser(String user) { return (PgPoolOptions) super.setUser(user); } @Override public PgPoolOptions setPassword(String password) { return (PgPoolOptions) super.setPassword(password); } @Override public PgPoolOptions setPipeliningLimit(int pipeliningLimit) { return (PgPoolOptions) super.setPipeliningLimit(pipeliningLimit); } @Override public PgPoolOptions setCachePreparedStatements(boolean cachePreparedStatements) { return (PgPoolOptions) super.setCachePreparedStatements(cachePreparedStatements); } @Override public PgPoolOptions setSslMode(SslMode sslmode) { return (PgPoolOptions) super.setSslMode(sslmode); } @Override public PgPoolOptions setSendBufferSize(int sendBufferSize) { return (PgPoolOptions) super.setSendBufferSize(sendBufferSize); } @Override public PgPoolOptions setReceiveBufferSize(int receiveBufferSize) { return (PgPoolOptions) super.setReceiveBufferSize(receiveBufferSize); } @Override public PgPoolOptions setReuseAddress(boolean reuseAddress) { return (PgPoolOptions) super.setReuseAddress(reuseAddress); } @Override public PgPoolOptions setTrafficClass(int trafficClass) { return (PgPoolOptions) super.setTrafficClass(trafficClass); } @Override public PgPoolOptions setTcpNoDelay(boolean tcpNoDelay) { return (PgPoolOptions) super.setTcpNoDelay(tcpNoDelay); } @Override public PgPoolOptions setTcpKeepAlive(boolean tcpKeepAlive) { return (PgPoolOptions) super.setTcpKeepAlive(tcpKeepAlive); } @Override public PgPoolOptions setSoLinger(int soLinger) { return (PgPoolOptions) super.setSoLinger(soLinger); } @Override public PgPoolOptions setUsePooledBuffers(boolean usePooledBuffers) { return (PgPoolOptions) super.setUsePooledBuffers(usePooledBuffers); } @Override public PgPoolOptions setIdleTimeout(int idleTimeout) { return (PgPoolOptions) super.setIdleTimeout(idleTimeout); } @Override public PgPoolOptions setSsl(boolean ssl) { return (PgPoolOptions) super.setSsl(ssl); } @Override public PgPoolOptions setKeyCertOptions(KeyCertOptions options) { return (PgPoolOptions) super.setKeyCertOptions(options); } @Override public PgPoolOptions setKeyStoreOptions(JksOptions options) { return (PgPoolOptions) super.setKeyStoreOptions(options); } @Override public PgPoolOptions setPfxKeyCertOptions(PfxOptions options) { return (PgPoolOptions) super.setPfxKeyCertOptions(options); } @Override public PgPoolOptions setPemKeyCertOptions(PemKeyCertOptions options) { return (PgPoolOptions) super.setPemKeyCertOptions(options); } @Override public PgPoolOptions setTrustOptions(TrustOptions options) { return (PgPoolOptions) super.setTrustOptions(options); } @Override public PgPoolOptions setTrustStoreOptions(JksOptions options) { return (PgPoolOptions) super.setTrustStoreOptions(options); } @Override public PgPoolOptions setPemTrustOptions(PemTrustOptions options) { return (PgPoolOptions) super.setPemTrustOptions(options); } @Override public PgPoolOptions setPfxTrustOptions(PfxOptions options) { return (PgPoolOptions) super.setPfxTrustOptions(options); } @Override public PgPoolOptions addEnabledCipherSuite(String suite) { return (PgPoolOptions) super.addEnabledCipherSuite(suite); } @Override public PgPoolOptions addEnabledSecureTransportProtocol(String protocol) { return (PgPoolOptions) super.addEnabledSecureTransportProtocol(protocol); } @Override public PgPoolOptions addCrlPath(String crlPath) throws NullPointerException { return (PgPoolOptions) super.addCrlPath(crlPath); } @Override public PgPoolOptions addCrlValue(Buffer crlValue) throws NullPointerException { return (PgPoolOptions) super.addCrlValue(crlValue); } @Override public PgPoolOptions setTrustAll(boolean trustAll) { return (PgPoolOptions) super.setTrustAll(trustAll); } @Override public PgPoolOptions setConnectTimeout(int connectTimeout) { return (PgPoolOptions) super.setConnectTimeout(connectTimeout); } @Override public PgPoolOptions setMetricsName(String metricsName) { return (PgPoolOptions) super.setMetricsName(metricsName); } @Override public PgPoolOptions setReconnectAttempts(int attempts) { return (PgPoolOptions) super.setReconnectAttempts(attempts); } @Override public PgPoolOptions setHostnameVerificationAlgorithm(String hostnameVerificationAlgorithm) { return (PgPoolOptions) super.setHostnameVerificationAlgorithm(hostnameVerificationAlgorithm); } @Override public PgPoolOptions setLogActivity(boolean logEnabled) { return (PgPoolOptions) super.setLogActivity(logEnabled); } @Override public PgPoolOptions setReconnectInterval(long interval) { return (PgPoolOptions) super.setReconnectInterval(interval); } @Override public PgPoolOptions setProxyOptions(ProxyOptions proxyOptions) { return (PgPoolOptions) super.setProxyOptions(proxyOptions); } @Override public PgPoolOptions setLocalAddress(String localAddress) { return (PgPoolOptions) super.setLocalAddress(localAddress); } @Override public PgPoolOptions setUseAlpn(boolean useAlpn) { return (PgPoolOptions) super.setUseAlpn(useAlpn); } @Override public PgPoolOptions setSslEngineOptions(SSLEngineOptions sslEngineOptions) { return (PgPoolOptions) super.setSslEngineOptions(sslEngineOptions); } @Override public PgPoolOptions setJdkSslEngineOptions(JdkSSLEngineOptions sslEngineOptions) { return (PgPoolOptions) super.setJdkSslEngineOptions(sslEngineOptions); } @Override public PgPoolOptions setOpenSslEngineOptions(OpenSSLEngineOptions sslEngineOptions) { return (PgPoolOptions) super.setOpenSslEngineOptions(sslEngineOptions); } @Override public PgPoolOptions setReusePort(boolean reusePort) { return (PgPoolOptions) super.setReusePort(reusePort); } @Override public PgPoolOptions setTcpFastOpen(boolean tcpFastOpen) { return (PgPoolOptions) super.setTcpFastOpen(tcpFastOpen); } @Override public PgPoolOptions setTcpCork(boolean tcpCork) { return (PgPoolOptions) super.setTcpCork(tcpCork); } @Override public PgPoolOptions setTcpQuickAck(boolean tcpQuickAck) { return (PgPoolOptions) super.setTcpQuickAck(tcpQuickAck); } @Override public JsonObject toJson() { JsonObject json = super.toJson(); PgPoolOptionsConverter.toJson(this, json); return json; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof PgPoolOptions)) return false; if (!super.equals(o)) return false; PgPoolOptions that = (PgPoolOptions) o; if (maxSize != that.maxSize) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + maxSize; return result; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/PgPreparedQuery.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.reactiverse.pgclient.impl.ArrayTuple; import io.vertx.codegen.annotations.Fluent; import io.vertx.codegen.annotations.GenIgnore; import io.vertx.codegen.annotations.VertxGen; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import java.util.List; import java.util.stream.Collector; /** * A prepared query. * * @author Julien Viet */ @VertxGen public interface PgPreparedQuery { /** * Calls {@link #execute(Tuple, Handler)} with an empty tuple argument. */ @Fluent default PgPreparedQuery execute(Handler> handler) { return execute(ArrayTuple.EMPTY, handler); } /** * Calls {@link #execute(Tuple, Collector, Handler)} with an empty tuple argument. */ @GenIgnore default PgPreparedQuery execute(Collector collector, Handler>> handler) { return execute(ArrayTuple.EMPTY, collector, handler); } /** * Create a cursor with the provided {@code arguments}. * * @param args the list of arguments * @return the query */ @Fluent PgPreparedQuery execute(Tuple args, Handler> handler); /** * Create a cursor with the provided {@code arguments}. * * @param args the list of arguments * @param collector the collector * @return the query */ @GenIgnore PgPreparedQuery execute(Tuple args, Collector collector, Handler>> handler); /** * @return create a query cursor with a {@code fetch} size and empty arguments */ default PgCursor cursor() { return cursor(ArrayTuple.EMPTY); } /** * Create a cursor with the provided {@code arguments}. * * @param args the list of arguments * @return the query */ PgCursor cursor(Tuple args); /** * Execute the prepared query with a cursor and createStream the result. The createStream opens a cursor * with a {@code fetch} size to fetch the results. *

        * Note: this requires to be in a transaction, since cursors require it. * * @param fetch the cursor fetch size * @param args the prepared query arguments * @return the createStream */ PgStream createStream(int fetch, Tuple args); /** * Execute a batch. * * @param argsList the list of tuple for the batch * @return the createBatch */ @Fluent PgPreparedQuery batch(List argsList, Handler> handler); /** * Execute a batch. * * @param argsList the list of tuple for the batch * @param collector the collector * @return the createBatch */ @GenIgnore PgPreparedQuery batch(List argsList, Collector collector, Handler>> handler); /** * Close the prepared query and release its resources. */ void close(); /** * Like {@link #close()} but notifies the {@code completionHandler} when it's closed. */ void close(Handler> completionHandler); } ================================================ FILE: src/main/java/io/reactiverse/pgclient/PgResult.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.vertx.codegen.annotations.VertxGen; import java.util.List; /** * Represents the result of an operation on database. * @param */ @VertxGen public interface PgResult { /** * Get the number of the affected rows in the operation to this PgResult. *

        * The meaning depends on the executed statement: *

          *
        • INSERT: the number of rows inserted
        • *
        • DELETE: the number of rows deleted
        • *
        • UPDATE: the number of rows updated
        • *
        • SELECT: the number of rows retrieved
        • *
        * * @return the count of affected rows. */ int rowCount(); /** * Get the names of columns in the PgResult. * * @return the list of names of columns. */ List columnsNames(); /** * Get the number of rows in the PgResult. * * @return the count of rows. */ int size(); /** * Get the result value. * * @return the result */ T value(); /** * Return the next available result or {@code null}, e.g for a simple query that executed multiple queries or for * a batch result. * * @return the next available result or {@code null} if none is available */ PgResult next(); } ================================================ FILE: src/main/java/io/reactiverse/pgclient/PgRowSet.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.vertx.codegen.annotations.VertxGen; /** * A set of rows. */ @VertxGen public interface PgRowSet extends Iterable, PgResult { @Override PgIterator iterator(); @Override PgRowSet next(); } ================================================ FILE: src/main/java/io/reactiverse/pgclient/PgStream.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.vertx.codegen.annotations.VertxGen; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import io.vertx.core.streams.ReadStream; /** * A row oriented stream. */ @VertxGen public interface PgStream extends ReadStream { @Override PgStream exceptionHandler(Handler handler); @Override PgStream handler(Handler handler); @Override PgStream pause(); @Override PgStream resume(); @Override PgStream endHandler(Handler endHandler); /** * Close the stream and release the resources. */ void close(); /** * Close the stream and release the resources. * * @param completionHandler the completion handler for this operation */ void close(Handler> completionHandler); } ================================================ FILE: src/main/java/io/reactiverse/pgclient/PgTransaction.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.vertx.codegen.annotations.Fluent; import io.vertx.codegen.annotations.GenIgnore; import io.vertx.codegen.annotations.VertxGen; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import java.util.List; import java.util.stream.Collector; /** * A transaction that allows to control the transaction and receive events. */ @VertxGen public interface PgTransaction extends PgClient { /** * Create a prepared query. * * @param sql the sql * @param handler the handler notified with the prepared query asynchronously */ @Fluent PgTransaction prepare(String sql, Handler> handler); /** * Commit the current transaction. */ void commit(); /** * Like {@link #commit} with an handler to be notified when the transaction commit has completed */ void commit(Handler> handler); /** * Rollback the current transaction. */ void rollback(); /** * Like {@link #rollback} with an handler to be notified when the transaction rollback has completed */ void rollback(Handler> handler); /** * Set an handler to be called when the transaction is aborted. * * @param handler the handler */ @Fluent PgTransaction abortHandler(Handler handler); @Override PgTransaction query(String sql, Handler> handler); @Override @GenIgnore PgTransaction query(String sql, Collector collector, Handler>> handler); @Override PgTransaction preparedQuery(String sql, Handler> handler); @Override @GenIgnore PgTransaction preparedQuery(String sql, Collector collector, Handler>> handler); @Override PgTransaction preparedQuery(String sql, Tuple arguments, Handler> handler); @Override @GenIgnore PgTransaction preparedQuery(String sql, Tuple arguments, Collector collector, Handler>> handler); @Override PgTransaction preparedBatch(String sql, List batch, Handler> handler); @Override @GenIgnore PgTransaction preparedBatch(String sql, List batch, Collector collector, Handler>> handler); /** * Rollback the transaction and release the associated resources. */ void close(); } ================================================ FILE: src/main/java/io/reactiverse/pgclient/Row.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.reactiverse.pgclient.data.Box; import io.reactiverse.pgclient.data.Circle; import io.reactiverse.pgclient.data.Interval; import io.reactiverse.pgclient.data.Json; import io.reactiverse.pgclient.data.Line; import io.reactiverse.pgclient.data.LineSegment; import io.reactiverse.pgclient.data.Numeric; import io.reactiverse.pgclient.data.Path; import io.reactiverse.pgclient.data.Point; import io.reactiverse.pgclient.data.Polygon; import io.vertx.codegen.annotations.GenIgnore; import io.vertx.codegen.annotations.VertxGen; import io.vertx.core.buffer.Buffer; import java.math.BigDecimal; import java.time.*; import java.time.temporal.Temporal; import java.util.UUID; @VertxGen public interface Row extends Tuple { /** * Get a column name at {@code pos}. * * @param pos the position * @return the column name or {@code null} */ String getColumnName(int pos); /** * Get a boolean value at {@code pos}. * * @param name the column * @return the value or {@code null} */ Boolean getBoolean(String name); /** * Get an object value at {@code pos}. * * @param name the column * @return the value or {@code null} */ Object getValue(String name); /** * Get a short value at {@code pos}. * * @param name the column * @return the value or {@code null} */ Short getShort(String name); /** * Get an integer value at {@code pos}. * * @param name the column * @return the value or {@code null} */ Integer getInteger(String name); /** * Get a long value at {@code pos}. * * @param name the column * @return the value or {@code null} */ Long getLong(String name); /** * Get a float value at {@code pos}. * * @param name the column * @return the value or {@code null} */ Float getFloat(String name); /** * Get a double value at {@code pos}. * * @param name the column * @return the value or {@code null} */ Double getDouble(String name); /** * Get a string value at {@code pos}. * * @param name the column * @return the value or {@code null} */ String getString(String name); /** * Get a json value at {@code pos}. * * @param name the column * @return the value or {@code null} */ Json getJson(String name); /** * Get a buffer value at {@code pos}. * * @param name the column * @return the value or {@code null} */ Buffer getBuffer(String name); /** * Get a temporal value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Temporal getTemporal(String name); /** * Get {@link java.time.LocalDate} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) LocalDate getLocalDate(String name); /** * Get {@link java.time.LocalTime} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) LocalTime getLocalTime(String name); /** * Get {@link java.time.LocalDateTime} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) LocalDateTime getLocalDateTime(String name); /** * Get {@link java.time.OffsetTime} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) OffsetTime getOffsetTime(String name); /** * Get {@link java.time.OffsetDateTime} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) OffsetDateTime getOffsetDateTime(String name); /** * Get {@link java.util.UUID} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) UUID getUUID(String name); /** * Get {@link BigDecimal} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) BigDecimal getBigDecimal(String name); /** * Get {@link Numeric} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Numeric getNumeric(String name); /** * Get {@link Point} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ Point getPoint(String name); /** * Get {@link Line} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ Line getLine(String name); /** * Get {@link LineSegment} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ LineSegment getLineSegment(String name); /** * Get {@link Box} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ Box getBox(String name); /** * Get {@link Path} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ Path getPath(String name); /** * Get {@link Polygon} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ Polygon getPolygon(String name); /** * Get {@link Circle} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ Circle getCircle(String name); /** * Get {@link Interval} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ Interval getInterval(String name); /** * Get an array of {@link Integer} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Integer[] getIntegerArray(String name); /** * Get an array of {@link Boolean} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Boolean[] getBooleanArray(String name); /** * Get an array of {@link Short} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Short[] getShortArray(String name); /** * Get an array of {@link Long} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Long[] getLongArray(String name); /** * Get an array of {@link Float} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Float[] getFloatArray(String name); /** * Get an array of {@link Double} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Double[] getDoubleArray(String name); /** * Get an array of {@link String} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) String[] getStringArray(String name); /** * Get an array of {@link LocalDate} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) LocalDate[] getLocalDateArray(String name); /** * Get an array of {@link LocalTime} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) LocalTime[] getLocalTimeArray(String name); /** * Get an array of {@link OffsetTime} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) OffsetTime[] getOffsetTimeArray(String name); /** * Get an array of {@link LocalDateTime} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) LocalDateTime[] getLocalDateTimeArray(String name); /** * Get an array of {@link OffsetDateTime} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) OffsetDateTime[] getOffsetDateTimeArray(String name); /** * Get an array of {@link Buffer} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore Buffer[] getBufferArray(String name); /** * Get an array of {@link UUID} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) UUID[] getUUIDArray(String name); /** * Get an array of {@link Json} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore Json[] getJsonArray(String name); /** * Get an array of {@link Numeric} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Numeric[] getNumericArray(String name); /** * Get an array of {@link Point} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Point[] getPointArray(String name); /** * Get an array of {@link Line} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Line[] getLineArray(String name); /** * Get an array of {@link LineSegment} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) LineSegment[] getLineSegmentArray(String name); /** * Get an array of {@link Box} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Box[] getBoxArray(String name); /** * Get an array of {@link Path} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Path[] getPathArray(String name); /** * Get an array of {@link Polygon} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Polygon[] getPolygonArray(String name); /** * Get an array of {@link Circle} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Circle[] getCircleArray(String name); /** * Get an array of {@link Interval} value at {@code pos}. * * @param name the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Interval[] getIntervalArray(String name); } ================================================ FILE: src/main/java/io/reactiverse/pgclient/SslMode.java ================================================ /* * Copyright (C) 2018 Julien Viet * * Licensed 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 io.reactiverse.pgclient; /** * The different values for the sslmode parameter provide different levels of protection. * See more information in Protection Provided in Different Modes. */ public enum SslMode { /** * only try a non-SSL connection. */ DISABLE("disable"), /** * first try a non-SSL connection; if that fails, try an SSL connection. */ ALLOW("allow"), /** * first try an SSL connection; if that fails, try a non-SSL connection. */ PREFER("prefer"), /** * only try an SSL connection. If a root CA file is present, verify the certificate in the same way as if verify-ca was specified. */ REQUIRE("require"), /** * only try an SSL connection, and verify that the server certificate is issued by a trusted certificate authority (CA). */ VERIFY_CA("verify-ca"), /** * only try an SSL connection, verify that the server certificate is issued by a trusted CA and that the requested server host name matches that in the certificate. */ VERIFY_FULL("verify-full"); public static final SslMode[] VALUES = SslMode.values(); public final String value; SslMode(String value) { this.value = value; } public static SslMode of(String value) { for (SslMode sslMode : VALUES) { if (sslMode.value.equalsIgnoreCase(value)) { return sslMode; } } throw new IllegalArgumentException("Could not find an appropriate SSL mode for the value [" + value + "]."); } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/Tuple.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.reactiverse.pgclient.data.Box; import io.reactiverse.pgclient.data.Circle; import io.reactiverse.pgclient.data.Interval; import io.reactiverse.pgclient.data.Json; import io.reactiverse.pgclient.data.Line; import io.reactiverse.pgclient.data.LineSegment; import io.reactiverse.pgclient.data.Numeric; import io.reactiverse.pgclient.data.Path; import io.reactiverse.pgclient.data.Polygon; import io.reactiverse.pgclient.impl.ArrayTuple; import io.reactiverse.pgclient.data.Point; import io.vertx.codegen.annotations.Fluent; import io.vertx.codegen.annotations.GenIgnore; import io.vertx.codegen.annotations.VertxGen; import io.vertx.core.buffer.Buffer; import java.math.BigDecimal; import java.time.*; import java.time.temporal.Temporal; import java.util.UUID; /** * A general purpose tuple. */ @VertxGen public interface Tuple { /** * @return a new empty tuple */ static Tuple tuple() { return new ArrayTuple(10); } /** * Create a tuple of one element. * * @param elt1 the first value * @return the tuple */ static Tuple of(Object elt1) { ArrayTuple tuple = new ArrayTuple(1); tuple.addValue(elt1); return tuple; } /** * Create a tuple of two elements. * * @param elt1 the first value * @param elt2 the second value * @return the tuple */ static Tuple of(Object elt1, Object elt2) { ArrayTuple tuple = new ArrayTuple(2); tuple.addValue(elt1); tuple.addValue(elt2); return tuple; } /** * Create a tuple of three elements. * * @param elt1 the first value * @param elt2 the second value * @param elt3 the third value * @return the tuple */ static Tuple of(Object elt1, Object elt2, Object elt3) { ArrayTuple tuple = new ArrayTuple(3); tuple.addValue(elt1); tuple.addValue(elt2); tuple.addValue(elt3); return tuple; } /** * Create a tuple of four elements. * * @param elt1 the first value * @param elt2 the second value * @param elt3 the third value * @param elt4 the fourth value * @return the tuple */ static Tuple of(Object elt1, Object elt2, Object elt3, Object elt4) { ArrayTuple tuple = new ArrayTuple(4); tuple.addValue(elt1); tuple.addValue(elt2); tuple.addValue(elt3); tuple.addValue(elt4); return tuple; } /** * Create a tuple of five elements. * * @param elt1 the first value * @param elt2 the second value * @param elt3 the third value * @param elt4 the fourth value * @param elt5 the fifth value * @return the tuple */ static Tuple of(Object elt1, Object elt2, Object elt3, Object elt4, Object elt5) { ArrayTuple tuple = new ArrayTuple(5); tuple.addValue(elt1); tuple.addValue(elt2); tuple.addValue(elt3); tuple.addValue(elt4); tuple.addValue(elt5); return tuple; } /** * Create a tuple of six elements. * * @param elt1 the first value * @param elt2 the second valueg * @param elt3 the third value * @param elt4 the fourth value * @param elt5 the fifth value * @param elt6 the sixth value * @return the tuple */ static Tuple of(Object elt1, Object elt2, Object elt3, Object elt4, Object elt5, Object elt6) { ArrayTuple tuple = new ArrayTuple(5); tuple.addValue(elt1); tuple.addValue(elt2); tuple.addValue(elt3); tuple.addValue(elt4); tuple.addValue(elt5); tuple.addValue(elt6); return tuple; } /** * Create a tuple of an arbitrary number of elements. * * @param elt1 the first element * @param elts the remaining elements * @return the tuple */ @GenIgnore static Tuple of(Object elt1, Object... elts) { ArrayTuple tuple = new ArrayTuple(1 + elts.length); tuple.addValue(elt1); for (Object elt: elts) { tuple.addValue(elt); } return tuple; } /** * Get a boolean value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ Boolean getBoolean(int pos); /** * Get an object value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ Object getValue(int pos); /** * Get a short value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ Short getShort(int pos); /** * Get an integer value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ Integer getInteger(int pos); /** * Get a long value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ Long getLong(int pos); /** * Get a float value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ Float getFloat(int pos); /** * Get a double value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ Double getDouble(int pos); /** * Get a string value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ String getString(int pos); /** * Get a json value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ Json getJson(int pos); /** * Get a {@link java.time.temporal.Temporal} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Temporal getTemporal(int pos); /** * Get {@link java.time.LocalDate} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) LocalDate getLocalDate(int pos); /** * Get {@link java.time.LocalTime} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) LocalTime getLocalTime(int pos); /** * Get {@link java.time.LocalDateTime} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) LocalDateTime getLocalDateTime(int pos); /** * Get {@link java.time.OffsetTime} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) OffsetTime getOffsetTime(int pos); /** * Get {@link java.time.OffsetDateTime} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) OffsetDateTime getOffsetDateTime(int pos); /** * Get {@link java.util.UUID} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) UUID getUUID(int pos); /** * Get {@link BigDecimal} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) BigDecimal getBigDecimal(int pos); /** * Get an array of {@link Integer} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Integer[] getIntegerArray(int pos); /** * Get an array of {@link Boolean} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Boolean[] getBooleanArray(int pos); /** * Get an array of {@link Short} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Short[] getShortArray(int pos); /** * Get an array of {@link Long} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Long[] getLongArray(int pos); /** * Get an array of {@link Float} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Float[] getFloatArray(int pos); /** * Get an array of {@link Double} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Double[] getDoubleArray(int pos); /** * Get an array of {@link String} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) String[] getStringArray(int pos); /** * Get an array of {@link LocalDate} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) LocalDate[] getLocalDateArray(int pos); /** * Get an array of {@link LocalTime} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) LocalTime[] getLocalTimeArray(int pos); /** * Get an array of {@link OffsetTime} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) OffsetTime[] getOffsetTimeArray(int pos); /** * Get an array of {@link LocalDateTime} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) LocalDateTime[] getLocalDateTimeArray(int pos); /** * Get an array of {@link OffsetDateTime} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) OffsetDateTime[] getOffsetDateTimeArray(int pos); /** * Get an array of {@link Buffer} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ @GenIgnore Buffer[] getBufferArray(int pos); /** * Get an array of {@link UUID} value at {@code pos}. * * @param pos the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) UUID[] getUUIDArray(int pos); /** * Get an array of {@link Json} value at {@code pos}. * * @param pos the column * @return the value or {@code null} */ @GenIgnore Json[] getJsonArray(int pos); /** * Get an array of {@link Numeric} value at {@code pos}. * * @param pos the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Numeric[] getNumericArray(int pos); /** * Get an array of {@link Point} value at {@code pos}. * * @param pos the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Point[] getPointArray(int pos); /** * Get an array of {@link Line} value at {@code pos}. * * @param pos the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Line[] getLineArray(int pos); /** * Get an array of {@link LineSegment} value at {@code pos}. * * @param pos the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) LineSegment[] getLineSegmentArray(int pos); /** * Get an array of {@link Box} value at {@code pos}. * * @param pos the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Box[] getBoxArray(int pos); /** * Get an array of {@link Path} value at {@code pos}. * * @param pos the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Path[] getPathArray(int pos); /** * Get an array of {@link Polygon} value at {@code pos}. * * @param pos the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Polygon[] getPolygonArray(int pos); /** * Get an array of {@link Circle} value at {@code pos}. * * @param pos the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Circle[] getCircleArray(int pos); /** * Get an array of {@link Interval} value at {@code pos}. * * @param pos the column * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Interval[] getIntervalArray(int pos); /** * Get {@link Numeric} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Numeric getNumeric(int pos); /** * Get {@link Point} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ Point getPoint(int pos); /** * Get {@link Line} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ Line getLine(int pos); /** * Get {@link LineSegment} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ LineSegment getLineSegment(int pos); /** * Get {@link Box} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ Box getBox(int pos); /** * Get {@link Path} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ Path getPath(int pos); /** * Get {@link Polygon} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ Polygon getPolygon(int pos); /** * Get {@link Circle} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ Circle getCircle(int pos); /** * Get {@link Interval} value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ Interval getInterval(int pos); /** * Get a buffer value at {@code pos}. * * @param pos the position * @return the value or {@code null} */ Buffer getBuffer(int pos); /** * Add a boolean value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @Fluent Tuple addBoolean(Boolean value); /** * Add an object value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @Fluent Tuple addValue(Object value); /** * Add a short value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @Fluent Tuple addShort(Short value); /** * Add an integer value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @Fluent Tuple addInteger(Integer value); /** * Add a long value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @Fluent Tuple addLong(Long value); /** * Add a float value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @Fluent Tuple addFloat(Float value); /** * Add a double value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @Fluent Tuple addDouble(Double value); /** * Add a string value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @Fluent Tuple addString(String value); /** * Add a json value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @Fluent Tuple addJson(Json value); /** * Add a buffer value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @Fluent Tuple addBuffer(Buffer value); /** * Add a {@link java.time.temporal.Temporal} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addTemporal(Temporal value); /** * Add a {@link java.time.LocalDate} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addLocalDate(LocalDate value); /** * Add a {@link java.time.LocalTime} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addLocalTime(LocalTime value); /** * Add a {@link java.time.LocalDateTime} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addLocalDateTime(LocalDateTime value); /** * Add a {@link java.time.OffsetTime} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addOffsetTime(OffsetTime value); /** * Add a {@link java.time.OffsetDateTime} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addOffsetDateTime(OffsetDateTime value); /** * Add a {@link java.util.UUID} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addUUID(UUID value); /** * Add a {@link Numeric} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addNumeric(Numeric value); /** * Add a {@link BigDecimal} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addBigDecimal(BigDecimal value); /** * Add a {@link Point} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @Fluent Tuple addPoint(Point value); /** * Add a {@link Line} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @Fluent Tuple addLine(Line value); /** * Add a {@link LineSegment} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @Fluent Tuple addLineSegment(LineSegment value); /** * Add a {@link Box} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @Fluent Tuple addBox(Box value); /** * Add a {@link Path} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @Fluent Tuple addPath(Path value); /** * Add a {@link Polygon} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @Fluent Tuple addPolygon(Polygon value); /** * Add a {@link Circle} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @Fluent Tuple addCircle(Circle value); /** * Add a {@link Point} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @Fluent Tuple addInterval(Interval value); /** * Add an array of {@code Integer} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addIntegerArray(Integer[] value); /** * Add an array of {@code Boolean} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addBooleanArray(Boolean[] value); /** * Add an array of {@link Short} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addShortArray(Short[] value); /** * Add an array of {@link Long} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addLongArray(Long[] value); /** * Add an array of {@link Float} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addFloatArray(Float[] value); /** * Add an array of {@link Double} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addDoubleArray(Double[] value); /** * Add an array of {@link String} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addStringArray(String[] value); /** * Add an array of {@link LocalDate} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addLocalDateArray(LocalDate[] value); /** * Add an array of {@link LocalTime} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addLocalTimeArray(LocalTime[] value); /** * Add an array of {@link OffsetTime} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addOffsetTimeArray(OffsetTime[] value); /** * Add an array of {@link LocalDateTime} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addLocalDateTimeArray(LocalDateTime[] value); /** * Add an array of {@link OffsetDateTime} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addOffsetDateTimeArray(OffsetDateTime[] value); /** * Add an array of {@link Buffer} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore Tuple addBufferArray(Buffer[] value); /** * Add an array of {@link UUID} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addUUIDArray(UUID[] value); /** * Add an array of {@link Json} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore Tuple addJsonArray(Json[] value); /** * Add an array of {@link Numeric} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addNumericArray(Numeric[] value); /** * Add an array of {@link Point} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addPointArray(Point[] value); /** * Add an array of {@link io.reactiverse.pgclient.data.Line} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addLineArray(Line[] value); /** * Add an array of {@link LineSegment} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addLineSegmentArray(LineSegment[] value); /** * Add an array of {@link Box} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addBoxArray(Box[] value); /** * Add an array of {@link Path} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addPathArray(Path[] value); /** * Add an array of {@link Polygon} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addPolygonArray(Polygon[] value); /** * Add an array of {@link Circle} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addCircleArray(Circle[] value); /** * Add an array of {@link Interval} value at the end of the tuple. * * @param value the value * @return a reference to this, so the API can be used fluently */ @GenIgnore(GenIgnore.PERMITTED_TYPE) Tuple addIntervalArray(Interval[] value); /** * @return the tuple size */ int size(); void clear(); } ================================================ FILE: src/main/java/io/reactiverse/pgclient/data/Box.java ================================================ package io.reactiverse.pgclient.data; import io.vertx.codegen.annotations.DataObject; import io.vertx.core.json.JsonObject; /** * Rectangular box data type in Postgres represented by pairs of {@link Point}s that are opposite corners of the box. */ @DataObject(generateConverter = true) public class Box { private Point upperRightCorner, lowerLeftCorner; public Box() { this(new Point(), new Point()); } public Box(Point upperRightCorner, Point lowerLeftCorner) { this.upperRightCorner = upperRightCorner; this.lowerLeftCorner = lowerLeftCorner; } public Box(JsonObject json) { BoxConverter.fromJson(json, this); } public Point getUpperRightCorner() { return upperRightCorner; } public void setUpperRightCorner(Point upperRightCorner) { this.upperRightCorner = upperRightCorner; } public Point getLowerLeftCorner() { return lowerLeftCorner; } public void setLowerLeftCorner(Point lowerLeftCorner) { this.lowerLeftCorner = lowerLeftCorner; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Box box = (Box) o; if (!upperRightCorner.equals(box.upperRightCorner)) return false; if (!lowerLeftCorner.equals(box.lowerLeftCorner)) return false; return true; } @Override public int hashCode() { int result = upperRightCorner.hashCode(); result = 31 * result + lowerLeftCorner.hashCode(); return result; } @Override public String toString() { return "Box(" + upperRightCorner.toString() + "," + lowerLeftCorner.toString() + ")"; } public JsonObject toJson() { JsonObject json = new JsonObject(); BoxConverter.toJson(this, json); return json; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/data/Circle.java ================================================ package io.reactiverse.pgclient.data; import io.vertx.codegen.annotations.DataObject; import io.vertx.core.json.JsonObject; /** * Circle data type in Postgres represented by a center {@link Point} and radius. */ @DataObject(generateConverter = true) public class Circle { private Point centerPoint; private double radius; public Circle() { this(new Point(), 0.0); } public Circle(Point centerPoint, double radius) { this.centerPoint = centerPoint; this.radius = radius; } public Circle(JsonObject json) { CircleConverter.fromJson(json, this); } public Point getCenterPoint() { return centerPoint; } public void setCenterPoint(Point centerPoint) { this.centerPoint = centerPoint; } public double getRadius() { return radius; } public void setRadius(double radius) { this.radius = radius; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Circle that = (Circle) o; if (radius != that.radius) return false; if (!centerPoint.equals(that.centerPoint)) return false; return true; } @Override public int hashCode() { int result; long temp; result = centerPoint.hashCode(); temp = Double.doubleToLongBits(radius); result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public String toString() { return "Circle<" + centerPoint.toString() + "," + radius + ">"; } public JsonObject toJson() { JsonObject json = new JsonObject(); CircleConverter.toJson(this, json); return json; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/data/Interval.java ================================================ package io.reactiverse.pgclient.data; import io.vertx.codegen.annotations.DataObject; import io.vertx.core.json.JsonObject; /** * Postgres Interval is date and time based * such as 120 years 3 months 332 days 20 hours 20 minutes 20.999999 seconds * * @author Emad Alblueshi */ @DataObject(generateConverter = true) public class Interval { private int years, months, days, hours, minutes, seconds, microseconds; public Interval() { this(0, 0, 0, 0, 0, 0, 0); } public Interval(int years, int months, int days, int hours, int minutes, int seconds, int microseconds) { this.years = years; this.months = months; this.days = days; this.hours = hours; this.minutes = minutes; this.seconds = seconds; this.microseconds = microseconds; } public Interval(int years, int months, int days, int hours, int minutes, int seconds) { this(years, months, days, hours, minutes, seconds, 0); } public Interval(int years, int months, int days, int hours, int minutes) { this(years, months, days, hours, minutes, 0); } public Interval(int years, int months, int days, int hours) { this(years, months, days, hours, 0); } public Interval(int years, int months, int days) { this(years, months, days, 0); } public Interval(int years, int months) { this(years, months, 0); } public Interval(int years) { this(years, 0); } public Interval(JsonObject json) { IntervalConverter.fromJson(json, this); } public static Interval of() { return new Interval(); } public static Interval of(int years, int months, int days, int hours, int minutes, int seconds, int microseconds) { return new Interval(years, months, days, hours, minutes, seconds, microseconds); } public static Interval of(int years, int months, int days, int hours, int minutes, int seconds) { return new Interval(years, months, days, hours, minutes, seconds); } public static Interval of(int years, int months, int days, int hours, int minutes) { return new Interval(years, months, days, hours, minutes); } public static Interval of(int years, int months, int days, int hours) { return new Interval(years, months, days, hours); } public static Interval of(int years, int months, int days) { return new Interval(years, months, days); } public static Interval of(int years, int months) { return new Interval(years, months); } public static Interval of(int years) { return new Interval(years); } public Interval years(int years) { this.years = years; return this; } public Interval months(int months) { this.months = months; return this; } public Interval days(int days) { this.days = days; return this; } public Interval hours(int hours) { this.hours = hours; return this; } public Interval minutes(int minutes) { this.minutes = minutes; return this; } public Interval seconds(int seconds) { this.seconds = seconds; return this; } public Interval microseconds(int microseconds) { this.microseconds = microseconds; return this; } public int getYears() { return years; } public void setYears(int years) { this.years = years; } public int getMonths() { return months; } public void setMonths(int months) { this.months = months; } public int getDays() { return days; } public void setDays(int days) { this.days = days; } public int getHours() { return hours; } public void setHours(int hours) { this.hours = hours; } public int getMinutes() { return minutes; } public void setMinutes(int minutes) { this.minutes = minutes; } public int getSeconds() { return seconds; } public void setSeconds(int seconds) { this.seconds = seconds; } public int getMicroseconds() { return microseconds; } public void setMicroseconds(int microseconds) { this.microseconds = microseconds; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Interval interval = (Interval) o; return years == interval.years && months == interval.months && days == interval.days && hours == interval.hours && minutes == interval.minutes && seconds == interval.seconds && microseconds == interval.microseconds; } @Override public int hashCode() { int result = years; result = 31 * result + months; result = 31 * result + days; result = 31 * result + hours; result = 31 * result + minutes; result = 31 * result + seconds; result = 31 * result + microseconds; return result; } @Override public String toString() { return "Interval( " + years + " years " + months + " months " + days + " days " + hours + " hours " + minutes + " minutes " + seconds + (microseconds == 0 ? "" : "." + Math.abs(microseconds)) + " seconds )"; } public JsonObject toJson() { JsonObject json = new JsonObject(); IntervalConverter.toJson(this, json); return json; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/data/Json.java ================================================ /* * Copyright (C) 2018 Julien Viet * * Licensed 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 io.reactiverse.pgclient.data; import io.reactiverse.pgclient.impl.data.JsonImpl; import io.vertx.codegen.annotations.VertxGen; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; @VertxGen public interface Json { static Json create(Object value) { if (value == null) { return JsonImpl.NULL; } else if (value instanceof String || value instanceof Number || value instanceof JsonObject || value instanceof JsonArray || value instanceof Boolean) { return new JsonImpl(value); } else { throw new IllegalArgumentException("Invalid json value " + value + " with class " + value.getClass().getName()); } } Object value(); } ================================================ FILE: src/main/java/io/reactiverse/pgclient/data/Line.java ================================================ package io.reactiverse.pgclient.data; import io.vertx.codegen.annotations.DataObject; import io.vertx.core.json.JsonObject; /** * Line data type in Postgres represented by the linear equation Ax + By + C = 0, where A and B are not both zero. */ @DataObject(generateConverter = true) public class Line { private double a; private double b; private double c; public Line() { this(0.0, 0.0, 0.0); } public Line(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } public Line(JsonObject json) { LineConverter.fromJson(json, this); } public double getA() { return a; } public void setA(double a) { this.a = a; } public double getB() { return b; } public void setB(double b) { this.b = b; } public double getC() { return c; } public void setC(double c) { this.c = c; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Line that = (Line) o; if (a != that.a) return false; if (b != that.b) return false; if (c != that.c) return false; return true; } @Override public int hashCode() { int result; long temp; temp = Double.doubleToLongBits(a); result = (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(b); result = 31 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(c); result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public String toString() { return "Line{" + a + "," + b + "," + c + "}"; } public JsonObject toJson() { JsonObject json = new JsonObject(); LineConverter.toJson(this, json); return json; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/data/LineSegment.java ================================================ package io.reactiverse.pgclient.data; import io.vertx.codegen.annotations.DataObject; import io.vertx.core.json.JsonObject; /** * Finite line segment data type in Postgres represented by pairs of {@link Point}s that are the endpoints of the segment. */ @DataObject(generateConverter = true) public class LineSegment { private Point p1, p2; public LineSegment() { this(new Point(), new Point()); } public LineSegment(Point p1, Point p2) { this.p1 = p1; this.p2 = p2; } public LineSegment(JsonObject json) { LineSegmentConverter.fromJson(json, this); } public Point getP1() { return p1; } public void setP1(Point p1) { this.p1 = p1; } public Point getP2() { return p2; } public void setP2(Point p2) { this.p2 = p2; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LineSegment that = (LineSegment) o; if (!p1.equals(that.p1)) return false; if (!p2.equals(that.p2)) return false; return true; } @Override public int hashCode() { int result = p1.hashCode(); result = 31 * result + p2.hashCode(); return result; } @Override public String toString() { return "LineSegment[" + p1.toString() + "," + p2.toString() + "]"; } public JsonObject toJson() { JsonObject json = new JsonObject(); LineSegmentConverter.toJson(this, json); return json; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/data/Numeric.java ================================================ /* * Copyright (C) 2018 Julien Viet * * Licensed 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 io.reactiverse.pgclient.data; import java.math.BigDecimal; import java.math.BigInteger; /** * The Postgres NUMERIC type. */ public final class Numeric extends Number { /** * Constant for the {@code NaN} value. */ public static final Numeric NaN = new Numeric(Double.NaN); private final Number value; /** * Return a {@code Numeric} instance for the given {@code number}. *

        * Null values or infinite {@code Double} or {@code Float} are rejected. * * @param number the number * @return the {@code Numeric} value * @throws NumberFormatException when the number is infinite */ public static Numeric create(Number number) { if (number == null) { throw new NullPointerException(); } if (number instanceof Double && ((Double)number).isInfinite() || number instanceof Float && ((Float)number).isInfinite()) { throw new NumberFormatException("Infinite numbers are not valid numerics"); } return new Numeric(number); } /** * Parse and return a {@code Numeric} instance for the given {@code s}. *

        * The string {@code "Nan"} will return the {@link #NaN} instance. * * @param s the string * @return the {@code Numeric} value */ public static Numeric parse(String s) { switch (s) { case "NaN": return NaN; default: return new Numeric(new BigDecimal(s)); } } private Numeric(Number value) { this.value = value; } @Override public short shortValue() { return value.shortValue(); } @Override public int intValue() { return value.intValue(); } @Override public long longValue() { return value.longValue(); } @Override public float floatValue() { return value.floatValue(); } @Override public double doubleValue() { return value.doubleValue(); } /** * @return {@code true} when this number represents {@code NaN} */ public boolean isNaN() { return value instanceof Double && ((Double)value).isNaN() || value instanceof Float && ((Float)value).isNaN(); } /** * @return the numeric value represented by this object after conversion * to type {@code BigDecimal}. It can be {@code null} when this instance * represents the {@code NaN} value. */ public BigDecimal bigDecimalValue() { if (value instanceof BigDecimal) { return (BigDecimal) value; } else if (value instanceof BigInteger) { return new BigDecimal((BigInteger)value); } else if (isNaN()) { return null; } else { return new BigDecimal(value.toString()); } } /** * @return the numeric value represented by this object after conversion * to type {@code BigInteger}. It can be {@code null} when this instance * represents the {@code NaN} value. */ public BigInteger bigIntegerValue() { if (value instanceof BigInteger) { return (BigInteger) value; } else if (value instanceof BigDecimal) { return ((BigDecimal)value).toBigInteger(); } else if (isNaN()) { return null; } else { return new BigInteger(Long.toString(value.longValue())); } } @Override public boolean equals(Object obj) { if (obj instanceof Numeric) { Numeric that = (Numeric) obj; if (value.getClass() == that.value.getClass()) { return value.equals(that.value); } else { BigDecimal l = bigDecimalValue(); BigDecimal r = that.bigDecimalValue(); if (l == null) { return r == null; } else if (r == null) { return false; } return l.compareTo(r) == 0; } } return false; } @Override public int hashCode() { return intValue(); } @Override public String toString() { return value.toString(); } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/data/Path.java ================================================ package io.reactiverse.pgclient.data; import io.vertx.codegen.annotations.DataObject; import io.vertx.core.json.JsonObject; import java.util.ArrayList; import java.util.List; /** * Path data type in Postgres represented by lists of connected points. * Paths can be open, where the first and last points in the list are considered not connected, * or closed, where the first and last points are considered connected. */ @DataObject(generateConverter = true) public class Path { private boolean isOpen; private List points; public Path() { this(false, new ArrayList<>()); } public Path(boolean isOpen, List points) { this.isOpen = isOpen; this.points = points; } public Path(JsonObject json) { PathConverter.fromJson(json, this); } public boolean isOpen() { return isOpen; } public void setOpen(boolean open) { isOpen = open; } public List getPoints() { return points; } public void setPoints(List points) { this.points = points; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Path path = (Path) o; if (isOpen != path.isOpen) return false; return points.equals(path.points); } @Override public int hashCode() { int result = (isOpen ? 1 : 0); result = 31 * result + points.hashCode(); return result; } @Override public String toString() { String left; String right; if (isOpen) { left = "["; right = "]"; } else { left = "("; right = ")"; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Path"); stringBuilder.append(left); for (int i = 0; i < points.size(); i++) { Point point = points.get(i); stringBuilder.append(point.toString()); if (i != points.size() - 1) { // not the last one stringBuilder.append(","); } } stringBuilder.append(right); return stringBuilder.toString(); } public JsonObject toJson() { JsonObject json = new JsonObject(); PathConverter.toJson(this, json); return json; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/data/Point.java ================================================ /* * Copyright (C) 2018 Julien Viet * * Licensed 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 io.reactiverse.pgclient.data; import io.vertx.codegen.annotations.DataObject; import io.vertx.core.json.JsonObject; /** * A Postgresql point. */ @DataObject(generateConverter = true) public class Point { public double x, y; public Point() { this(0, 0); } public Point(double x, double y) { this.x = x; this.y = y; } public Point(JsonObject json) { PointConverter.fromJson(json, this); } public double getX() { return x; } public Point setX(double x) { this.x = x; return this; } public double getY() { return y; } public Point setY(double y) { this.y = y; return this; } @Override public boolean equals(Object obj) { if (obj instanceof Point) { Point that = (Point) obj; return x == that.x && y == that.y; } return false; } @Override public String toString() { return "Point(" + x + "," + y + ")"; } public JsonObject toJson() { JsonObject json = new JsonObject(); PointConverter.toJson(this, json); return json; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/data/Polygon.java ================================================ package io.reactiverse.pgclient.data; import io.vertx.codegen.annotations.DataObject; import io.vertx.core.json.JsonObject; import java.util.ArrayList; import java.util.List; /** * Polygon data type in Postgres represented by lists of points (the vertexes of the polygon). * Polygons are very similar to closed paths, but are stored differently and have their own set of support routines. */ @DataObject(generateConverter = true) public class Polygon { private List points; public Polygon() { this(new ArrayList<>()); } public Polygon(List points) { this.points = points; } public Polygon(JsonObject json) { PolygonConverter.fromJson(json, this); } public List getPoints() { return points; } public void setPoints(List points) { this.points = points; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Polygon polygon = (Polygon) o; return points.equals(polygon.points); } @Override public int hashCode() { return points.hashCode(); } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Polygon"); stringBuilder.append("("); for (int i = 0; i < points.size(); i++) { Point point = points.get(i); stringBuilder.append(point.toString()); if (i != points.size() - 1) { // not the last one stringBuilder.append(","); } } stringBuilder.append(")"); return stringBuilder.toString(); } public JsonObject toJson() { JsonObject json = new JsonObject(); PolygonConverter.toJson(this, json); return json; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/ArrayTuple.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.data.Box; import io.reactiverse.pgclient.data.Circle; import io.reactiverse.pgclient.data.Json; import io.reactiverse.pgclient.data.Line; import io.reactiverse.pgclient.data.LineSegment; import io.reactiverse.pgclient.data.Numeric; import io.reactiverse.pgclient.Tuple; import io.reactiverse.pgclient.data.Interval; import io.reactiverse.pgclient.data.Path; import io.reactiverse.pgclient.data.Point; import io.reactiverse.pgclient.data.Polygon; import io.vertx.core.buffer.Buffer; import java.math.BigDecimal; import java.time.*; import java.time.temporal.Temporal; import java.util.ArrayList; import java.util.Collection; import java.util.UUID; public class ArrayTuple extends ArrayList implements Tuple { public static Tuple EMPTY = new ArrayTuple(0); public ArrayTuple(int len) { super(len); } public ArrayTuple(Collection c) { super(c); } @Override public Boolean getBoolean(int pos) { Object val = get(pos); if (val instanceof Boolean) { return (Boolean) val; } return null; } @Override public Object getValue(int pos) { return get(pos); } @Override public Short getShort(int pos) { Object val = get(pos); if (val instanceof Short) { return (Short) val; } else if (val instanceof Number) { return ((Number) val).shortValue(); } return null; } @Override public Integer getInteger(int pos) { Object val = get(pos); if (val instanceof Integer) { return (Integer) val; } else if (val instanceof Number) { return ((Number) val).intValue(); } return null; } @Override public Long getLong(int pos) { Object val = get(pos); if (val instanceof Long) { return (Long) val; } else if (val instanceof Number) { return ((Number) val).longValue(); } return null; } @Override public Float getFloat(int pos) { Object val = get(pos); if (val instanceof Float) { return (Float) val; } else if (val instanceof Number) { return ((Number) val).floatValue(); } return null; } @Override public Double getDouble(int pos) { Object val = get(pos); if (val instanceof Double) { return (Double) val; } else if (val instanceof Number) { return ((Number) val).doubleValue(); } return null; } @Override public BigDecimal getBigDecimal(int pos) { Object val = get(pos); if (val instanceof BigDecimal) { return (BigDecimal) val; } else if (val instanceof Number) { return new BigDecimal(val.toString()); } return null; } @Override public Numeric getNumeric(int pos) { Object val = get(pos); if (val instanceof Numeric) { return (Numeric) val; } else if (val instanceof Number) { return Numeric.parse(val.toString()); } return null; } @Override public Point getPoint(int pos) { Object val = get(pos); if (val instanceof Point) { return (Point) val; } else { return null; } } @Override public Line getLine(int pos) { Object val = get(pos); if (val instanceof Line) { return (Line) val; } else { return null; } } @Override public LineSegment getLineSegment(int pos) { Object val = get(pos); if (val instanceof LineSegment) { return (LineSegment) val; } else { return null; } } @Override public Box getBox(int pos) { Object val = get(pos); if (val instanceof Box) { return (Box) val; } else { return null; } } @Override public Path getPath(int pos) { Object val = get(pos); if (val instanceof Path) { return (Path) val; } else { return null; } } @Override public Polygon getPolygon(int pos) { Object val = get(pos); if (val instanceof Polygon) { return (Polygon) val; } else { return null; } } @Override public Circle getCircle(int pos) { Object val = get(pos); if (val instanceof Circle) { return (Circle) val; } else { return null; } } @Override public Interval getInterval(int pos) { Object val = get(pos); if (val instanceof Interval) { return (Interval) val; } else { return null; } } @Override public Integer[] getIntegerArray(int pos) { Object val = get(pos); if (val instanceof Integer[]) { return (Integer[]) val; } else { return null; } } @Override public Boolean[] getBooleanArray(int pos) { Object val = get(pos); if (val instanceof Boolean[]) { return (Boolean[]) val; } else { return null; } } @Override public Short[] getShortArray(int pos) { Object val = get(pos); if (val instanceof Short[]) { return (Short[]) val; } else { return null; } } @Override public Long[] getLongArray(int pos) { Object val = get(pos); if (val instanceof Long[]) { return (Long[]) val; } else { return null; } } @Override public Float[] getFloatArray(int pos) { Object val = get(pos); if (val instanceof Float[]) { return (Float[]) val; } else { return null; } } @Override public Double[] getDoubleArray(int pos) { Object val = get(pos); if (val instanceof Double[]) { return (Double[]) val; } else { return null; } } @Override public String[] getStringArray(int pos) { Object val = get(pos); if (val instanceof String[]) { return (String[]) val; } else { return null; } } @Override public LocalDate[] getLocalDateArray(int pos) { Object val = get(pos); if (val instanceof LocalDate[]) { return (LocalDate[]) val; } else { return null; } } @Override public LocalTime[] getLocalTimeArray(int pos) { Object val = get(pos); if (val instanceof LocalTime[]) { return (LocalTime[]) val; } else { return null; } } @Override public OffsetTime[] getOffsetTimeArray(int pos) { Object val = get(pos); if (val instanceof OffsetTime[]) { return (OffsetTime[]) val; } else { return null; } } @Override public LocalDateTime[] getLocalDateTimeArray(int pos) { Object val = get(pos); if (val instanceof LocalDateTime[]) { return (LocalDateTime[]) val; } else { return null; } } @Override public OffsetDateTime[] getOffsetDateTimeArray(int pos) { Object val = get(pos); if (val instanceof OffsetDateTime[]) { return (OffsetDateTime[]) val; } else { return null; } } @Override public Buffer[] getBufferArray(int pos) { Object val = get(pos); if (val instanceof Buffer[]) { return (Buffer[]) val; } else { return null; } } @Override public UUID[] getUUIDArray(int pos) { Object val = get(pos); if (val instanceof UUID[]) { return (UUID[]) val; } else { return null; } } @Override public Json[] getJsonArray(int pos) { Object val = get(pos); if (val instanceof Json[]) { return (Json[]) val; } else { return null; } } @Override public Numeric[] getNumericArray(int pos) { Object val = get(pos); if (val instanceof Numeric[]) { return (Numeric[]) val; } else { return null; } } @Override public Point[] getPointArray(int pos) { Object val = get(pos); if (val instanceof Point[]) { return (Point[]) val; } else { return null; } } @Override public Line[] getLineArray(int pos) { Object val = get(pos); if (val instanceof Line[]) { return (Line[]) val; } else { return null; } } @Override public LineSegment[] getLineSegmentArray(int pos) { Object val = get(pos); if (val instanceof LineSegment[]) { return (LineSegment[]) val; } else { return null; } } @Override public Box[] getBoxArray(int pos) { Object val = get(pos); if (val instanceof Box[]) { return (Box[]) val; } else { return null; } } @Override public Path[] getPathArray(int pos) { Object val = get(pos); if (val instanceof Path[]) { return (Path[]) val; } else { return null; } } @Override public Polygon[] getPolygonArray(int pos) { Object val = get(pos); if (val instanceof Polygon[]) { return (Polygon[]) val; } else { return null; } } @Override public Circle[] getCircleArray(int pos) { Object val = get(pos); if (val instanceof Circle[]) { return (Circle[]) val; } else { return null; } } @Override public Interval[] getIntervalArray(int pos) { Object val = get(pos); if (val instanceof Interval[]) { return (Interval[]) val; } else { return null; } } @Override public String getString(int pos) { Object val = get(pos); if (val instanceof String) { return (String) val; } return null; } @Override public Json getJson(int pos) { Object val = get(pos); if (val instanceof Json) { return (Json) val; } return null; } @Override public Buffer getBuffer(int pos) { Object val = get(pos); if (val instanceof Buffer) { return (Buffer) val; } return null; } @Override public Temporal getTemporal(int pos) { Object val = get(pos); if (val instanceof Temporal) { return (Temporal) val; } return null; } @Override public LocalDate getLocalDate(int pos) { Object val = get(pos); if (val instanceof LocalDate) { return (LocalDate) val; } return null; } @Override public LocalTime getLocalTime(int pos) { Object val = get(pos); if (val instanceof LocalTime) { return (LocalTime) val; } return null; } @Override public LocalDateTime getLocalDateTime(int pos) { Object val = get(pos); if (val instanceof LocalDateTime) { return (LocalDateTime) val; } return null; } @Override public OffsetTime getOffsetTime(int pos) { Object val = get(pos); if (val instanceof OffsetTime) { return (OffsetTime) val; } return null; } @Override public OffsetDateTime getOffsetDateTime(int pos) { Object val = get(pos); if (val instanceof OffsetDateTime) { return (OffsetDateTime) val; } return null; } @Override public UUID getUUID(int pos) { Object val = get(pos); if (val instanceof UUID) { return (UUID) val; } return null; } @Override public Tuple addBoolean(Boolean value) { add(value); return this; } @Override public Tuple addValue(Object value) { if(value instanceof Boolean || value instanceof Number || value instanceof String || value instanceof Buffer || value instanceof LocalTime || value instanceof OffsetTime || value instanceof LocalDate || value instanceof LocalDateTime || value instanceof OffsetDateTime || value instanceof UUID || value instanceof Json || value instanceof Point || value instanceof Line || value instanceof LineSegment || value instanceof Box || value instanceof Path || value instanceof Polygon || value instanceof Circle || value instanceof Interval || value instanceof Boolean[] || value instanceof Number[] || value instanceof String[] || value instanceof LocalDate[] || value instanceof LocalTime[] || value instanceof OffsetTime[] || value instanceof LocalDateTime[] || value instanceof OffsetDateTime[] || value instanceof UUID[] || value instanceof Json[] || value instanceof Point[] || value instanceof Line[] || value instanceof LineSegment[] || value instanceof Box[] || value instanceof Path[] || value instanceof Polygon[] || value instanceof Circle[] || value instanceof Interval[] || value instanceof Buffer[]) { add(value); } else { add(null); } return this; } @Override public Tuple addShort(Short value) { add(value); return this; } @Override public Tuple addInteger(Integer value) { add(value); return this; } @Override public Tuple addLong(Long value) { add(value); return this; } @Override public Tuple addFloat(Float value) { add(value); return this; } @Override public Tuple addDouble(Double value) { add(value); return this; } @Override public Tuple addString(String value) { add(value); return this; } @Override public Tuple addJson(Json value) { add(value); return this; } @Override public Tuple addBuffer(Buffer value) { add(value); return this; } @Override public Tuple addTemporal(Temporal value) { add(value); return this; } @Override public Tuple addLocalDate(LocalDate value) { add(value); return this; } @Override public Tuple addLocalTime(LocalTime value) { add(value); return this; } @Override public Tuple addLocalDateTime(LocalDateTime value) { add(value); return this; } @Override public Tuple addOffsetTime(OffsetTime value) { add(value); return this; } @Override public Tuple addOffsetDateTime(OffsetDateTime value) { add(value); return this; } @Override public Tuple addUUID(UUID value) { add(value); return this; } @Override public Tuple addBigDecimal(BigDecimal value) { add(value); return this; } @Override public Tuple addPoint(Point value) { add(value); return this; } @Override public Tuple addLine(Line value) { add(value); return this; } @Override public Tuple addLineSegment(LineSegment value) { add(value); return this; } @Override public Tuple addBox(Box value) { add(value); return this; } @Override public Tuple addPath(Path value) { add(value); return this; } @Override public Tuple addPolygon(Polygon value) { add(value); return this; } @Override public Tuple addCircle(Circle value) { add(value); return this; } @Override public Tuple addInterval(Interval value) { add(value); return this; } @Override public Tuple addNumeric(Numeric value) { add(value); return this; } @Override public Tuple addNumericArray(Numeric[] value) { add(value); return this; } @Override public Tuple addPointArray(Point[] value) { add(value); return this; } @Override public Tuple addLineArray(Line[] value) { add(value); return this; } @Override public Tuple addLineSegmentArray(LineSegment[] value) { add(value); return this; } @Override public Tuple addBoxArray(Box[] value) { add(value); return this; } @Override public Tuple addPathArray(Path[] value) { add(value); return this; } @Override public Tuple addPolygonArray(Polygon[] value) { add(value); return this; } @Override public Tuple addCircleArray(Circle[] value) { add(value); return this; } @Override public Tuple addIntervalArray(Interval[] value) { add(value); return this; } @Override public Tuple addIntegerArray(Integer[] value) { add(value); return this; } @Override public Tuple addBooleanArray(Boolean[] value) { add(value); return this; } @Override public Tuple addShortArray(Short[] value) { add(value); return this; } @Override public Tuple addLongArray(Long[] value) { add(value); return this; } @Override public Tuple addFloatArray(Float[] value) { add(value); return this; } @Override public Tuple addDoubleArray(Double[] value) { add(value); return this; } @Override public Tuple addStringArray(String[] value) { add(value); return this; } @Override public Tuple addLocalDateArray(LocalDate[] value) { add(value); return this; } @Override public Tuple addLocalTimeArray(LocalTime[] value) { add(value); return this; } @Override public Tuple addOffsetTimeArray(OffsetTime[] value) { add(value); return this; } @Override public Tuple addLocalDateTimeArray(LocalDateTime[] value) { add(value); return this; } @Override public Tuple addOffsetDateTimeArray(OffsetDateTime[] value) { add(value); return this; } @Override public Tuple addBufferArray(Buffer[] value) { add(value); return this; } @Override public Tuple addUUIDArray(UUID[] value) { add(value); return this; } @Override public Tuple addJsonArray(Json[] value) { add(value); return this; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/CloseConnectionCommand.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.impl.codec.encoder.MessageEncoder; class CloseConnectionCommand extends CommandBase { static final CloseConnectionCommand INSTANCE = new CloseConnectionCommand(); private CloseConnectionCommand() { handler = ar -> {}; } @Override void exec(MessageEncoder out) { out.writeTerminate(); } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/ClosePortalCommand.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.impl.codec.encoder.MessageEncoder; import io.vertx.core.Handler; /** * @author Julien Viet */ class ClosePortalCommand extends CommandBase { private final String portal; ClosePortalCommand(String portal) { this.portal = portal; } @Override void exec(MessageEncoder out) { out.writeClosePortal(portal); out.writeSync(); } @Override public void handleCloseComplete() { // Expected } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/CloseStatementCommand.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.impl.codec.encoder.MessageEncoder; /** * @author Julien Viet */ class CloseStatementCommand extends CommandBase { @Override void exec(MessageEncoder out) { /* if (conn.psCache == null) { conn.writeMessage(new Close().setStatement(statement)); conn.writeMessage(Sync.INSTANCE); } else { } */ CommandResponse resp = CommandResponse.success(null); completionHandler.handle(resp); } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/CommandBase.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.impl.codec.TxStatus; import io.reactiverse.pgclient.impl.codec.decoder.ErrorResponse; import io.reactiverse.pgclient.impl.codec.decoder.NoticeResponse; import io.reactiverse.pgclient.impl.codec.decoder.ParameterDescription; import io.reactiverse.pgclient.impl.codec.decoder.RowDescription; import io.reactiverse.pgclient.impl.codec.encoder.MessageEncoder; import io.vertx.core.Handler; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; /** * @author Julien Viet */ public abstract class CommandBase { private static final Logger logger = LoggerFactory.getLogger(CommandBase.class); public Handler> completionHandler; public Handler noticeHandler; Handler> handler; Throwable failure; R result; public void handleBackendKeyData(int processId, int secretKey) { logger.warn(getClass().getSimpleName() + " should handle message BackendKeyData"); } public void handleEmptyQueryResponse() { logger.warn(getClass().getSimpleName() + " should handle message EmptyQueryResponse"); } public void handleParameterDescription(ParameterDescription parameterDesc) { logger.warn(getClass().getSimpleName() + " should handle message " + parameterDesc); } public void handleParseComplete() { logger.warn(getClass().getSimpleName() + " should handle message ParseComplete"); } public void handleCloseComplete() { logger.warn(getClass().getSimpleName() + " should handle message CloseComplete"); } public void handleRowDescription(RowDescription rowDescription) { logger.warn(getClass().getSimpleName() + " should handle message " + rowDescription); } public void handleNoData() { logger.warn(getClass().getSimpleName() + " should handle message NoData"); } public void handleNoticeResponse(NoticeResponse noticeResponse) { noticeHandler.handle(noticeResponse); } public void handleErrorResponse(ErrorResponse errorResponse) { logger.warn(getClass().getSimpleName() + " should handle message " + errorResponse); } public void handlePortalSuspended() { logger.warn(getClass().getSimpleName() + " should handle message PortalSuspended"); } public void handleBindComplete() { logger.warn(getClass().getSimpleName() + " should handle message BindComplete"); } public void handleCommandComplete(int updated) { logger.warn(getClass().getSimpleName() + " should handle message CommandComplete"); } public void handleAuthenticationMD5Password(byte[] salt) { logger.warn(getClass().getSimpleName() + " should handle message AuthenticationMD5Password"); } public void handleAuthenticationClearTextPassword() { logger.warn(getClass().getSimpleName() + " should handle message AuthenticationClearTextPassword"); } public void handleAuthenticationOk() { logger.warn(getClass().getSimpleName() + " should handle message AuthenticationOk"); } public void handleParameterStatus(String key, String value) { logger.warn(getClass().getSimpleName() + " should handle message ParameterStatus"); } /** *

        * The frontend can issue commands. Every message returned from the backend has transaction status * that would be one of the following *

        * IDLE : Not in a transaction block *

        * ACTIVE : In transaction block *

        * FAILED : Failed transaction block (queries will be rejected until block is ended) */ public void handleReadyForQuery(TxStatus txStatus) { CommandResponse resp; if (failure != null) { resp = CommandResponse.failure(this.failure, txStatus); } else { resp = CommandResponse.success(result, txStatus); } completionHandler.handle(resp); } abstract void exec(MessageEncoder out); final void fail(Throwable err) { handler.handle(CommandResponse.failure(err)); } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/CommandResponse.java ================================================ package io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.impl.codec.TxStatus; import io.vertx.core.AsyncResult; import io.vertx.core.impl.NoStackTraceThrowable; public abstract class CommandResponse implements AsyncResult { static CommandResponse failure(String msg) { return failure(new NoStackTraceThrowable(msg), null); } static CommandResponse failure(String msg, TxStatus txStatus) { return failure(new NoStackTraceThrowable(msg), txStatus); } static CommandResponse failure(Throwable cause) { return failure(cause, null); } static CommandResponse failure(Throwable cause, TxStatus txStatus) { return new CommandResponse(txStatus) { @Override public R result() { return null; } @Override public Throwable cause() { return cause; } @Override public boolean succeeded() { return false; } @Override public boolean failed() { return true; } }; } static CommandResponse success(R result) { return success(result, null); } static CommandResponse success(R result, TxStatus txStatus) { return new CommandResponse(txStatus) { @Override public R result() { return result; } @Override public Throwable cause() { return null; } @Override public boolean succeeded() { return true; } @Override public boolean failed() { return false; } }; } // The connection that executed the command CommandScheduler scheduler; private final TxStatus txStatus; public CommandResponse(TxStatus txStatus) { this.txStatus = txStatus; } TxStatus txStatus() { return txStatus; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/CommandScheduler.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.vertx.core.Handler; @FunctionalInterface interface CommandScheduler { void schedule(CommandBase cmd, Handler> handler); } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/Connection.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; public interface Connection { void init(Holder holder); boolean isSsl(); void schedule(CommandBase cmd); void close(Holder holder); int getProcessId(); int getSecretKey(); interface Holder { Connection connection(); void handleNotification(int processId, String channel, String payload); void handleClosed(); void handleException(Throwable err); } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/ConnectionPool.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.PgException; import io.reactiverse.pgclient.PgPoolOptions; import io.vertx.core.*; import io.vertx.core.impl.NoStackTraceThrowable; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import java.util.function.Consumer; /** * @author Julien Viet */ public class ConnectionPool { private final Consumer>> connector; private final int maxSize; private final ArrayDeque> waiters = new ArrayDeque<>(); private final Set all = new HashSet<>(); private final ArrayDeque available = new ArrayDeque<>(); private int size; private final int maxWaitQueueSize; private boolean checkInProgress; private boolean closed; public ConnectionPool(Consumer>> connector) { this(connector, PgPoolOptions.DEFAULT_MAX_SIZE, PgPoolOptions.DEFAULT_MAX_WAIT_QUEUE_SIZE); } public ConnectionPool(Consumer>> connector, int maxSize) { this(connector, maxSize, PgPoolOptions.DEFAULT_MAX_WAIT_QUEUE_SIZE); } public ConnectionPool(Consumer>> connector, int maxSize, int maxWaitQueueSize) { this.maxSize = maxSize; this.maxWaitQueueSize = maxWaitQueueSize; this.connector = connector; } public int available() { return available.size(); } public int size() { return size; } public void acquire(Handler> holder) { if (closed) { throw new IllegalStateException("Connection pool closed"); } waiters.add(Future.future().setHandler(holder)); check(); } public void close() { if (closed) { throw new IllegalStateException("Connection pool already closed"); } closed = true; for (PooledConnection pooled : new ArrayList<>(all)) { pooled.close(); } Future failure = Future.failedFuture("Connection pool close"); for (Future pending : waiters) { try { pending.handle(failure); } catch (Exception ignore) { } } } private class PooledConnection implements Connection, Connection.Holder { private final Connection conn; private Holder holder; PooledConnection(Connection conn) { this.conn = conn; } @Override public Connection connection() { return this; } @Override public boolean isSsl() { return conn.isSsl(); } @Override public void schedule(CommandBase cmd) { conn.schedule(cmd); } /** * Close the underlying connection */ private void close() { conn.close(this); } @Override public void init(Holder holder) { if (this.holder != null) { throw new IllegalStateException(); } this.holder = holder; } @Override public void close(Holder holder) { if (holder != this.holder) { throw new IllegalStateException(); } this.holder = null; release(this); } @Override public void handleClosed() { if (all.remove(this)) { size--; if (holder == null) { available.remove(this); } else { holder.handleClosed(); } check(); } else { throw new IllegalStateException(); } } @Override public void handleNotification(int processId, String channel, String payload) { if (holder != null) { holder.handleNotification(processId, channel, payload); } } @Override public void handleException(Throwable err) { if (holder != null) { holder.handleException(err); } } @Override public int getProcessId() { return conn.getProcessId(); } @Override public int getSecretKey() { return conn.getSecretKey(); } } private void release(PooledConnection proxy) { if (all.contains(proxy)) { available.add(proxy); check(); } } private void check() { if (closed) { return; } if (!checkInProgress) { checkInProgress = true; try { while (waiters.size() > 0) { if (available.size() > 0) { PooledConnection proxy = available.poll(); Future waiter = waiters.poll(); waiter.complete(proxy); } else { if (size < maxSize) { Future waiter = waiters.poll(); size++; connector.accept(ar -> { if (ar.succeeded()) { Connection conn = ar.result(); PooledConnection proxy = new PooledConnection(conn); all.add(proxy); conn.init(proxy); waiter.complete(proxy); } else { size--; waiter.fail(ar.cause()); check(); } }); } else { if (maxWaitQueueSize >= 0) { int numInProgress = size - all.size(); int numToFail = waiters.size() - (maxWaitQueueSize + numInProgress); while (numToFail-- > 0) { Future waiter = waiters.pollLast(); waiter.fail(new NoStackTraceThrowable("Max waiter size reached")); } } break; } } } } finally { checkInProgress = false; } } } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/ExtendedBatchQueryCommand.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.Tuple; import io.reactiverse.pgclient.impl.codec.encoder.MessageEncoder; import io.reactiverse.pgclient.impl.codec.encoder.Parse; import java.util.List; import java.util.stream.Collector; public class ExtendedBatchQueryCommand extends ExtendedQueryCommandBase { private final List params; ExtendedBatchQueryCommand(PreparedStatement ps, List params, boolean singleton, Collector collector, QueryResultHandler resultHandler) { this(ps, params, 0, null, false, singleton, collector, resultHandler); } private ExtendedBatchQueryCommand(PreparedStatement ps, List params, int fetch, String portal, boolean suspended, boolean singleton, Collector collector, QueryResultHandler resultHandler) { super(ps, fetch, portal, suspended, singleton, collector, resultHandler); this.params = params; } @Override void exec(MessageEncoder out) { if (suspended) { out.writeExecute(portal, fetch); out.writeSync(); } else { if (ps.bind.statement == 0) { out.writeParse(new Parse(ps.sql)); } if (params.isEmpty()) { // We set suspended to false as we won't get a command complete command back from Postgres result = false; } else { for (Tuple param : params) { out.writeBind(ps.bind, portal, (List) param); out.writeExecute(portal, fetch); } } out.writeSync(); } } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/ExtendedQueryCommand.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.Tuple; import io.reactiverse.pgclient.impl.codec.encoder.MessageEncoder; import io.reactiverse.pgclient.impl.codec.encoder.Parse; import java.util.List; import java.util.stream.Collector; public class ExtendedQueryCommand extends ExtendedQueryCommandBase { private final Tuple params; ExtendedQueryCommand(PreparedStatement ps, Tuple params, boolean singleton, Collector collector, QueryResultHandler resultHandler) { this(ps, params, 0, null, false, singleton, collector, resultHandler); } ExtendedQueryCommand(PreparedStatement ps, Tuple params, int fetch, String portal, boolean suspended, boolean singleton, Collector collector, QueryResultHandler resultHandler) { super(ps, fetch, portal, suspended, singleton, collector, resultHandler); this.params = params; } @Override void exec(MessageEncoder out) { if (suspended) { out.writeExecute(portal, fetch); out.writeSync(); } else { if (ps.bind.statement == 0) { out.writeParse(new Parse(ps.sql)); } out.writeBind(ps.bind, portal, (List) params); out.writeExecute(portal, fetch); out.writeSync(); } } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/ExtendedQueryCommandBase.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.impl.codec.decoder.RowDescription; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import java.util.stream.Collector; /** * @author Julien Viet */ abstract class ExtendedQueryCommandBase extends QueryCommandBase { protected final PreparedStatement ps; protected final int fetch; protected final String portal; protected final boolean suspended; ExtendedQueryCommandBase(PreparedStatement ps, int fetch, String portal, boolean suspended, boolean singleton, Collector collector, QueryResultHandler resultHandler) { super(collector, resultHandler); this.ps = ps; this.fetch = fetch; this.portal = portal; this.suspended = suspended; this.decoder = new RowResultDecoder<>(collector, singleton, ps.rowDesc); } @Override String sql() { return ps.sql; } @Override public void handleParseComplete() { // Response to Parse } @Override public void handlePortalSuspended() { R result = decoder.complete(); RowDescription desc = decoder.description(); int size = decoder.size(); decoder.reset(); this.result = true; resultHandler.handleResult(0, size, desc, result); } @Override public void handleBindComplete() { // Response to Bind } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/InitCommand.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.PgException; import io.reactiverse.pgclient.impl.codec.TxStatus; import io.reactiverse.pgclient.impl.codec.decoder.ErrorResponse; import io.reactiverse.pgclient.impl.codec.encoder.MessageEncoder; import io.reactiverse.pgclient.impl.codec.encoder.PasswordMessage; import io.reactiverse.pgclient.impl.codec.encoder.StartupMessage; import io.vertx.core.Handler; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; /** * Initialize the connection so it can be used to interact with the database. * * @author Julien Viet */ public class InitCommand extends CommandBase { private final SocketConnection conn; private final String username; private final String password; private final String database; private String encoding; private MessageEncoder out; InitCommand( SocketConnection conn, String username, String password, String database) { this.conn = conn; this.username = username; this.password = password; this.database = database; } @Override void exec(MessageEncoder out) { this.out = out; out.writeStartupMessage(new StartupMessage(username, database)); } @Override public void handleAuthenticationMD5Password(byte[] salt) { out.writePasswordMessage(new PasswordMessage(username, password, salt)); out.flush(); } @Override public void handleAuthenticationClearTextPassword() { out.writePasswordMessage(new PasswordMessage(username, password, null)); out.flush(); } @Override public void handleAuthenticationOk() { // handler.handle(Future.succeededFuture(conn)); // handler = null; } @Override public void handleParameterStatus(String key, String value) { if(key.equals("client_encoding")) { encoding = value; } } @Override public void handleBackendKeyData(int processId, int secretKey) { conn.processId = processId; conn.secretKey = secretKey; } @Override public void handleErrorResponse(ErrorResponse errorResponse) { CommandResponse resp = CommandResponse.failure(new PgException(errorResponse)); completionHandler.handle(resp); } @Override public void handleReadyForQuery(TxStatus txStatus) { // The final phase before returning the connection // We should make sure we are supporting only UTF8 // https://www.postgresql.org/docs/9.5/static/multibyte.html#MULTIBYTE-CHARSET-SUPPORTED Charset cs = null; try { cs = Charset.forName(encoding); } catch (Exception ignore) { } CommandResponse fut; if(cs == null || !cs.equals(StandardCharsets.UTF_8)) { fut = CommandResponse.failure(encoding + " is not supported in the client only UTF8"); } else { fut = CommandResponse.success(conn); } completionHandler.handle(fut); } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/PgClientBase.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.*; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import java.util.List; import java.util.function.Function; import java.util.stream.Collector; public abstract class PgClientBase implements PgClient, CommandScheduler { @Override public C query(String sql, Handler> handler) { return query(sql, false,PgRowSetImpl.FACTORY, PgRowSetImpl.COLLECTOR, handler); } @Override public C query(String sql, Collector collector, Handler>> handler) { return query(sql, true, PgResultImpl::new, collector, handler); } private , R3 extends PgResult> C query( String sql, boolean singleton, Function factory, Collector collector, Handler> handler) { PgResultBuilder b = new PgResultBuilder<>(factory, handler); schedule(new SimpleQueryCommand<>(sql, singleton, collector, b), b); return (C) this; } @Override public C preparedQuery(String sql, Tuple arguments, Handler> handler) { return preparedQuery(sql, arguments, false, PgRowSetImpl.FACTORY, PgRowSetImpl.COLLECTOR, handler); } @Override public C preparedQuery(String sql, Tuple arguments, Collector collector, Handler>> handler) { return preparedQuery(sql, arguments, true, PgResultImpl::new, collector, handler); } private , R3 extends PgResult> C preparedQuery( String sql, Tuple arguments, boolean singleton, Function factory, Collector collector, Handler> handler) { schedule(new PrepareStatementCommand(sql), cr -> { if (cr.succeeded()) { PreparedStatement ps = cr.result(); String msg = ps.prepare((List) arguments); if (msg != null) { handler.handle(Future.failedFuture(msg)); } else { PgResultBuilder b = new PgResultBuilder<>(factory, handler); cr.scheduler.schedule(new ExtendedQueryCommand<>(ps, arguments, singleton, collector, b), b); } } else { handler.handle(Future.failedFuture(cr.cause())); } }); return (C) this; } @Override public C preparedQuery(String sql, Handler> handler) { return preparedQuery(sql, ArrayTuple.EMPTY, handler); } @Override public C preparedQuery(String sql, Collector collector, Handler>> handler) { return preparedQuery(sql, ArrayTuple.EMPTY, collector, handler); } @Override public C preparedBatch(String sql, List batch, Handler> handler) { return preparedBatch(sql, batch, false, PgRowSetImpl.FACTORY, PgRowSetImpl.COLLECTOR, handler); } @Override public C preparedBatch(String sql, List batch, Collector collector, Handler>> handler) { return preparedBatch(sql, batch, true, PgResultImpl::new, collector, handler); } private , R3 extends PgResult> C preparedBatch( String sql, List batch, boolean singleton, Function factory, Collector collector, Handler> handler) { schedule(new PrepareStatementCommand(sql), cr -> { if (cr.succeeded()) { PreparedStatement ps = cr.result(); for (Tuple args : batch) { String msg = ps.prepare((List) args); if (msg != null) { handler.handle(Future.failedFuture(msg)); return; } } PgResultBuilder b = new PgResultBuilder<>(factory, handler); cr.scheduler.schedule(new ExtendedBatchQueryCommand<>( ps, batch, singleton, collector, b), b); } else { handler.handle(Future.failedFuture(cr.cause())); } }); return (C) this; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/PgConnectionBase.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.PgPreparedQuery; import io.vertx.core.*; /** * @author Julien Viet */ public abstract class PgConnectionBase extends PgClientBase { protected final Context context; protected final Connection conn; PgConnectionBase(Context context, Connection conn) { this.context = context; this.conn = conn; } public C prepare(String sql, Handler> handler) { schedule(new PrepareStatementCommand(sql), cr -> { if (cr.succeeded()) { handler.handle(Future.succeededFuture(new PgPreparedQueryImpl(conn, context, cr.result()))); } else { handler.handle(Future.failedFuture(cr.cause())); } }); return (C) this; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/PgConnectionFactory.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.PgConnectOptions; import io.reactiverse.pgclient.SslMode; import io.vertx.core.*; import io.vertx.core.impl.NetSocketInternal; import io.vertx.core.net.*; /** * @author Julien Viet */ public class PgConnectionFactory { private final NetClient client; private final Context ctx; private final boolean registerCloseHook; private final String host; private final int port; private final SslMode sslMode; private final TrustOptions trustOptions; private final String hostnameVerificationAlgorithm; private final String database; private final String username; private final String password; private final boolean cachePreparedStatements; private final int pipeliningLimit; private final boolean isUsingDomainSocket; private final Closeable hook; public PgConnectionFactory(Context context, boolean registerCloseHook, PgConnectOptions options) { hook = this::close; this.registerCloseHook = registerCloseHook; ctx = context; if (registerCloseHook) { ctx.addCloseHook(hook); } NetClientOptions netClientOptions = new NetClientOptions(options); // Make sure ssl=false as we will use STARTLS netClientOptions.setSsl(false); this.sslMode = options.getSslMode(); this.hostnameVerificationAlgorithm = netClientOptions.getHostnameVerificationAlgorithm(); this.trustOptions = netClientOptions.getTrustOptions(); this.host = options.getHost(); this.port = options.getPort(); this.database = options.getDatabase(); this.username = options.getUser(); this.password = options.getPassword(); this.cachePreparedStatements = options.getCachePreparedStatements(); this.pipeliningLimit = options.getPipeliningLimit(); this.isUsingDomainSocket = options.isUsingDomainSocket(); this.client = context.owner().createNetClient(netClientOptions); } // Called by hook private void close(Handler> completionHandler) { client.close(); completionHandler.handle(Future.succeededFuture()); } public void close() { if (registerCloseHook) { ctx.removeCloseHook(hook); } client.close(); } public void create(Handler> completionHandler) { connect(ar -> { if (ar.succeeded()) { SocketConnection conn = ar.result(); conn.initializeCodec(); conn.sendStartupMessage(username, password, database, completionHandler); } else { completionHandler.handle(CommandResponse.failure(ar.cause())); } }); } public void connect(Handler> handler) { switch (sslMode) { case DISABLE: doConnect(false, handler); break; case ALLOW: doConnect(false, ar -> { if (ar.succeeded()) { handler.handle(Future.succeededFuture(ar.result())); } else { doConnect(true, handler); } }); break; case PREFER: doConnect(true, ar -> { if (ar.succeeded()) { handler.handle(Future.succeededFuture(ar.result())); } else { doConnect(false, handler); } }); break; case VERIFY_FULL: if (hostnameVerificationAlgorithm == null || hostnameVerificationAlgorithm.isEmpty()) { handler.handle(Future.failedFuture(new IllegalArgumentException("Host verification algorithm must be specified under verify-full sslmode"))); return; } case VERIFY_CA: if (trustOptions == null) { handler.handle(Future.failedFuture(new IllegalArgumentException("Trust options must be specified under verify-full or verify-ca sslmode"))); return; } case REQUIRE: doConnect(true, handler); break; default: throw new IllegalArgumentException("Unsupported SSL mode"); } } private void doConnect(boolean ssl, Handler> handler) { if (Vertx.currentContext() != ctx) { throw new IllegalStateException(); } SocketAddress socketAddress; if (!isUsingDomainSocket) { socketAddress = SocketAddress.inetSocketAddress(port, host); } else { socketAddress = SocketAddress.domainSocketAddress(host + "/.s.PGSQL." + port); } Future future = Future.future().setHandler(ar -> { if (ar.succeeded()) { NetSocketInternal socket = (NetSocketInternal) ar.result(); SocketConnection conn = newSocketConnection(socket); if (ssl && !isUsingDomainSocket) { // upgrade connection to SSL if needed conn.upgradeToSSLConnection(ar2 -> { if (ar2.succeeded()) { handler.handle(Future.succeededFuture(conn)); } else { handler.handle(Future.failedFuture(ar2.cause())); } }); } else { handler.handle(Future.succeededFuture(conn)); } } else { handler.handle(Future.failedFuture(ar.cause())); } }); try { client.connect(socketAddress, null, future); } catch (Exception e) { // Client is closed future.fail(e); } } private SocketConnection newSocketConnection(NetSocketInternal socket) { return new SocketConnection(socket, cachePreparedStatements, pipeliningLimit, ctx); } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/PgConnectionImpl.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.*; import io.vertx.core.*; /** * @author Julien Viet */ public class PgConnectionImpl extends PgConnectionBase implements PgConnection, Connection.Holder { private final PgConnectionFactory factory; private volatile Handler exceptionHandler; private volatile Handler closeHandler; private Transaction tx; private volatile Handler notificationHandler; public PgConnectionImpl(PgConnectionFactory factory, Context context, Connection conn) { super(context, conn); this.factory = factory; } @Override public Connection connection() { return conn; } @Override public void handleClosed() { Handler handler = closeHandler; if (handler != null) { context.runOnContext(handler); } } @Override public void schedule(CommandBase cmd, Handler> handler) { cmd.handler = cr -> { // Tx might be gone ??? cr.scheduler = this; handler.handle(cr); }; schedule(cmd); } protected void schedule(CommandBase cmd) { if (context == Vertx.currentContext()) { if (tx != null) { tx.schedule(cmd); } else { conn.schedule(cmd); } } else { context.runOnContext(v -> { schedule(cmd); }); } } @Override public void handleException(Throwable err) { Handler handler = exceptionHandler; if (handler != null) { context.runOnContext(v -> { handler.handle(err); }); } else { err.printStackTrace(); } } @Override public boolean isSSL() { return conn.isSsl(); } @Override public PgConnection closeHandler(Handler handler) { closeHandler = handler; return this; } @Override public PgConnection notificationHandler(Handler handler) { notificationHandler = handler; return this; } @Override public PgConnection exceptionHandler(Handler handler) { exceptionHandler = handler; return this; } @Override public PgTransaction begin() { return begin(false); } PgTransaction begin(boolean closeOnEnd) { if (tx != null) { throw new IllegalStateException(); } tx = new Transaction(context, conn, v -> { tx = null; if (closeOnEnd) { close(); } }); return tx; } public void handleNotification(int processId, String channel, String payload) { Handler handler = notificationHandler; if (handler != null) { handler.handle(new PgNotification().setProcessId(processId).setChannel(channel).setPayload(payload)); } } @Override public void close() { if (context == Vertx.currentContext()) { if (tx != null) { tx.rollback(ar -> conn.close(this)); tx = null; } else { conn.close(this); } } else { context.runOnContext(v -> close()); } } @Override public int processId() { return conn.getProcessId(); } @Override public int secretKey() { return conn.getSecretKey(); } @Override public PgConnection cancelRequest(Handler> handler) { Context current = Vertx.currentContext(); if (current == context) { factory.connect(ar -> { if (ar.succeeded()) { SocketConnection conn = ar.result(); conn.sendCancelRequestMessage(this.processId(), this.secretKey(), handler); } else { handler.handle(Future.failedFuture(ar.cause())); } }); } else { context.runOnContext(v -> cancelRequest(handler)); } return this; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/PgConnectionUriParser.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.SslMode; import io.vertx.core.json.JsonObject; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.lang.Integer.*; import static java.lang.String.*; /** * This is Parser for parsing connection URIs of PostgreSQL. * Based on Version 9.6 * * @author Billy Yuan */ public class PgConnectionUriParser { private static final String FULL_URI_REGEX = "^postgre(?:s|sql)://(?:(\\w+(?::\\S+)?)@)?([0-9.]+|\\[[A-Za-z0-9:]+]|[A-Za-z0-9.%\\-_]+)?(?::(\\d+))?(?:/([A-Za-z0-9_\\-]+))?(?:\\?(.*))?$"; private static final int USER_INFO_GROUP = 1; private static final int NET_LOCATION_GROUP = 2; private static final int PORT_GROUP = 3; private static final int DATABASE_GROUP = 4; private static final int PARAMETER_GROUP = 5; public static JsonObject parse(String connectionUri) { // if we get any exception during the parsing, then we throw an IllegalArgumentException. try { JsonObject configuration = new JsonObject(); doParse(connectionUri, configuration); return configuration; } catch (Exception e) { throw new IllegalArgumentException("Cannot parse invalid connection URI: " + connectionUri, e); } } // execute the parsing process and store options in the configuration private static void doParse(String connectionUri, JsonObject configuration) { Pattern pattern = Pattern.compile(FULL_URI_REGEX); Matcher matcher = pattern.matcher(connectionUri); if (matcher.matches()) { // parse the user and password parseUserandPassword(matcher.group(USER_INFO_GROUP), configuration); // parse the IP address/host/unix domainSocket address parseNetLocation(matcher.group(NET_LOCATION_GROUP), configuration); // parse the port parsePort(matcher.group(PORT_GROUP), configuration); // parse the database name parseDatabaseName(matcher.group(DATABASE_GROUP), configuration); // parse the parameters parseParameters(matcher.group(PARAMETER_GROUP), configuration); } else { throw new IllegalArgumentException("Wrong syntax of connection URI"); } } private static void parseUserandPassword(String userInfo, JsonObject configuration) { if (userInfo == null || userInfo.isEmpty()) { return; } if (occurExactlyOnce(userInfo, ":")) { int index = userInfo.indexOf(":"); String user = userInfo.substring(0, index); if (user.isEmpty()) { throw new IllegalArgumentException("Can not only specify the password without a concrete user"); } String password = userInfo.substring(index + 1); configuration.put("user", decodeUrl(user)); configuration.put("password", decodeUrl(password)); } else if (!userInfo.contains(":")) { configuration.put("user", decodeUrl(userInfo)); } else { throw new IllegalArgumentException("Can not use multiple delimiters to delimit user and password"); } } private static void parseNetLocation(String hostInfo, JsonObject configuration) { if (hostInfo == null || hostInfo.isEmpty()) { return; } parseNetLocationValue(decodeUrl(hostInfo), configuration); } private static void parsePort(String portInfo, JsonObject configuration) { if (portInfo == null || portInfo.isEmpty()) { return; } int port; try { port = parseInt(decodeUrl(portInfo)); } catch (NumberFormatException e) { throw new IllegalArgumentException("The post must be a valid integer"); } if (port > 65535 || port <= 0) { throw new IllegalArgumentException("The post can only range in 1-65535"); } configuration.put("port", port); } private static void parseDatabaseName(String databaseInfo, JsonObject configuration) { if (databaseInfo == null || databaseInfo.isEmpty()) { return; } configuration.put("database", decodeUrl(databaseInfo)); } private static void parseParameters(String parametersInfo, JsonObject configuration) { if (parametersInfo == null || parametersInfo.isEmpty()) { return; } for (String parameterPair : parametersInfo.split("&")) { if (parameterPair.isEmpty()) { continue; } int indexOfDelimiter = parameterPair.indexOf("="); if (indexOfDelimiter < 0) { throw new IllegalArgumentException(format("Missing delimiter '=' of parameters \"%s\" in the part \"%s\"", parametersInfo, parameterPair)); } else { String key = parameterPair.substring(0, indexOfDelimiter).toLowerCase(); String value = decodeUrl(parameterPair.substring(indexOfDelimiter + 1).trim()); switch (key) { case "port": parsePort(value, configuration); break; case "host": parseNetLocationValue(value, configuration); break; case "hostaddr": configuration.put("host", value); break; case "user": configuration.put("user", value); break; case "password": configuration.put("password", value); break; case "dbname": configuration.put("database", value); break; case "sslmode": configuration.put("sslMode", SslMode.of(value)); break; default: configuration.put(key, value); break; } } } } private static void parseNetLocationValue(String hostValue, JsonObject configuration) { if (isRegardedAsIpv6Address(hostValue)) { configuration.put("host", hostValue.substring(1, hostValue.length() - 1)); } else { configuration.put("host", hostValue); } } private static boolean isRegardedAsIpv6Address(String hostAddress) { return hostAddress.startsWith("[") && hostAddress.endsWith("]"); } private static String decodeUrl(String url) { try { return URLDecoder.decode(url, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("The connection uri contains unknown characters that can not be resolved."); } } private static boolean occurExactlyOnce(String uri, String character) { return uri.contains(character) && uri.indexOf(character) == uri.lastIndexOf(character); } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/PgCursorImpl.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.*; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import java.util.*; /** * @author Julien Viet */ public class PgCursorImpl implements PgCursor { private final PgPreparedQueryImpl ps; private final Tuple params; private String portal; private boolean closed; private PgResultBuilder result; PgCursorImpl(PgPreparedQueryImpl ps, Tuple params) { this.ps = ps; this.params = params; } @Override public synchronized boolean hasMore() { if (result == null) { throw new IllegalStateException("No current cursor read"); } return result.isSuspended(); } @Override public synchronized void read(int count, Handler> handler) { if (portal == null) { portal = UUID.randomUUID().toString(); result = new PgResultBuilder<>(PgRowSetImpl.FACTORY, handler); ps.execute(params, count, portal, false, false, PgRowSetImpl.COLLECTOR, result, result); } else if (result.isSuspended()) { result = new PgResultBuilder<>(PgRowSetImpl.FACTORY, handler); ps.execute(params, count, portal, true, false, PgRowSetImpl.COLLECTOR, result, result); } else { throw new IllegalStateException(); } } @Override public synchronized void close(Handler> completionHandler) { if (!closed) { closed = true; if (portal == null) { completionHandler.handle(Future.succeededFuture()); } else { String p = portal; portal = null; result = null; ps.closePortal(p, completionHandler); } } } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/PgPoolImpl.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.*; import io.vertx.core.*; /** * Todo : * * - handle timeout when acquiring a connection * - for per statement pooling, have several physical connection and use the less busy one to avoid head of line blocking effect * * @author Julien Viet * @author Emad Alblueshi */ public class PgPoolImpl extends PgClientBase implements PgPool { private final Context context; private final PgConnectionFactory factory; private final ConnectionPool pool; private final boolean closeVertx; public PgPoolImpl(Vertx vertx, boolean closeVertx, PgPoolOptions options) { int maxSize = options.getMaxSize(); if (maxSize < 1) { throw new IllegalArgumentException("Pool max size must be > 0"); } if (options.isUsingDomainSocket() && !vertx.isNativeTransportEnabled()) { throw new VertxException("Native transport is not available"); } this.context = vertx.getOrCreateContext(); this.factory = new PgConnectionFactory(context, Vertx.currentContext() != null, options); this.pool = new ConnectionPool(factory::create, maxSize, options.getMaxWaitQueueSize()); this.closeVertx = closeVertx; } @Override public void getConnection(Handler> handler) { Context current = Vertx.currentContext(); if (current == context) { pool.acquire(new ConnectionWaiter(handler)); } else { context.runOnContext(v -> getConnection(handler)); } } @Override public void begin(Handler> handler) { getConnection(ar -> { if (ar.succeeded()) { PgConnectionImpl conn = (PgConnectionImpl) ar.result(); PgTransaction tx = conn.begin(true); handler.handle(Future.succeededFuture(tx)); } else { handler.handle(Future.failedFuture(ar.cause())); } }); } @Override public void schedule(CommandBase cmd, Handler> handler) { Context current = Vertx.currentContext(); if (current == context) { pool.acquire(new CommandWaiter() { // SHOULD BE IT !!!!! @Override protected void onSuccess(Connection conn) { cmd.handler = ar -> { ar.scheduler = new CommandScheduler() { @Override public void schedule(CommandBase cmd, Handler> handler) { cmd.handler = cr -> { cr.scheduler = this; handler.handle(cr); }; conn.schedule(cmd); } }; handler.handle(ar); }; conn.schedule(cmd); conn.close(this); } @Override protected void onFailure(Throwable cause) { cmd.handler = handler; cmd.fail(cause); } }); } else { context.runOnContext(v -> schedule(cmd, handler)); } } private abstract class CommandWaiter implements Connection.Holder, Handler> { private Connection conn; protected abstract void onSuccess(Connection conn); protected abstract void onFailure(Throwable cause); @Override public void handleNotification(int processId, String channel, String payload) { // What should we do ? } @Override public void handle(AsyncResult ar) { if (ar.succeeded()) { Connection conn = ar.result(); this.conn = conn; conn.init(this); onSuccess(conn); } else { onFailure(ar.cause()); } } @Override public void handleClosed() { } @Override public void handleException(Throwable err) { } @Override public Connection connection() { return conn; } } private class ConnectionWaiter implements Handler> { private final Handler> handler; private ConnectionWaiter(Handler> handler) { this.handler = handler; } @Override public void handle(AsyncResult ar) { if (ar.succeeded()) { Connection conn = ar.result(); PgConnectionImpl holder = new PgConnectionImpl(factory, context, conn); conn.init(holder); handler.handle(Future.succeededFuture(holder)); } else { handler.handle(Future.failedFuture(ar.cause())); } } } @Override public void close() { Context current = Vertx.currentContext(); if (current == context) { pool.close(); factory.close(); if (closeVertx) { context.owner().close(); } } else { context.runOnContext(v -> close()); } } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/PgPreparedQueryImpl.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.*; import io.vertx.core.*; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.stream.Collector; /** * @author Julien Viet */ class PgPreparedQueryImpl implements PgPreparedQuery { private final Connection conn; private final Context context; private final PreparedStatement ps; private final AtomicBoolean closed = new AtomicBoolean(); PgPreparedQueryImpl(Connection conn, Context context, PreparedStatement ps) { this.conn = conn; this.context = context; this.ps = ps; } @Override public PgPreparedQuery execute(Tuple args, Handler> handler) { return execute(args, false, PgRowSetImpl.FACTORY, PgRowSetImpl.COLLECTOR, handler); } @Override public PgPreparedQuery execute(Tuple args, Collector collector, Handler>> handler) { return execute(args, true, PgResultImpl::new, collector, handler); } private , R3 extends PgResult> PgPreparedQuery execute( Tuple args, boolean singleton, Function factory, Collector collector, Handler> handler) { PgResultBuilder b = new PgResultBuilder<>(factory, handler); return execute(args, 0, null, false, singleton, collector, b, b); } PgPreparedQuery execute(Tuple args, int fetch, String portal, boolean suspended, boolean singleton, Collector collector, QueryResultHandler resultHandler, Handler> handler) { if (context == Vertx.currentContext()) { String msg = ps.prepare((List) args); if (msg != null) { handler.handle(Future.failedFuture(msg)); } else { ExtendedQueryCommand cmd = new ExtendedQueryCommand<>( ps, args, fetch, portal, suspended, singleton, collector, resultHandler); cmd.handler = handler; conn.schedule(cmd); } } else { context.runOnContext(v -> execute(args, fetch, portal, suspended, singleton, collector, resultHandler, handler)); } return this; } @Override public PgCursor cursor(Tuple args) { String msg = ps.prepare((List) args); if (msg != null) { throw new IllegalArgumentException(msg); } return new PgCursorImpl(this, args); } @Override public void close() { close(ar -> { }); } public PgPreparedQuery batch(List argsList, Handler> handler) { return batch(argsList, false, PgRowSetImpl.FACTORY, PgRowSetImpl.COLLECTOR, handler); } @Override public PgPreparedQuery batch(List argsList, Collector collector, Handler>> handler) { return batch(argsList, true, PgResultImpl::new, collector, handler); } private , R3 extends PgResult> PgPreparedQuery batch( List argsList, boolean singleton, Function factory, Collector collector, Handler> handler) { for (Tuple args : argsList) { String msg = ps.prepare((List) args); if (msg != null) { handler.handle(Future.failedFuture(msg)); return this; } } PgResultBuilder b = new PgResultBuilder<>(factory, handler); ExtendedBatchQueryCommand cmd = new ExtendedBatchQueryCommand<>(ps, argsList, singleton, collector, b); cmd.handler = b; conn.schedule(cmd); return this; } @Override public PgStream createStream(int fetch, Tuple args) { return new PgStreamImpl(this, fetch, args); } @Override public void close(Handler> completionHandler) { if (closed.compareAndSet(false, true)) { CloseStatementCommand cmd = new CloseStatementCommand(); cmd.handler = completionHandler; conn.schedule(cmd); } else { completionHandler.handle(Future.failedFuture("Already closed")); } } void closePortal(String portal, Handler> handler) { ClosePortalCommand cmd = new ClosePortalCommand(portal); cmd.handler = handler; conn.schedule(cmd); } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/PgResultBase.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.PgResult; import java.util.List; public abstract class PgResultBase> implements PgResult { int updated; List columnNames; int size; R next; @Override public List columnsNames() { return columnNames; } @Override public int rowCount() { return updated; } @Override public int size() { return size; } @Override public R next() { return next; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/PgResultBuilder.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.PgResult; import io.reactiverse.pgclient.impl.codec.decoder.RowDescription; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import java.util.function.Function; /** * A query result handler for building a {@link PgResult}. */ public class PgResultBuilder, L extends PgResult> implements QueryResultHandler, Handler> { private final Handler> handler; private final Function factory; private R first; private boolean suspended; PgResultBuilder(Function factory, Handler> handler) { this.factory = factory; this.handler = handler; } @Override public void handleResult(int updatedCount, int size, RowDescription desc, T result) { R r = factory.apply(result); r.updated = updatedCount; r.size = size; r.columnNames = desc != null ? desc.columnNames() : null; handleResult(r); } private void handleResult(R result) { if (first == null) { first = result; } else { R h = first; while (h.next != null) { h = h.next; } h.next = result; } } @Override public void handle(AsyncResult res) { suspended = res.succeeded() && res.result(); handler.handle((AsyncResult) res.map(first)); } public boolean isSuspended() { return suspended; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/PgResultImpl.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; public class PgResultImpl extends PgResultBase> { private final T value; public PgResultImpl(T value) { this.value = value; } @Override public T value() { return value; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/PgRowSetImpl.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.PgIterator; import io.reactiverse.pgclient.PgRowSet; import io.reactiverse.pgclient.Row; import java.util.NoSuchElementException; import java.util.function.Function; import java.util.stream.Collector; class PgRowSetImpl extends PgResultBase implements PgRowSet { static Collector COLLECTOR = Collector.of( PgRowSetImpl::new, (set, row) -> { if (set.head == null) { set.head = set.tail = (RowImpl) row; } else { set.tail.next = (RowImpl) row; set.tail = set.tail.next; } }, (set1, set2) -> null, // Shall not be invoked as this is sequential (set) -> set ); static Function FACTORY = rs -> (PgRowSetImpl) rs; private RowImpl head; private RowImpl tail; @Override public PgRowSet value() { return this; } @Override public PgIterator iterator() { return new PgIterator() { RowImpl current = head; @Override public boolean hasNext() { return current != null; } @Override public Row next() { if (current == null) { throw new NoSuchElementException(); } RowImpl r = current; current = current.next; return r; } }; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/PgStreamImpl.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.*; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import java.util.Iterator; public class PgStreamImpl implements PgStream, Handler> { private final PgPreparedQueryImpl ps; private final int fetch; private final Tuple params; private Handler endHandler; private Handler rowHandler; private Handler exceptionHandler; private long demand; private boolean emitting; private PgCursor cursor; private Iterator result; PgStreamImpl(PgPreparedQueryImpl ps, int fetch, Tuple params) { this.ps = ps; this.fetch = fetch; this.params = params; this.demand = Long.MAX_VALUE; } @Override public synchronized PgStream exceptionHandler(Handler handler) { exceptionHandler = handler; return this; } @Override public PgStream handler(Handler handler) { PgCursor c; synchronized (this) { if (handler != null) { if (cursor == null) { rowHandler = handler; c = cursor = ps.cursor(params); } else { throw new UnsupportedOperationException("Handle me gracefully"); } } else { if (cursor != null) { cursor = null; } else { rowHandler = null; } return this; } } c.read(fetch, this); return this; } @Override public synchronized PgStream pause() { demand = 0L; return this; } public PgStream fetch(long amount) { if (amount < 0L) { throw new IllegalArgumentException("Invalid fetch amount " + amount); } synchronized (this) { demand += amount; if (demand < 0L) { demand = Long.MAX_VALUE; } if (cursor == null) { return this; } } checkPending(); return this; } @Override public PgStream resume() { return fetch(Long.MAX_VALUE); } @Override public synchronized PgStream endHandler(Handler handler) { endHandler = handler; return this; } @Override public void handle(AsyncResult ar) { if (ar.failed()) { Handler handler; synchronized (PgStreamImpl.this) { cursor = null; handler = exceptionHandler; } if (handler != null) { handler.handle(ar.cause()); } } else { result = ar.result().iterator(); checkPending(); } } @Override public void close() { close(ar -> {}); } @Override public void close(Handler> completionHandler) { PgCursor c; synchronized (this) { if ((c = cursor) == null) { return; } cursor = null; } c.close(completionHandler); } private void checkPending() { synchronized (PgStreamImpl.this) { if (emitting) { return; } emitting = true; } while (true) { synchronized (PgStreamImpl.this) { if (demand == 0L || result == null) { emitting = false; break; } Handler handler; Object event; if (result.hasNext()) { handler = rowHandler; event = result.next(); if (demand != Long.MAX_VALUE) { demand--; } } else { result = null; emitting = false; if (cursor.hasMore()) { cursor.read(fetch, this); break; } else { cursor = null; handler = endHandler; event = null; } } if (handler != null) { handler.handle(event); } } } } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/PrepareStatementCommand.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.PgException; import io.reactiverse.pgclient.impl.codec.TxStatus; import io.reactiverse.pgclient.impl.codec.decoder.ErrorResponse; import io.reactiverse.pgclient.impl.codec.decoder.ParameterDescription; import io.reactiverse.pgclient.impl.codec.decoder.RowDescription; import io.reactiverse.pgclient.impl.codec.encoder.MessageEncoder; import io.reactiverse.pgclient.impl.codec.encoder.Describe; import io.reactiverse.pgclient.impl.codec.encoder.Parse; import io.vertx.core.Handler; public class PrepareStatementCommand extends CommandBase { final String sql; long statement; // 0 means unamed statement otherwise CString SocketConnection.CachedPreparedStatement cached; private ParameterDescription parameterDesc; private RowDescription rowDesc; PrepareStatementCommand(String sql) { this.sql = sql; } @Override void exec(MessageEncoder out) { out.writeParse(new Parse(sql, statement)); out.writeDescribe(new Describe(statement, null)); out.writeSync(); } @Override public void handleParseComplete() { // Response to parse } @Override public void handleParameterDescription(ParameterDescription parameterDesc) { // Response to Describe this.parameterDesc = parameterDesc; } @Override public void handleRowDescription(RowDescription rowDesc) { // Response to Describe this.rowDesc = rowDesc; } @Override public void handleNoData() { // Response to Describe } @Override public void handleErrorResponse(ErrorResponse errorResponse) { failure = new PgException(errorResponse); } @Override public void handleReadyForQuery(TxStatus txStatus) { result = new PreparedStatement(sql, statement, parameterDesc, rowDesc); super.handleReadyForQuery(txStatus); } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/PreparedStatement.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.impl.codec.ColumnDesc; import io.reactiverse.pgclient.impl.codec.DataFormat; import io.reactiverse.pgclient.impl.codec.decoder.ParameterDescription; import io.reactiverse.pgclient.impl.codec.decoder.RowDescription; import io.reactiverse.pgclient.impl.codec.encoder.Bind; import java.util.Arrays; import java.util.List; class PreparedStatement { private static final ColumnDesc[] EMPTY_COLUMNS = new ColumnDesc[0]; final String sql; final Bind bind; private final ParameterDescription paramDesc; final RowDescription rowDesc; PreparedStatement(String sql, long statement, ParameterDescription paramDesc, RowDescription rowDesc) { // Fix to use binary when possible if (rowDesc != null) { rowDesc = new RowDescription(Arrays.stream(rowDesc.columns()) .map(c -> new ColumnDesc( c.getName(), c.getRelationId(), c.getRelationAttributeNo(), c.getDataType(), c.getLength(), c.getTypeModifier(), c.getDataType().supportsBinary ? DataFormat.BINARY : DataFormat.TEXT)) .toArray(ColumnDesc[]::new)); } this.paramDesc = paramDesc; this.rowDesc = rowDesc; this.sql = sql; this.bind = new Bind(statement, paramDesc != null ? paramDesc.getParamDataTypes() : null, rowDesc != null ? rowDesc.columns() : EMPTY_COLUMNS); } String prepare(List values) { return paramDesc.prepare(values); } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/QueryCommandBase.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.PgException; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.impl.codec.decoder.ErrorResponse; import io.reactiverse.pgclient.impl.codec.decoder.RowDescription; import java.util.stream.Collector; /** * @author Julien Viet */ public abstract class QueryCommandBase extends CommandBase { public RowResultDecoder decoder; final QueryResultHandler resultHandler; final Collector collector; QueryCommandBase(Collector collector, QueryResultHandler resultHandler) { this.resultHandler = resultHandler; this.collector = collector; } abstract String sql(); @Override public void handleCommandComplete(int updated) { this.result = false; T result; int size; RowDescription desc; if (decoder != null) { result = decoder.complete(); desc = decoder.description(); size = decoder.size(); decoder.reset(); } else { result = emptyResult(collector); size = 0; desc = null; } resultHandler.handleResult(updated, size, desc, result); } @Override public void handleErrorResponse(ErrorResponse errorResponse) { failure = new PgException(errorResponse); } private static T emptyResult(Collector collector) { return collector.finisher().apply(collector.supplier().get()); } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/QueryResultHandler.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.impl.codec.decoder.RowDescription; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; /** * @author Julien Viet */ public interface QueryResultHandler { void handleResult(int updatedCount, int size, RowDescription desc, T result); } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/RowImpl.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.data.Box; import io.reactiverse.pgclient.data.Circle; import io.reactiverse.pgclient.data.Json; import io.reactiverse.pgclient.data.Line; import io.reactiverse.pgclient.data.LineSegment; import io.reactiverse.pgclient.data.Numeric; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.data.Path; import io.reactiverse.pgclient.data.Polygon; import io.reactiverse.pgclient.impl.codec.ColumnDesc; import io.reactiverse.pgclient.data.Interval; import io.reactiverse.pgclient.impl.codec.decoder.RowDescription; import io.reactiverse.pgclient.data.Point; import io.vertx.core.buffer.Buffer; import java.math.BigDecimal; import java.time.*; import java.time.temporal.Temporal; import java.util.UUID; public class RowImpl extends ArrayTuple implements Row { // Linked list RowImpl next; private final RowDescription desc; public RowImpl(RowDescription desc) { super(desc.columns().length); this.desc = desc; } public RowImpl(RowImpl row) { super(row); this.desc = row.desc; } @Override public String getColumnName(int pos) { final ColumnDesc[] columnDescs = desc.columns(); return pos < 0 || columnDescs.length - 1 < pos ? null : columnDescs[pos].getName(); } @Override public Boolean getBoolean(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getBoolean(pos); } @Override public Object getValue(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getValue(pos); } @Override public Short getShort(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getShort(pos); } @Override public Integer getInteger(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getInteger(pos); } @Override public Long getLong(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getLong(pos); } @Override public Float getFloat(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getFloat(pos); } @Override public Double getDouble(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getDouble(pos); } @Override public String getString(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getString(pos); } @Override public Json getJson(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getJson(pos); } @Override public Buffer getBuffer(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getBuffer(pos); } @Override public Temporal getTemporal(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getTemporal(pos); } @Override public LocalDate getLocalDate(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getLocalDate(pos); } @Override public LocalTime getLocalTime(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getLocalTime(pos); } @Override public LocalDateTime getLocalDateTime(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getLocalDateTime(pos); } @Override public OffsetTime getOffsetTime(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getOffsetTime(pos); } @Override public OffsetDateTime getOffsetDateTime(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getOffsetDateTime(pos); } @Override public UUID getUUID(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getUUID(pos); } @Override public BigDecimal getBigDecimal(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getBigDecimal(pos); } @Override public Numeric getNumeric(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getNumeric(pos); } @Override public Point getPoint(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getPoint(pos); } @Override public Line getLine(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getLine(pos); } @Override public LineSegment getLineSegment(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getLineSegment(pos); } @Override public Box getBox(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getBox(pos); } @Override public Path getPath(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getPath(pos); } @Override public Polygon getPolygon(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getPolygon(pos); } @Override public Circle getCircle(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getCircle(pos); } @Override public Interval getInterval(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getInterval(pos); } @Override public Boolean[] getBooleanArray(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getBooleanArray(pos); } @Override public Short[] getShortArray(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getShortArray(pos); } @Override public Integer[] getIntegerArray(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getIntegerArray(pos); } @Override public Long[] getLongArray(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getLongArray(pos); } @Override public Float[] getFloatArray(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getFloatArray(pos); } @Override public Double[] getDoubleArray(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getDoubleArray(pos); } @Override public String[] getStringArray(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getStringArray(pos); } @Override public LocalDate[] getLocalDateArray(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getLocalDateArray(pos); } @Override public LocalTime[] getLocalTimeArray(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getLocalTimeArray(pos); } @Override public OffsetTime[] getOffsetTimeArray(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getOffsetTimeArray(pos); } @Override public LocalDateTime[] getLocalDateTimeArray(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getLocalDateTimeArray(pos); } @Override public OffsetDateTime[] getOffsetDateTimeArray(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getOffsetDateTimeArray(pos); } @Override public Buffer[] getBufferArray(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getBufferArray(pos); } @Override public UUID[] getUUIDArray(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getUUIDArray(pos); } @Override public Json[] getJsonArray(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getJsonArray(pos); } @Override public Numeric[] getNumericArray(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getNumericArray(pos); } @Override public Point[] getPointArray(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getPointArray(pos); } @Override public Line[] getLineArray(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getLineArray(pos); } @Override public LineSegment[] getLineSegmentArray(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getLineSegmentArray(pos); } @Override public Box[] getBoxArray(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getBoxArray(pos); } @Override public Path[] getPathArray(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getPathArray(pos); } @Override public Polygon[] getPolygonArray(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getPolygonArray(pos); } @Override public Circle[] getCircleArray(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getCircleArray(pos); } @Override public Interval[] getIntervalArray(String name) { int pos = desc.columnIndex(name); return pos == -1 ? null : getIntervalArray(pos); } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/RowResultDecoder.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.impl.codec.ColumnDesc; import io.reactiverse.pgclient.impl.codec.DataFormat; import io.reactiverse.pgclient.impl.codec.DataTypeCodec; import io.reactiverse.pgclient.impl.codec.decoder.RowDecoder; import io.reactiverse.pgclient.impl.codec.decoder.RowDescription; import io.netty.buffer.ByteBuf; import java.util.function.BiConsumer; import java.util.stream.Collector; public class RowResultDecoder implements RowDecoder { private final Collector collector; private final boolean singleton; private final BiConsumer accumulator; private RowDescription desc; private int size; private C container; private Row row; RowResultDecoder(Collector collector, boolean singleton, RowDescription desc) { this.collector = collector; this.singleton = singleton; this.accumulator = collector.accumulator(); this.desc = desc; } public RowDescription description() { return desc; } public int size() { return size; } @Override public void decodeRow(int len, ByteBuf in) { if (container == null) { container = collector.supplier().get(); } if (singleton) { if (row == null) { row = new RowImpl(desc); } else { row.clear(); } } else { row = new RowImpl(desc); } Row row = new RowImpl(desc); for (int c = 0; c < len; ++c) { int length = in.readInt(); Object decoded = null; if (length != -1) { ColumnDesc columnDesc = desc.columns()[c]; if (columnDesc.getDataFormat() == DataFormat.BINARY) { decoded = DataTypeCodec.decodeBinary(columnDesc.getDataType(), in.readerIndex(), length, in); } else { decoded = DataTypeCodec.decodeText(columnDesc.getDataType(), in.readerIndex(), length, in); } in.skipBytes(length); } row.addValue(decoded); } accumulator.accept(container, row); size++; } R complete() { if (container == null) { container = collector.supplier().get(); } return collector.finisher().apply(container); } void reset() { container = null; size = 0; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/SimpleQueryCommand.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.impl.codec.decoder.RowDescription; import io.reactiverse.pgclient.impl.codec.encoder.MessageEncoder; import io.reactiverse.pgclient.impl.codec.encoder.Query; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import java.util.stream.Collector; /** * @author Julien Viet */ class SimpleQueryCommand extends QueryCommandBase { private final String sql; private final boolean singleton; SimpleQueryCommand(String sql, boolean singleton, Collector collector, QueryResultHandler resultHandler) { super(collector, resultHandler); this.sql = sql; this.singleton = singleton; } @Override String sql() { return sql; } @Override void exec(MessageEncoder out) { out.writeQuery(new Query(sql)); } @Override public void handleRowDescription(RowDescription rowDescription) { decoder = new RowResultDecoder<>(collector, singleton, rowDescription); } public String getSql() { return sql; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/SocketConnection.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.DecoderException; import io.reactiverse.pgclient.impl.codec.decoder.InitiateSslHandler; import io.reactiverse.pgclient.impl.codec.decoder.MessageDecoder; import io.reactiverse.pgclient.impl.codec.decoder.NoticeResponse; import io.reactiverse.pgclient.impl.codec.decoder.NotificationResponse; import io.reactiverse.pgclient.impl.codec.encoder.MessageEncoder; import io.vertx.core.*; import io.vertx.core.buffer.Buffer; import io.vertx.core.impl.NetSocketInternal; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author Julien Viet */ public class SocketConnection implements Connection { private static final Logger logger = LoggerFactory.getLogger(SocketConnection.class); enum Status { CLOSED, CONNECTED, CLOSING } private final NetSocketInternal socket; private final ArrayDeque> inflight = new ArrayDeque<>(); private final ArrayDeque> pending = new ArrayDeque<>(); private final Context context; private Status status = Status.CONNECTED; private Holder holder; private final Map psCache; private final StringLongSequence psSeq = new StringLongSequence(); private final int pipeliningLimit; private MessageDecoder decoder; private MessageEncoder encoder; int processId; int secretKey; public SocketConnection(NetSocketInternal socket, boolean cachePreparedStatements, int pipeliningLimit, Context context) { this.socket = socket; this.context = context; this.psCache = cachePreparedStatements ? new ConcurrentHashMap<>() : null; this.pipeliningLimit = pipeliningLimit; } public Context context() { return context; } void upgradeToSSLConnection(Handler> completionHandler) { ChannelPipeline pipeline = socket.channelHandlerContext().pipeline(); Future upgradeFuture = Future.future(); upgradeFuture.setHandler(ar->{ if (ar.succeeded()) { completionHandler.handle(Future.succeededFuture()); } else { Throwable cause = ar.cause(); if (cause instanceof DecoderException) { DecoderException err = (DecoderException) cause; cause = err.getCause(); } completionHandler.handle(Future.failedFuture(cause)); } }); pipeline.addBefore("handler", "initiate-ssl-handler", new InitiateSslHandler(this, upgradeFuture)); } void initializeCodec() { decoder = new MessageDecoder(inflight, socket.channelHandlerContext().alloc()); encoder = new MessageEncoder(socket.channelHandlerContext()); ChannelPipeline pipeline = socket.channelHandlerContext().pipeline(); pipeline.addBefore("handler", "decoder", decoder); socket.closeHandler(this::handleClosed); socket.exceptionHandler(this::handleException); socket.messageHandler(msg -> { try { handleMessage(msg); } catch (Exception e) { handleException(e); } }); } void sendStartupMessage(String username, String password, String database, Handler> completionHandler) { InitCommand cmd = new InitCommand(this, username, password, database); cmd.handler = completionHandler; schedule(cmd); } void sendCancelRequestMessage(int processId, int secretKey, Handler> handler) { Buffer buffer = Buffer.buffer(16); buffer.appendInt(16); // cancel request code buffer.appendInt(80877102); buffer.appendInt(processId); buffer.appendInt(secretKey); socket.write(buffer, ar -> { if (ar.succeeded()) { // directly close this connection if (status == Status.CONNECTED) { status = Status.CLOSING; socket.close(); } handler.handle(Future.succeededFuture()); } else { handler.handle(Future.failedFuture(ar.cause())); } }); } static class CachedPreparedStatement implements Handler> { private CommandResponse resp; private final ArrayDeque>> waiters = new ArrayDeque<>(); void get(Handler> handler) { if (resp != null) { handler.handle(resp); } else { waiters.add(handler); } } @Override public void handle(CommandResponse event) { resp = event; Handler> waiter; while ((waiter = waiters.poll()) != null) { waiter.handle(resp); } } } public NetSocketInternal socket() { return socket; } public boolean isSsl() { return socket.isSsl(); } @Override public void init(Holder holder) { this.holder = holder; } @Override public void close(Holder holder) { if (Vertx.currentContext() == context) { if (status == Status.CONNECTED) { status = Status.CLOSING; // Append directly since schedule checks the status and won't enqueue the command pending.add(CloseConnectionCommand.INSTANCE); checkPending(); } } else { context.runOnContext(v -> close(holder)); } } public void schedule(CommandBase cmd) { if (cmd.handler == null) { throw new IllegalArgumentException(); } if (Vertx.currentContext() != context) { throw new IllegalStateException(); } // Special handling for cache if (cmd instanceof PrepareStatementCommand) { PrepareStatementCommand psCmd = (PrepareStatementCommand) cmd; Map psCache = this.psCache; if (psCache != null) { SocketConnection.CachedPreparedStatement cached = psCache.get(psCmd.sql); if (cached != null) { Handler> handler = psCmd.handler; cached.get(handler); return; } else { psCmd.statement = psSeq.next(); psCmd.cached = cached = new SocketConnection.CachedPreparedStatement(); psCache.put(psCmd.sql, cached); Handler> a = psCmd.handler; psCmd.cached.get(a); psCmd.handler = psCmd.cached; } } } // if (status == Status.CONNECTED) { pending.add(cmd); checkPending(); } else { cmd.fail(new VertxException("Connection not open " + status)); } } @Override public int getProcessId() { return processId; } @Override public int getSecretKey() { return secretKey; } private void checkPending() { if (inflight.size() < pipeliningLimit) { CommandBase cmd; while (inflight.size() < pipeliningLimit && (cmd = pending.poll()) != null) { inflight.add(cmd); decoder.run(cmd); cmd.exec(encoder); } encoder.flush(); } } private void handleMessage(Object msg) { if (msg instanceof CommandResponse) { CommandBase cmd = inflight.poll(); checkPending(); cmd.handler.handle(msg); } else if (msg instanceof NotificationResponse) { handleNotification((NotificationResponse) msg); } else if (msg instanceof NoticeResponse) { handleNotice((NoticeResponse) msg); } } private void handleNotification(NotificationResponse response) { if (holder != null) { holder.handleNotification(response.getProcessId(), response.getChannel(), response.getPayload()); } } private void handleNotice(NoticeResponse notice) { logger.warn("Backend notice: " + "severity='" + notice.getSeverity() + "'" + ", code='" + notice.getCode() + "'" + ", message='" + notice.getMessage() + "'" + ", detail='" + notice.getDetail() + "'" + ", hint='" + notice.getHint() + "'" + ", position='" + notice.getPosition() + "'" + ", internalPosition='" + notice.getInternalPosition() + "'" + ", internalQuery='" + notice.getInternalQuery() + "'" + ", where='" + notice.getWhere() + "'" + ", file='" + notice.getFile() + "'" + ", line='" + notice.getLine() + "'" + ", routine='" + notice.getRoutine() + "'" + ", schema='" + notice.getSchema() + "'" + ", table='" + notice.getTable() + "'" + ", column='" + notice.getColumn() + "'" + ", dataType='" + notice.getDataType() + "'" + ", constraint='" + notice.getConstraint() + "'"); } private void handleClosed(Void v) { handleClose(null); } private synchronized void handleException(Throwable t) { if (t instanceof DecoderException) { DecoderException err = (DecoderException) t; t = err.getCause(); } handleClose(t); } private void handleClose(Throwable t) { if (status != Status.CLOSED) { status = Status.CLOSED; if (t != null) { synchronized (this) { if (holder != null) { holder.handleException(t); } } } Throwable cause = t == null ? new VertxException("closed") : t; for (ArrayDeque> q : Arrays.asList(inflight, pending)) { CommandBase cmd; while ((cmd = q.poll()) != null) { CommandBase c = cmd; context.runOnContext(v -> c.fail(cause)); } } if (holder != null) { holder.handleClosed(); } } } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/StringLongSequence.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; public class StringLongSequence { private short count; public long next() { short val = count++; long next = 0x30_30_30_00_00_00_00_00L; next |= toHex(val >> 12 & 0xF) << 32; next |= toHex(val >> 8 & 0xF) << 24; next |= toHex(val >> 4 & 0xF) << 16; next |= toHex(val >> 0 & 0xF) << 8; return next; } private static long toHex(int c) { if (c < 10) { return (byte)('0' + c); } else { return (byte)('A' + c - 10); } } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/Transaction.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl; import io.reactiverse.pgclient.*; import io.reactiverse.pgclient.impl.codec.TxStatus; import io.vertx.core.*; import java.util.ArrayDeque; import java.util.Deque; class Transaction extends PgConnectionBase implements PgTransaction { private static final int ST_BEGIN = 0; private static final int ST_PENDING = 1; private static final int ST_PROCESSING = 2; private static final int ST_COMPLETED = 3; private final Handler disposeHandler; private Deque> pending = new ArrayDeque<>(); private Handler failedHandler; private int status = ST_BEGIN; Transaction(Context context, Connection conn, Handler disposeHandler) { super(context, conn); this.disposeHandler = disposeHandler; doSchedule(doQuery("BEGIN", this::afterBegin)); } private void doSchedule(CommandBase cmd) { if (context == Vertx.currentContext()) { conn.schedule(cmd); } else { context.runOnContext(v -> conn.schedule(cmd)); } } private synchronized void afterBegin(AsyncResult ar) { if (ar.succeeded()) { status = ST_PENDING; } else { status = ST_COMPLETED; } checkPending(); } private boolean isComplete(CommandBase cmd) { if (cmd instanceof QueryCommandBase) { String sql = ((QueryCommandBase) cmd).sql().trim(); return sql.equalsIgnoreCase("COMMIT") || sql.equalsIgnoreCase("ROLLBACK"); } return false; } private synchronized void checkPending() { switch (status) { case ST_BEGIN: break; case ST_PENDING: { CommandBase cmd = pending.poll(); if (cmd != null) { if (isComplete(cmd)) { status = ST_COMPLETED; } else { wrap(cmd); status = ST_PROCESSING; } doSchedule(cmd); } break; } case ST_PROCESSING: break; case ST_COMPLETED: { if (pending.size() > 0) { VertxException err = new VertxException("Transaction already completed"); CommandBase cmd; while ((cmd = pending.poll()) != null) { cmd.fail(err); } } break; } } } @Override public void schedule(CommandBase cmd, Handler> handler) { cmd.handler = cr -> { cr.scheduler = this; handler.handle(cr); }; schedule(cmd); } public void schedule(CommandBase cmd) { synchronized (this) { pending.add(cmd); } checkPending(); } private void wrap(CommandBase cmd) { Handler> handler = cmd.handler; cmd.handler = ar -> { synchronized (Transaction.this) { status = ST_PENDING; if (ar.txStatus() == TxStatus.FAILED) { // We won't recover from this so rollback CommandBase c; while ((c = pending.poll()) != null) { c.fail(new RuntimeException("rollback exception")); } Handler h = failedHandler; if (h != null) { context.runOnContext(h); } schedule(doQuery("ROLLBACK", ar2 -> { disposeHandler.handle(null); handler.handle(ar); })); } else { handler.handle(ar); checkPending(); } } }; } @Override public void commit() { commit(null); } public void commit(Handler> handler) { switch (status) { case ST_BEGIN: case ST_PENDING: case ST_PROCESSING: schedule(doQuery("COMMIT", ar -> { disposeHandler.handle(null); if (handler != null) { if (ar.succeeded()) { handler.handle(Future.succeededFuture()); } else { handler.handle(Future.failedFuture(ar.cause())); } } })); break; case ST_COMPLETED: if (handler != null) { handler.handle(Future.failedFuture("Transaction already completed")); } break; } } @Override public void rollback() { rollback(null); } public void rollback(Handler> handler) { schedule(doQuery("ROLLBACK", ar -> { disposeHandler.handle(null); if (handler != null) { handler.handle(ar.mapEmpty()); } })); } @Override public void close() { rollback(); } @Override public PgTransaction abortHandler(Handler handler) { failedHandler = handler; return this; } private CommandBase doQuery(String sql, Handler> handler) { PgResultBuilder b = new PgResultBuilder<>(PgRowSetImpl.FACTORY, handler); SimpleQueryCommand cmd = new SimpleQueryCommand<>(sql, false, PgRowSetImpl.COLLECTOR, b); cmd.handler = b; return cmd; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/ColumnDesc.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec; import java.util.Objects; /** * @author Emad Alblueshi */ public class ColumnDesc { private final String name; private final int relationId; private final DataType dataType; private final DataFormat dataFormat; // are we sure of taht ???? private final short relationAttributeNo; private final short length; private final int typeModifier; public ColumnDesc(String name, int relationId, short relationAttributeNo, DataType dataType, short length, int typeModifier, DataFormat dataFormat) { this.name = name; this.dataType = dataType; this.dataFormat = dataFormat; this.length = length; this.relationId = relationId; this.relationAttributeNo = relationAttributeNo; this.typeModifier = typeModifier; } public String getName() { return name; } public DataType getDataType() { return dataType; } public DataFormat getDataFormat() { return dataFormat; } public int getRelationId() { return relationId; } public short getRelationAttributeNo() { return relationAttributeNo; } public short getLength() { return length; } public int getTypeModifier() { return typeModifier; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ColumnDesc column = (ColumnDesc) o; return relationId == column.relationId && relationAttributeNo == column.relationAttributeNo && length == column.length && typeModifier == column.typeModifier && Objects.equals(name, column.name) && dataType == column.dataType && dataFormat == column.dataFormat; } @Override public int hashCode() { return Objects.hash(name, dataType, dataFormat, relationId, relationAttributeNo, length, typeModifier); } @Override public String toString() { return "Column{" + "name='" + name + '\'' + ", dataType=" + dataType + ", dataFormat=" + dataFormat + ", relationId=" + relationId + ", relationAttributeNo=" + relationAttributeNo + ", length=" + length + ", typeModifier=" + typeModifier + '}'; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/DataFormat.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec; /** * @author Emad Alblueshi */ public enum DataFormat { TEXT(0), BINARY(1); final int id; DataFormat(int id) { this.id = id; } public static DataFormat valueOf(int id) { return (id == 0) ? DataFormat.TEXT : DataFormat.BINARY; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/DataType.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec; import io.netty.util.collection.IntObjectHashMap; import io.netty.util.collection.IntObjectMap; import io.reactiverse.pgclient.data.Box; import io.reactiverse.pgclient.data.Circle; import io.reactiverse.pgclient.data.Json; import io.reactiverse.pgclient.data.Line; import io.reactiverse.pgclient.data.LineSegment; import io.reactiverse.pgclient.data.Numeric; import io.reactiverse.pgclient.data.Interval; import io.reactiverse.pgclient.data.Path; import io.reactiverse.pgclient.data.Point; import io.reactiverse.pgclient.data.Polygon; import io.vertx.core.buffer.Buffer; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import java.time.*; import java.util.UUID; /** * PostgreSQL object * identifiers (OIDs) for data types * * @author Emad Alblueshi */ public enum DataType { BOOL(16, true, Boolean.class), BOOL_ARRAY(1000, true, Boolean[].class), INT2(21, true, Short.class, Number.class), INT2_ARRAY(1005, true, Short[].class, Number[].class), INT4(23, true, Integer.class, Number.class), INT4_ARRAY(1007, true, Integer[].class, Number[].class), INT8(20, true, Long.class, Number.class), INT8_ARRAY(1016, true, Long[].class, Number[].class), FLOAT4(700, true, Float.class, Number.class), FLOAT4_ARRAY(1021, true, Float[].class, Number[].class), FLOAT8(701, true, Double.class, Number.class), FLOAT8_ARRAY(1022, true, Double[].class, Number[].class), NUMERIC(1700, false, Numeric.class, Number.class), NUMERIC_ARRAY(1231, false, Numeric[].class, Number[].class), MONEY(790, true, Object.class), MONEY_ARRAY(791, true, Object[].class), BIT(1560, true, Object.class), BIT_ARRAY(1561, true, Object[].class), VARBIT(1562, true, Object.class), VARBIT_ARRAY(1563, true, Object[].class), CHAR(18, true, String.class), CHAR_ARRAY(1002, true, String[].class), VARCHAR(1043, true, String.class), VARCHAR_ARRAY(1015, true, String[].class), BPCHAR(1042, true, String.class), BPCHAR_ARRAY(1014, true, String[].class), TEXT(25, true, String.class), TEXT_ARRAY(1009, true, String[].class), NAME(19, true, String.class), NAME_ARRAY(1003, true, String[].class), DATE(1082, true, LocalDate.class), DATE_ARRAY(1182, true, LocalDate[].class), TIME(1083, true, LocalTime.class), TIME_ARRAY(1183, true, LocalTime[].class), TIMETZ(1266, true, OffsetTime.class), TIMETZ_ARRAY(1270, true, OffsetTime[].class), TIMESTAMP(1114, true, LocalDateTime.class), TIMESTAMP_ARRAY(1115, true, LocalDateTime[].class), TIMESTAMPTZ(1184, true, OffsetDateTime.class), TIMESTAMPTZ_ARRAY(1185, true, OffsetDateTime[].class), INTERVAL(1186, true, Interval.class), INTERVAL_ARRAY(1187, true, Interval[].class), BYTEA(17, true, Buffer.class), BYTEA_ARRAY(1001, true, Buffer[].class), MACADDR(829, true, Object.class), INET(869, true, Object[].class), CIDR(650, true, Object.class), MACADDR8(774, true, Object[].class), UUID(2950, true, UUID.class), UUID_ARRAY(2951, true, UUID[].class), JSON(114, true, Json.class), JSON_ARRAY(199, true, Json[].class), JSONB(3802, true, Json.class), JSONB_ARRAY(3807, true, Json[].class), XML(142, true, Object.class), XML_ARRAY(143, true, Object[].class), POINT(600, true, Point.class), POINT_ARRAY(1017, true, Point[].class), LINE(628, true, Line.class), LINE_ARRAY(629, true, Line[].class), LSEG(601, true, LineSegment.class), LSEG_ARRAY(1018, true, LineSegment[].class), BOX(603, true, Box.class), BOX_ARRAY(1020, true, Box[].class), PATH(602, true, Path.class), PATH_ARRAY(1019, true, Path[].class), POLYGON(604, true, Polygon.class), POLYGON_ARRAY(1027, true, Polygon[].class), CIRCLE(718, true, Circle.class), CIRCLE_ARRAY(719, true, Circle[].class), HSTORE(33670, true, Object.class), OID(26, true, Object.class), OID_ARRAY(1028, true, Object[].class), VOID(2278, true, Object.class), UNKNOWN(705, false, String.class); private static final Logger logger = LoggerFactory.getLogger(DataType.class); public final int id; public final boolean supportsBinary; public final Class encodingType; // Not really used for now public final Class decodingType; DataType(int id, boolean supportsBinary, Class type) { this.id = id; this.supportsBinary = supportsBinary; this.decodingType = type; this.encodingType = type; } DataType(int id, boolean supportsBinary, Class encodingType, Class decodingType) { this.id = id; this.supportsBinary = supportsBinary; this.encodingType = encodingType; this.decodingType = decodingType; } public static DataType valueOf(int oid) { DataType value = oidToDataType.get(oid); if (value == null) { logger.warn("Postgres type OID=" + oid + " not handled - using unknown type instead"); return UNKNOWN; } else { return value; } } private static IntObjectMap oidToDataType = new IntObjectHashMap<>(); static { for (DataType dataType : values()) { oidToDataType.put(dataType.id, dataType); } } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/DataTypeCodec.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec; import com.fasterxml.jackson.databind.JsonNode; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.handler.codec.DecoderException; import io.reactiverse.pgclient.data.Json; import io.reactiverse.pgclient.data.Numeric; import io.reactiverse.pgclient.data.*; import io.reactiverse.pgclient.impl.codec.formatter.DateTimeFormatter; import io.reactiverse.pgclient.impl.codec.formatter.TimeFormatter; import io.reactiverse.pgclient.impl.codec.util.UTF8StringEndDetector; import io.vertx.core.buffer.Buffer; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.*; import java.time.temporal.ChronoField; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.function.IntFunction; import java.util.stream.Collectors; import static java.util.concurrent.TimeUnit.*; public class DataTypeCodec { private static final Logger logger = LoggerFactory.getLogger(DataTypeCodec.class); private static final String[] empty_string_array = new String[0]; private static final LocalDate[] empty_local_date_array = new LocalDate[0]; private static final LocalTime[] empty_local_time_array = new LocalTime[0]; private static final OffsetTime[] empty_offset_time_array = new OffsetTime[0]; private static final LocalDateTime[] empty_local_date_time_array = new LocalDateTime[0]; private static final OffsetDateTime[] empty_offset_date_time_array = new OffsetDateTime[0]; private static final Buffer[] empty_buffer_array = new Buffer[0]; private static final UUID[] empty_uuid_array = new UUID[0]; private static final Json[] empty_json_array = new Json[0]; private static final Numeric[] empty_numeric_array = new Numeric[0]; private static final Point[] empty_point_array = new Point[0]; private static final Line[] empty_line_array = new Line[0]; private static final LineSegment[] empty_lseg_array = new LineSegment[0]; private static final Box[] empty_box_array = new Box[0]; private static final Path[] empty_path_array = new Path[0]; private static final Polygon[] empty_polygon_array = new Polygon[0]; private static final Circle[] empty_circle_array = new Circle[0]; private static final Interval[] empty_interval_array = new Interval[0]; private static final Boolean[] empty_boolean_array = new Boolean[0]; private static final Integer[] empty_integer_array = new Integer[0]; private static final Short[] empty_short_array = new Short[0]; private static final Long[] empty_long_array = new Long[0]; private static final Float[] empty_float_array = new Float[0]; private static final Double[] empty_double_array = new Double[0]; private static final LocalDate LOCAL_DATE_EPOCH = LocalDate.of(2000, 1, 1); private static final LocalDateTime LOCAL_DATE_TIME_EPOCH = LocalDateTime.of(2000, 1, 1, 0, 0, 0); private static final OffsetDateTime OFFSET_DATE_TIME_EPOCH = LocalDateTime.of(2000, 1, 1, 0, 0, 0).atOffset(ZoneOffset.UTC); // Sentinel used when an object is refused by the data type public static final Object REFUSED_SENTINEL = new Object(); private static final IntFunction BOOLEAN_ARRAY_FACTORY = size -> size == 0 ? empty_boolean_array : new Boolean[size]; private static final IntFunction SHORT_ARRAY_FACTORY = size -> size == 0 ? empty_short_array : new Short[size]; private static final IntFunction INTEGER_ARRAY_FACTORY = size -> size == 0 ? empty_integer_array : new Integer[size]; private static final IntFunction LONG_ARRAY_FACTORY = size -> size == 0 ? empty_long_array : new Long[size]; private static final IntFunction FLOAT_ARRAY_FACTORY = size -> size == 0 ? empty_float_array : new Float[size]; private static final IntFunction DOUBLE_ARRAY_FACTORY = size -> size == 0 ? empty_double_array : new Double[size]; private static final IntFunction STRING_ARRAY_FACTORY = size -> size == 0 ? empty_string_array : new String[size]; private static final IntFunction LOCALDATE_ARRAY_FACTORY = size -> size == 0 ? empty_local_date_array : new LocalDate[size]; private static final IntFunction LOCALTIME_ARRAY_FACTORY = size -> size == 0 ? empty_local_time_array : new LocalTime[size]; private static final IntFunction OFFSETTIME_ARRAY_FACTORY = size -> size == 0 ? empty_offset_time_array : new OffsetTime[size]; private static final IntFunction LOCALDATETIME_ARRAY_FACTORY = size -> size == 0 ? empty_local_date_time_array : new LocalDateTime[size]; private static final IntFunction OFFSETDATETIME_ARRAY_FACTORY = size -> size == 0 ? empty_offset_date_time_array : new OffsetDateTime[size]; private static final IntFunction BUFFER_ARRAY_FACTORY =size -> size == 0 ? empty_buffer_array : new Buffer[size]; private static final IntFunction UUID_ARRAY_FACTORY = size -> size == 0 ? empty_uuid_array : new UUID[size]; private static final IntFunction JSON_ARRAY_FACTORY = size -> size == 0 ? empty_json_array : new Json[size]; private static final IntFunction NUMERIC_ARRAY_FACTORY = size -> size == 0 ? empty_numeric_array : new Numeric[size]; private static final IntFunction POINT_ARRAY_FACTORY = size -> size == 0 ? empty_point_array : new Point[size]; private static final IntFunction LINE_ARRAY_FACTORY = size -> size == 0 ? empty_line_array : new Line[size]; private static final IntFunction LSEG_ARRAY_FACTORY = size -> size == 0 ? empty_lseg_array : new LineSegment[size]; private static final IntFunction BOX_ARRAY_FACTORY = size -> size == 0 ? empty_box_array : new Box[size]; private static final IntFunction PATH_ARRAY_FACTORY = size -> size == 0 ? empty_path_array : new Path[size]; private static final IntFunction POLYGON_ARRAY_FACTORY = size -> size == 0 ? empty_polygon_array : new Polygon[size]; private static final IntFunction CIRCLE_ARRAY_FACTORY = size -> size == 0 ? empty_circle_array : new Circle[size]; private static final IntFunction INTERVAL_ARRAY_FACTORY = size -> size == 0 ? empty_interval_array : new Interval[size]; public static void encodeText(DataType id, Object value, ByteBuf buff) { int index = buff.writerIndex(); buff.writeInt(0); textEncode(id, value, buff); buff.setInt(index, buff.writerIndex() - index - 4); } private static void textEncode(DataType id, Object value, ByteBuf buff) { switch (id) { case NUMERIC: textEncodeNUMERIC((Number) value, buff); break; case NUMERIC_ARRAY: textEncodeNUMERIC_ARRAY((Number[]) value, buff); break; case UNKNOWN: //default to treating unknown as a string buff.writeCharSequence(String.valueOf(value), StandardCharsets.UTF_8); break; default: logger.warn("Data type " + id + " does not support text encoding"); buff.writeCharSequence(String.valueOf(value), StandardCharsets.UTF_8); break; } } public static void encodeBinary(DataType id, Object value, ByteBuf buff) { switch (id) { case BOOL: binaryEncodeBOOL((Boolean) value, buff); break; case BOOL_ARRAY: binaryEncodeArray((Boolean[]) value, DataType.BOOL, buff); break; case INT2: binaryEncodeINT2((Number) value, buff); break; case INT2_ARRAY: binaryEncodeArray((Number[]) value, DataType.INT2, buff); break; case INT4: binaryEncodeINT4((Number) value, buff); break; case INT4_ARRAY: binaryEncodeArray((Number[]) value, DataType.INT4, buff); break; case INT8: binaryEncodeINT8((Number) value, buff); break; case INT8_ARRAY: binaryEncodeArray((Number[]) value, DataType.INT8, buff); break; case FLOAT4: binaryEncodeFLOAT4((Number) value, buff); break; case FLOAT4_ARRAY: binaryEncodeArray((Number[]) value, DataType.FLOAT4, buff); break; case FLOAT8: binaryEncodeFLOAT8((Number) value, buff); break; case FLOAT8_ARRAY: binaryEncodeArray((Number[]) value, DataType.FLOAT8, buff); break; case CHAR: binaryEncodeCHAR((String) value, buff); break; case CHAR_ARRAY: binaryEncodeArray((String[]) value, DataType.CHAR, buff); break; case VARCHAR: binaryEncodeVARCHAR((String) value, buff); break; case VARCHAR_ARRAY: binaryEncodeArray((String[]) value, DataType.VARCHAR, buff); break; case BPCHAR: binaryEncodeBPCHAR((String) value, buff); break; case BPCHAR_ARRAY: binaryEncodeArray((String[]) value, DataType.BPCHAR, buff); break; case TEXT: binaryEncodeTEXT((String) value, buff); break; case TEXT_ARRAY: binaryEncodeArray((String[]) value, DataType.TEXT, buff); break; case NAME: binaryEncodeNAME((String) value, buff); break; case NAME_ARRAY: binaryEncodeArray((String[]) value, DataType.NAME, buff); break; case DATE: binaryEncodeDATE((LocalDate) value, buff); break; case DATE_ARRAY: binaryEncodeArray((LocalDate[]) value, DataType.DATE, buff); break; case TIME: binaryEncodeTIME((LocalTime) value, buff); break; case TIME_ARRAY: binaryEncodeArray((LocalTime[]) value, DataType.TIME, buff); break; case TIMETZ: binaryEncodeTIMETZ((OffsetTime) value, buff); break; case TIMETZ_ARRAY: binaryEncodeArray((OffsetTime[]) value, DataType.TIMETZ, buff); break; case TIMESTAMP: binaryEncodeTIMESTAMP((LocalDateTime) value, buff); break; case TIMESTAMP_ARRAY: binaryEncodeArray((LocalDateTime[]) value, DataType.TIMESTAMP, buff); break; case TIMESTAMPTZ: binaryEncodeTIMESTAMPTZ((OffsetDateTime) value, buff); break; case TIMESTAMPTZ_ARRAY: binaryEncodeArray((OffsetDateTime[]) value, DataType.TIMESTAMPTZ, buff); break; case BYTEA: binaryEncodeBYTEA((Buffer) value, buff); break; case BYTEA_ARRAY: binaryEncodeArray((Buffer[]) value, DataType.BYTEA, buff); break; case UUID: binaryEncodeUUID((UUID) value, buff); break; case UUID_ARRAY: binaryEncodeArray((UUID[]) value, DataType.UUID, buff); break; case JSON: binaryEncodeJSON((Json) value, buff); break; case JSON_ARRAY: binaryEncodeArray((Json[]) value, DataType.JSON, buff); break; case JSONB: binaryEncodeJSONB((Json) value, buff); break; case JSONB_ARRAY: binaryEncodeArray((Json[]) value, DataType.JSONB, buff); break; case POINT: binaryEncodePoint((Point) value, buff); break; case POINT_ARRAY: binaryEncodeArray((Point[]) value, DataType.POINT, buff); break; case LINE: binaryEncodeLine((Line) value, buff); break; case LINE_ARRAY: binaryEncodeArray((Line[]) value, DataType.LINE, buff); break; case LSEG: binaryEncodeLseg((LineSegment) value, buff); break; case LSEG_ARRAY: binaryEncodeArray((LineSegment[]) value, DataType.LSEG, buff); break; case BOX: binaryEncodeBox((Box) value, buff); break; case BOX_ARRAY: binaryEncodeArray((Box[]) value, DataType.BOX, buff); break; case PATH: binaryEncodePath((Path) value, buff); break; case PATH_ARRAY: binaryEncodeArray((Path[]) value, DataType.PATH, buff); break; case POLYGON: binaryEncodePolygon((Polygon) value, buff); break; case POLYGON_ARRAY: binaryEncodeArray((Polygon[]) value, DataType.POLYGON, buff); break; case CIRCLE: binaryEncodeCircle((Circle) value, buff); break; case CIRCLE_ARRAY: binaryEncodeArray((Circle[]) value, DataType.CIRCLE, buff); break; case INTERVAL: binaryEncodeINTERVAL((Interval) value, buff); break; case INTERVAL_ARRAY: binaryEncodeArray((Interval[]) value, DataType.INTERVAL, buff); break; default: logger.warn("Data type " + id + " does not support binary encoding"); defaultEncodeBinary(value, buff); break; } } public static Object decodeBinary(DataType id, int index, int len, ByteBuf buff) { switch (id) { case BOOL: return binaryDecodeBOOL(index, len, buff); case BOOL_ARRAY: return binaryDecodeArray(BOOLEAN_ARRAY_FACTORY, DataType.BOOL, index, len, buff); case INT2: return binaryDecodeINT2(index, len, buff); case INT2_ARRAY: return binaryDecodeArray(SHORT_ARRAY_FACTORY, DataType.INT2, index, len, buff); case INT4: return binaryDecodeINT4(index, len, buff); case INT4_ARRAY: return binaryDecodeArray(INTEGER_ARRAY_FACTORY, DataType.INT4, index, len, buff); case INT8: return binaryDecodeINT8(index, len, buff); case INT8_ARRAY: return binaryDecodeArray(LONG_ARRAY_FACTORY, DataType.INT8, index, len, buff); case FLOAT4: return binaryDecodeFLOAT4(index, len, buff); case FLOAT4_ARRAY: return binaryDecodeArray(FLOAT_ARRAY_FACTORY, DataType.FLOAT4, index, len, buff); case FLOAT8: return binaryDecodeFLOAT8(index, len, buff); case FLOAT8_ARRAY: return binaryDecodeArray(DOUBLE_ARRAY_FACTORY, DataType.FLOAT8, index, len, buff); case CHAR: return binaryDecodeCHAR(index, len, buff); case CHAR_ARRAY: return binaryDecodeArray(STRING_ARRAY_FACTORY, DataType.CHAR, index, len, buff); case VARCHAR: return binaryDecodeVARCHAR(index, len, buff); case VARCHAR_ARRAY: return binaryDecodeArray(STRING_ARRAY_FACTORY, DataType.VARCHAR, index, len, buff); case BPCHAR: return binaryDecodeBPCHAR(index, len, buff); case BPCHAR_ARRAY: return binaryDecodeArray(STRING_ARRAY_FACTORY, DataType.BPCHAR, index, len, buff); case TEXT: return binaryDecodeTEXT(index, len, buff); case TEXT_ARRAY: return binaryDecodeArray(STRING_ARRAY_FACTORY, DataType.TEXT, index, len, buff); case NAME: return binaryDecodeNAME(index, len, buff); case NAME_ARRAY: return binaryDecodeArray(STRING_ARRAY_FACTORY, DataType.NAME, index, len, buff); case DATE: return binaryDecodeDATE(index, len, buff); case DATE_ARRAY: return binaryDecodeArray(LOCALDATE_ARRAY_FACTORY, DataType.DATE, index, len, buff); case TIME: return binaryDecodeTIME(index, len, buff); case TIME_ARRAY: return binaryDecodeArray(LOCALTIME_ARRAY_FACTORY, DataType.TIME, index, len, buff); case TIMETZ: return binaryDecodeTIMETZ(index, len, buff); case TIMETZ_ARRAY: return binaryDecodeArray(OFFSETTIME_ARRAY_FACTORY, DataType.TIMETZ, index, len, buff); case TIMESTAMP: return binaryDecodeTIMESTAMP(index, len, buff); case TIMESTAMP_ARRAY: return binaryDecodeArray(LOCALDATETIME_ARRAY_FACTORY, DataType.TIMESTAMP, index, len, buff); case TIMESTAMPTZ: return binaryDecodeTIMESTAMPTZ(index, len, buff); case TIMESTAMPTZ_ARRAY: return binaryDecodeArray(OFFSETDATETIME_ARRAY_FACTORY, DataType.TIMESTAMPTZ, index, len, buff); case BYTEA: return binaryDecodeBYTEA(index, len, buff); case BYTEA_ARRAY: return binaryDecodeArray(BUFFER_ARRAY_FACTORY, DataType.BYTEA, index, len, buff); case UUID: return binaryDecodeUUID(index, len, buff); case UUID_ARRAY: return binaryDecodeArray(UUID_ARRAY_FACTORY, DataType.UUID, index, len, buff); case JSON: return binaryDecodeJSON(index, len, buff); case JSON_ARRAY: return binaryDecodeArray(JSON_ARRAY_FACTORY, DataType.JSON, index, len, buff); case JSONB: return binaryDecodeJSONB(index, len, buff); case JSONB_ARRAY: return binaryDecodeArray(JSON_ARRAY_FACTORY, DataType.JSONB, index, len, buff); case POINT: return binaryDecodePoint(index, len, buff); case POINT_ARRAY: return binaryDecodeArray(POINT_ARRAY_FACTORY, DataType.POINT, index, len, buff); case LINE: return binaryDecodeLine(index, len, buff); case LINE_ARRAY: return binaryDecodeArray(LINE_ARRAY_FACTORY, DataType.LINE, index, len, buff); case LSEG: return binaryDecodeLseg(index, len, buff); case LSEG_ARRAY: return binaryDecodeArray(LSEG_ARRAY_FACTORY, DataType.LSEG, index, len, buff); case BOX: return binaryDecodeBox(index, len, buff); case BOX_ARRAY: return binaryDecodeArray(BOX_ARRAY_FACTORY, DataType.BOX, index, len, buff); case PATH: return binaryDecodePath(index, len, buff); case PATH_ARRAY: return binaryDecodeArray(PATH_ARRAY_FACTORY, DataType.PATH, index, len, buff); case POLYGON: return binaryDecodePolygon(index, len, buff); case POLYGON_ARRAY: return binaryDecodeArray(POLYGON_ARRAY_FACTORY, DataType.POLYGON, index, len, buff); case CIRCLE: return binaryDecodeCircle(index, len, buff); case CIRCLE_ARRAY: return binaryDecodeArray(CIRCLE_ARRAY_FACTORY, DataType.CIRCLE, index, len, buff); case INTERVAL: return binaryDecodeINTERVAL(index, len, buff); case INTERVAL_ARRAY: return binaryDecodeArray(INTERVAL_ARRAY_FACTORY, DataType.INTERVAL, index, len, buff); default: logger.warn("Data type " + id + " does not support binary decoding"); return defaultDecodeBinary(index, len, buff); } } public static Object decodeText(DataType id, int index, int len, ByteBuf buff) { switch (id) { case BOOL: return textDecodeBOOL(index, len, buff); case BOOL_ARRAY: return textDecodeArray(BOOLEAN_ARRAY_FACTORY, DataType.BOOL, index, len, buff); case INT2: return textDecodeINT2(index, len, buff); case INT2_ARRAY: return textDecodeArray(SHORT_ARRAY_FACTORY, DataType.INT2, index, len, buff); case INT4: return textDecodeINT4(index, len, buff); case INT4_ARRAY: return textDecodeArray(INTEGER_ARRAY_FACTORY, DataType.INT4, index, len, buff); case INT8: return textDecodeINT8(index, len, buff); case INT8_ARRAY: return textDecodeArray(LONG_ARRAY_FACTORY, DataType.INT8, index, len, buff); case FLOAT4: return textDecodeFLOAT4(index, len, buff); case FLOAT4_ARRAY: return textDecodeArray(FLOAT_ARRAY_FACTORY, DataType.FLOAT4, index, len, buff); case FLOAT8: return textDecodeFLOAT8(index, len, buff); case FLOAT8_ARRAY: return textDecodeArray(DOUBLE_ARRAY_FACTORY, DataType.FLOAT8, index, len, buff); case CHAR: return textDecodeCHAR(index, len, buff); // case CHAR_ARRAY: // return textDecodeCHAR_ARRAY(len, buff); case VARCHAR: return textDecodeVARCHAR(index, len, buff); case VARCHAR_ARRAY: return textDecodeArray(STRING_ARRAY_FACTORY, DataType.VARCHAR, index, len, buff); case BPCHAR: return textDecodeBPCHAR(index, len, buff); case BPCHAR_ARRAY: return textDecodeArray(STRING_ARRAY_FACTORY, DataType.BPCHAR, index, len, buff); case TEXT: return textdecodeTEXT(index, len, buff); case TEXT_ARRAY: return textDecodeArray(STRING_ARRAY_FACTORY, DataType.TEXT, index, len, buff); case NAME: return textDecodeNAME(index, len, buff); case NAME_ARRAY: return textDecodeArray(STRING_ARRAY_FACTORY, DataType.NAME, index, len, buff); case DATE: return textDecodeDATE(index, len, buff); case DATE_ARRAY: return textDecodeArray(LOCALDATE_ARRAY_FACTORY, DataType.DATE, index, len, buff); case TIME: return textDecodeTIME(index, len, buff); case TIME_ARRAY: return textDecodeArray(LOCALTIME_ARRAY_FACTORY, DataType.TIME, index, len, buff); case TIMETZ: return textDecodeTIMETZ(index, len, buff); case TIMETZ_ARRAY: return textDecodeArray(OFFSETTIME_ARRAY_FACTORY, DataType.TIMETZ, index, len, buff); case TIMESTAMP: return textDecodeTIMESTAMP(index, len, buff); case TIMESTAMP_ARRAY: return textDecodeArray(LOCALDATETIME_ARRAY_FACTORY, DataType.TIMESTAMP, index, len, buff); case TIMESTAMPTZ: return textDecodeTIMESTAMPTZ(index, len, buff); case TIMESTAMPTZ_ARRAY: return textDecodeArray(OFFSETDATETIME_ARRAY_FACTORY, DataType.TIMESTAMPTZ, index, len, buff); case BYTEA: return textDecodeBYTEA(index, len, buff); case BYTEA_ARRAY: return textDecodeArray(BUFFER_ARRAY_FACTORY, DataType.BYTEA, index, len, buff); case UUID: return textDecodeUUID(index, len, buff); case UUID_ARRAY: return textDecodeArray(UUID_ARRAY_FACTORY, DataType.UUID, index, len, buff); case NUMERIC: return textDecodeNUMERIC(index, len, buff); case NUMERIC_ARRAY: return textDecodeArray(NUMERIC_ARRAY_FACTORY, DataType.NUMERIC, index, len, buff); case JSON: return textDecodeJSON(index, len, buff); case JSON_ARRAY: return textDecodeArray(JSON_ARRAY_FACTORY, DataType.JSON, index, len, buff); case JSONB: return textDecodeJSONB(index, len, buff); case JSONB_ARRAY: return textDecodeArray(JSON_ARRAY_FACTORY, DataType.JSONB, index, len, buff); case POINT: return textDecodePOINT(index, len, buff); case POINT_ARRAY: return textDecodeArray(POINT_ARRAY_FACTORY, DataType.POINT, index, len, buff); case LINE: return textDecodeLine(index, len, buff); case LINE_ARRAY: return textDecodeArray(LINE_ARRAY_FACTORY, DataType.LINE, index, len, buff); case LSEG: return textDecodeLseg(index, len, buff); case LSEG_ARRAY: return textDecodeArray(LSEG_ARRAY_FACTORY, DataType.LSEG, index, len, buff); case BOX: return textDecodeBox(index, len, buff); case BOX_ARRAY: return textDecodeBoxArray(BOX_ARRAY_FACTORY, index, len, buff); case PATH: return textDecodePath(index, len, buff); case PATH_ARRAY: return textDecodeArray(PATH_ARRAY_FACTORY, DataType.PATH, index, len, buff); case POLYGON: return textDecodePolygon(index, len, buff); case POLYGON_ARRAY: return textDecodeArray(POLYGON_ARRAY_FACTORY, DataType.POLYGON, index, len, buff); case CIRCLE: return textDecodeCircle(index, len, buff); case CIRCLE_ARRAY: return textDecodeArray(CIRCLE_ARRAY_FACTORY, DataType.CIRCLE, index, len, buff); case INTERVAL: return textDecodeINTERVAL(index, len, buff); case INTERVAL_ARRAY: return textDecodeArray(INTERVAL_ARRAY_FACTORY, DataType.INTERVAL, index, len, buff); default: return defaultDecodeText(index, len, buff); } } public static Object prepare(DataType type, Object value) { switch (type) { case JSON: case JSONB: if (value == null || value instanceof Json) { return value; } else if (value instanceof String || value instanceof Boolean || value instanceof Number) { return Json.create(value); } else { return REFUSED_SENTINEL; } case UNKNOWN: if (value instanceof String[]) { return Arrays.stream((String[]) value).collect(Collectors.joining(",", "{", "}")); } else if (value == null || value instanceof String) { return value; } else { return REFUSED_SENTINEL; } default: Class javaType = type.decodingType; return value == null || javaType.isInstance(value) ? value : REFUSED_SENTINEL; } } private static Object defaultDecodeText(int index, int len, ByteBuf buff) { // decode unknown text values as text or as an array if it begins with `{` if (len > 1 && buff.getByte(index) == '{') { return textDecodeArray(STRING_ARRAY_FACTORY, DataType.TEXT, index, len, buff); } return textdecodeTEXT(index, len, buff); } private static void defaultEncodeBinary(Object value, ByteBuf buff) { // Default to null buff.writeInt(-1); } private static Object defaultDecodeBinary(int index, int len, ByteBuf buff) { // Default to null return null; } private static void binaryEncodeBOOL(Boolean value, ByteBuf buff) { buff.writeBoolean(value); } private static Boolean binaryDecodeBOOL(int index, int len, ByteBuf buff) { return buff.getBoolean(index); } private static Boolean textDecodeBOOL(int index, int len, ByteBuf buff) { if(buff.getByte(index) == 't') { return Boolean.TRUE; } else { return Boolean.FALSE; } } private static Short textDecodeINT2(int index, int len, ByteBuf buff) { return (short) DataTypeCodec.decodeDecStringToLong(index, len, buff); } private static Short binaryDecodeINT2(int index, int len, ByteBuf buff) { return buff.getShort(index); } private static void binaryEncodeINT2(Number value, ByteBuf buff) { buff.writeShort(value.shortValue()); } private static Integer textDecodeINT4(int index, int len, ByteBuf buff) { return (int) decodeDecStringToLong(index, len, buff); } private static Integer binaryDecodeINT4(int index, int len, ByteBuf buff) { return buff.getInt(index); } private static void binaryEncodeINT4(Number value, ByteBuf buff) { buff.writeInt(value.intValue()); } private static Long textDecodeINT8(int index, int len, ByteBuf buff) { return decodeDecStringToLong(index, len, buff); } private static Long binaryDecodeINT8(int index, int len, ByteBuf buff) { return buff.getLong(index); } private static void binaryEncodeINT8(Number value, ByteBuf buff) { buff.writeLong(value.longValue()); } private static Float textDecodeFLOAT4(int index, int len, ByteBuf buff) { // Todo optimize that CharSequence cs = buff.getCharSequence(index, len, StandardCharsets.UTF_8); return Float.parseFloat(cs.toString()); } private static Float binaryDecodeFLOAT4(int index, int len, ByteBuf buff) { return buff.getFloat(index); } private static void binaryEncodeFLOAT4(Number value, ByteBuf buff) { buff.writeFloat(value.floatValue()); } private static void binaryEncodeFLOAT8(Number value, ByteBuf buff) { buff.writeDouble(value.doubleValue()); } private static Double binaryDecodeFLOAT8(int index, int len, ByteBuf buff) { return buff.getDouble(index); } private static double textDecodeFLOAT8(int index, int len, ByteBuf buff) { // Todo optimize that CharSequence cs = buff.getCharSequence(index, len, StandardCharsets.UTF_8); return Double.parseDouble(cs.toString()); } private static Number textDecodeNUMERIC(int index, int len, ByteBuf buff) { // Todo optimize that CharSequence cs = buff.getCharSequence(index, len, StandardCharsets.UTF_8); return Numeric.parse(cs.toString()); } private static Point textDecodePOINT(int index, int len, ByteBuf buff) { // Point representation: (x,y) int idx = ++index; int s = buff.indexOf(idx, idx + len, (byte) ','); int t = s - idx; double x = textDecodeFLOAT8(idx, t, buff); double y = textDecodeFLOAT8(s + 1, len - t - 3, buff); return new Point(x, y); } private static Line textDecodeLine(int index, int len, ByteBuf buff) { // Line representation: {a,b,c} int idxOfFirstSeparator = buff.indexOf(index, index + len, (byte) ','); int idxOfLastSeparator = buff.indexOf(index + len, index, (byte) ','); int idx = index + 1; double a = textDecodeFLOAT8(idx, idxOfFirstSeparator - idx, buff); double b = textDecodeFLOAT8(idxOfFirstSeparator + 1, idxOfLastSeparator - idxOfFirstSeparator - 1, buff); double c = textDecodeFLOAT8(idxOfLastSeparator + 1, index + len - idxOfLastSeparator - 2, buff); return new Line(a, b, c); } private static LineSegment textDecodeLseg(int index, int len, ByteBuf buff) { // Lseg representation: [p1,p2] int idxOfPointsSeparator = buff.indexOf(index, index+len, (byte) ')') + 1; int lenOfP1 = idxOfPointsSeparator - index - 1; Point p1 = textDecodePOINT(index + 1, lenOfP1, buff); Point p2 = textDecodePOINT(idxOfPointsSeparator + 1, len - lenOfP1 - 3, buff); return new LineSegment(p1, p2); } private static Box textDecodeBox(int index, int len, ByteBuf buff) { // Box representation: p1,p2 int idxOfPointsSeparator = buff.indexOf(index, index+len, (byte) ')') + 1; int lenOfUpperRightCornerPoint = idxOfPointsSeparator - index; Point upperRightCorner = textDecodePOINT(index, lenOfUpperRightCornerPoint, buff); Point lowerLeftCorner = textDecodePOINT(idxOfPointsSeparator + 1, len - lenOfUpperRightCornerPoint - 1, buff); return new Box(upperRightCorner, lowerLeftCorner); } private static Box[] textDecodeBoxArray(IntFunction supplier, int index, int len, ByteBuf buff) { // Box Array representation: {box1;box2;...boxN} List boxes = new ArrayList<>(); int start = index + 1; int end = index + len - 1; while (start < end) { int idxOfBoxSeparator = buff.indexOf(start, end + 1, (byte) ';'); if (idxOfBoxSeparator == -1) { // the last box Box box = textDecodeBox(start, end - start, buff); boxes.add(box); break; } int lenOfBox = idxOfBoxSeparator - start; Box box = textDecodeBox(start, lenOfBox, buff); boxes.add(box); start = idxOfBoxSeparator + 1; } return boxes.toArray(supplier.apply(boxes.size())); } private static Path textDecodePath(int index, int len, ByteBuf buff) { // Path representation: (p1,p2...pn) or [p1,p2...pn] byte first = buff.getByte(index); byte last = buff.getByte(index + len - 1); boolean isOpen; if (first == '(' && last == ')') { isOpen = false; } else if (first == '[' && last == ']') { isOpen = true; } else { throw new DecoderException("Decoding Path is in wrong syntax"); } List points = textDecodeMultiplePoints(index + 1, len - 2, buff); return new Path(isOpen, points); } private static Polygon textDecodePolygon(int index, int len, ByteBuf buff) { // Polygon representation: (p1,p2...pn) List points = textDecodeMultiplePoints(index + 1, len - 2, buff); return new Polygon(points); } // this might be useful for decoding Lseg, Box, Path, Polygon Data Type. private static List textDecodeMultiplePoints(int index, int len, ByteBuf buff) { // representation: p1,p2,p3...pn List points = new ArrayList<>(); int start = index; int end = index + len - 1; while (start < end) { int rightParenthesis = buff.indexOf(start, end + 1, (byte) ')'); int idxOfPointSeparator = rightParenthesis + 1; int lenOfPoint = idxOfPointSeparator - start; Point point = textDecodePOINT(start, lenOfPoint, buff); points.add(point); start = idxOfPointSeparator + 1; } return points; } private static Circle textDecodeCircle(int index, int len, ByteBuf buff) { // Circle representation: int idxOfLastComma = buff.indexOf(index + len - 1, index, (byte) ','); int lenOfPoint = idxOfLastComma - index - 1; Point center = textDecodePOINT(index + 1, lenOfPoint, buff); int lenOfRadius = len - lenOfPoint - 3; double radius = textDecodeFLOAT8(idxOfLastComma + 1, lenOfRadius, buff); return new Circle(center, radius); } private static Interval textDecodeINTERVAL(int index, int len, ByteBuf buff) { CharSequence cs = buff.getCharSequence(index, len, StandardCharsets.UTF_8); String value = cs.toString(); int years = 0, months = 0, days = 0, hours = 0, minutes = 0, seconds = 0, microseconds = 0; final List chunks = new ArrayList<>(7); int idx = 0; for (;;) { int newIdx = value.indexOf(' ', idx); if (newIdx == -1) { chunks.add(value.substring(idx)); break; } chunks.add(value.substring(idx, newIdx)); idx = newIdx + 1; } boolean hasTime = chunks.size() % 2 == 1; int dateChunkMax = hasTime ? chunks.size() - 1 : chunks.size(); for (int i = 0; i < dateChunkMax; i += 2) { int val = Integer.parseInt(chunks.get(i)); switch (chunks.get(i + 1)) { case "year": case "years": years = val; break; case "mon": case "mons": months = val; break; case "day": case "days": days = val; break; } } if (hasTime) { String timeChunk = chunks.get(chunks.size() - 1); boolean isNeg = timeChunk.charAt(0) == '-'; if (isNeg) timeChunk = timeChunk.substring(1); int sidx = 0; for (;;) { int newIdx = timeChunk.indexOf(':', sidx); if (newIdx == -1) { int m = timeChunk.substring(sidx).indexOf('.'); if(m == -1) { // seconds without microseconds seconds = isNeg ? -Integer.parseInt(timeChunk.substring(sidx)) : Integer.parseInt(timeChunk.substring(sidx)); } else { // seconds with microseconds seconds = isNeg ? -Integer.parseInt(timeChunk.substring(sidx).substring(0, m)) : Integer.parseInt(timeChunk.substring(sidx).substring(0, m)); microseconds = isNeg ? -Integer.parseInt(timeChunk.substring(sidx).substring(m + 1)) : Integer.parseInt(timeChunk.substring(sidx).substring(m + 1)); } break; } // hours if(sidx == 0) { hours = isNeg ? -Integer.parseInt(timeChunk.substring(sidx, newIdx)) : Integer.parseInt(timeChunk.substring(sidx, newIdx)); } else { // minutes minutes = isNeg ? -Integer.parseInt(timeChunk.substring(sidx, newIdx)) : Integer.parseInt(timeChunk.substring(sidx, newIdx)); } sidx = newIdx + 1; } } return new Interval(years, months, days, hours, minutes, seconds, microseconds); } private static void textEncodeNUMERIC(Number value, ByteBuf buff) { String s = value.toString(); buff.writeCharSequence(s, StandardCharsets.UTF_8); } private static void textEncodeNUMERIC_ARRAY(Number[] value, ByteBuf buff) { textEncodeArray(value, DataType.NUMERIC, buff); } private static void binaryEncodeCHAR(String value, ByteBuf buff) { binaryEncodeTEXT(value, buff); } private static String textDecodeCHAR(int index, int len, ByteBuf buff) { return buff.getCharSequence(index, len, StandardCharsets.UTF_8).toString(); } private static String binaryDecodeCHAR(int index, int len, ByteBuf buff) { return binaryDecodeTEXT(index, len, buff); } private static void binaryEncodeVARCHAR(String value, ByteBuf buff) { String s = String.valueOf(value); buff.writeCharSequence(s, StandardCharsets.UTF_8); } private static String textDecodeVARCHAR(int index, int len, ByteBuf buff) { return buff.getCharSequence(index, len, StandardCharsets.UTF_8).toString(); } private static String binaryDecodeVARCHAR(int index, int len, ByteBuf buff) { return buff.getCharSequence(index, len, StandardCharsets.UTF_8).toString(); } private static String textDecodeBPCHAR(int index, int len, ByteBuf buff) { return buff.getCharSequence(index, len, StandardCharsets.UTF_8).toString(); } private static void binaryEncodeBPCHAR(String value, ByteBuf buff) { buff.writeCharSequence(value, StandardCharsets.UTF_8); } private static String binaryDecodeBPCHAR(int index, int len, ByteBuf buff) { return buff.getCharSequence(index, len, StandardCharsets.UTF_8).toString(); } private static String textdecodeTEXT(int index, int len, ByteBuf buff) { return buff.getCharSequence(index, len, StandardCharsets.UTF_8).toString(); } private static void binaryEncodeTEXT(String value, ByteBuf buff) { String s = String.valueOf(value); buff.writeCharSequence(s, StandardCharsets.UTF_8); } private static String binaryDecodeTEXT(int index, int len, ByteBuf buff) { return buff.getCharSequence(index, len, StandardCharsets.UTF_8).toString(); } private static String textDecodeNAME(int index, int len, ByteBuf buff) { return buff.getCharSequence(index, len, StandardCharsets.UTF_8).toString(); } private static void binaryEncodeNAME(String value, ByteBuf buff) { String s = String.valueOf(value); buff.writeCharSequence(s, StandardCharsets.UTF_8); } private static String binaryDecodeNAME(int index, int len, ByteBuf buff) { return buff.getCharSequence(index, len, StandardCharsets.UTF_8).toString(); } private static void binaryEncodeDATE(LocalDate value, ByteBuf buff) { buff.writeInt((int) -value.until(LOCAL_DATE_EPOCH, ChronoUnit.DAYS)); } private static LocalDate binaryDecodeDATE(int index, int len, ByteBuf buff) { return LOCAL_DATE_EPOCH.plus(buff.getInt(index), ChronoUnit.DAYS); } private static LocalDate textDecodeDATE(int index, int len, ByteBuf buff) { CharSequence cs = buff.getCharSequence(index, len, StandardCharsets.UTF_8); return LocalDate.parse(cs); } private static void binaryEncodeTIME(LocalTime value, ByteBuf buff) { buff.writeLong(value.getLong(ChronoField.MICRO_OF_DAY)); } private static LocalTime binaryDecodeTIME(int index, int len, ByteBuf buff) { // micros to nanos return LocalTime.ofNanoOfDay(buff.getLong(index) * 1000); } private static LocalTime textDecodeTIME(int index, int len, ByteBuf buff) { CharSequence cs = buff.getCharSequence(index, len, StandardCharsets.UTF_8); return LocalTime.parse(cs); } private static void binaryEncodeTIMETZ(OffsetTime value, ByteBuf buff) { buff.writeLong(value.toLocalTime().getLong(ChronoField.MICRO_OF_DAY)); // zone offset in seconds (should we change it to UTC ?) buff.writeInt(-value.getOffset().getTotalSeconds()); } private static OffsetTime binaryDecodeTIMETZ(int index, int len, ByteBuf buff) { // micros to nanos return OffsetTime.of(LocalTime.ofNanoOfDay(buff.getLong(index) * 1000), // zone offset in seconds (should we change it to UTC ?) ZoneOffset.ofTotalSeconds(-buff.getInt(index + 8))); } private static OffsetTime textDecodeTIMETZ(int index, int len, ByteBuf buff) { CharSequence cs = buff.getCharSequence(index, len, StandardCharsets.UTF_8); return OffsetTime.parse(cs, TimeFormatter.TIMETZ_FORMAT); } private static void binaryEncodeTIMESTAMP(LocalDateTime value, ByteBuf buff) { buff.writeLong(-value.until(LOCAL_DATE_TIME_EPOCH, ChronoUnit.MICROS)); } private static LocalDateTime binaryDecodeTIMESTAMP(int index, int len, ByteBuf buff) { return LOCAL_DATE_TIME_EPOCH.plus(buff.getLong(index), ChronoUnit.MICROS); } private static LocalDateTime textDecodeTIMESTAMP(int index, int len, ByteBuf buff) { CharSequence cs = buff.getCharSequence(index, len, StandardCharsets.UTF_8); return LocalDateTime.parse(cs, DateTimeFormatter.TIMESTAMP_FORMAT); } private static OffsetDateTime binaryDecodeTIMESTAMPTZ(int index, int len, ByteBuf buff) { return OFFSET_DATE_TIME_EPOCH.plus(buff.getLong(index), ChronoUnit.MICROS); } private static void binaryEncodeTIMESTAMPTZ(OffsetDateTime value, ByteBuf buff) { buff.writeLong(-value.until(OFFSET_DATE_TIME_EPOCH, ChronoUnit.MICROS)); } private static OffsetDateTime textDecodeTIMESTAMPTZ(int index, int len, ByteBuf buff) { CharSequence cs = buff.getCharSequence(index, len, StandardCharsets.UTF_8); return OffsetDateTime.parse(cs, DateTimeFormatter.TIMESTAMPTZ_FORMAT); } private static Buffer textDecodeBYTEA(int index, int len, ByteBuf buff) { if (isHexFormat(index, len, buff)) { // hex format // Shift 2 bytes: skip \x prolog return decodeHexStringToBytes(index + 2, len - 2, buff); } else { // escape format return decodeEscapeByteaStringToBuffer(index, len, buff); } } private static void binaryEncodeBYTEA(Buffer value, ByteBuf buff) { ByteBuf byteBuf = value.getByteBuf(); buff.writeBytes(byteBuf); } private static Buffer binaryDecodeBYTEA(int index, int len, ByteBuf buff) { return Buffer.buffer(buff.copy(index, len)); } private static void binaryEncodeUUID(UUID uuid, ByteBuf buff) { buff.writeLong(uuid.getMostSignificantBits()); buff.writeLong(uuid.getLeastSignificantBits()); } private static void binaryEncodePoint(Point point, ByteBuf buff) { binaryEncodeFLOAT8(point.x, buff); binaryEncodeFLOAT8(point.y, buff); } private static Point binaryDecodePoint(int index, int len, ByteBuf buff) { double x = binaryDecodeFLOAT8(index, 8, buff); double y = binaryDecodeFLOAT8(index + 8, 8, buff); return new Point(x, y); } private static void binaryEncodeLine(Line line, ByteBuf buff) { binaryEncodeFLOAT8(line.getA(), buff); binaryEncodeFLOAT8(line.getB(), buff); binaryEncodeFLOAT8(line.getC(), buff); } private static Line binaryDecodeLine(int index, int len, ByteBuf buff) { double a = binaryDecodeFLOAT8(index, 8, buff); double b = binaryDecodeFLOAT8(index + 8, 8, buff); double c = binaryDecodeFLOAT8(index + 16, 8, buff); return new Line(a, b, c); } private static void binaryEncodeLseg(LineSegment lseg, ByteBuf buff) { binaryEncodePoint(lseg.getP1(), buff); binaryEncodePoint(lseg.getP2(), buff); } private static LineSegment binaryDecodeLseg(int index, int len, ByteBuf buff) { Point p1 = binaryDecodePoint(index, 16, buff); Point p2 = binaryDecodePoint(index + 16, 16, buff); return new LineSegment(p1, p2); } private static void binaryEncodeBox(Box box, ByteBuf buff) { binaryEncodePoint(box.getUpperRightCorner(), buff); binaryEncodePoint(box.getLowerLeftCorner(), buff); } private static Box binaryDecodeBox(int index, int len, ByteBuf buff) { Point upperRightCorner = binaryDecodePoint(index, 16, buff); Point lowerLeftCorner = binaryDecodePoint(index + 16, 16, buff); return new Box(upperRightCorner, lowerLeftCorner); } private static void binaryEncodePath(Path path, ByteBuf buff) { if (path.isOpen()) { buff.writeByte(0); } else { buff.writeByte(1); } List points = path.getPoints(); binaryEncodeINT4(points.size(), buff); for (Point point : points) { binaryEncodePoint(point, buff); } } private static Path binaryDecodePath(int index, int len, ByteBuf buff) { byte first = buff.getByte(index); boolean isOpen; if (first == 0) { isOpen = true; } else if (first == 1) { isOpen = false; } else { throw new DecoderException("Decoding Path exception"); } int idx = ++index; int numberOfPoints = binaryDecodeINT4(idx, 4, buff); idx += 4; List points = new ArrayList<>(); // maybe we need some check? for (int i = 0; i < numberOfPoints; i++) { points.add(binaryDecodePoint(idx, 16, buff)); idx += 16; } return new Path(isOpen, points); } private static void binaryEncodePolygon(Polygon polygon, ByteBuf buff) { List points = polygon.getPoints(); int numberOfPoints = points.size(); binaryEncodeINT4(numberOfPoints, buff); for (Point point : points) { binaryEncodeFLOAT8(point.x, buff); binaryEncodeFLOAT8(point.y, buff); } } private static Polygon binaryDecodePolygon(int index, int len, ByteBuf buff) { int idx = index; int numberOfPoints = binaryDecodeINT4(index, 4, buff); idx += 4; List points = new ArrayList<>(); for (int i = 0; i < numberOfPoints; i++) { points.add(binaryDecodePoint(idx, 16, buff)); idx += 16; } return new Polygon(points); } private static void binaryEncodeCircle(Circle circle, ByteBuf buff) { binaryEncodePoint(circle.getCenterPoint(), buff); binaryEncodeFLOAT8(circle.getRadius(), buff); } private static Circle binaryDecodeCircle(int index, int len, ByteBuf buff) { Point center = binaryDecodePoint(index, 16, buff); double radius = binaryDecodeFLOAT8(index + 16, 8, buff); return new Circle(center, radius); } private static void binaryEncodeINTERVAL(Interval interval, ByteBuf buff) { Duration duration = Duration .ofHours(interval.getHours()) .plusMinutes(interval.getMinutes()) .plusSeconds(interval.getSeconds()) .plus(interval.getMicroseconds(), ChronoUnit.MICROS); // days won't be changed Period monthYear = Period.of(interval.getYears(), interval.getMonths(), interval.getDays()).normalized(); binaryEncodeINT8(NANOSECONDS.toMicros(duration.toNanos()), buff); binaryEncodeINT4(monthYear.getDays(), buff); binaryEncodeINT4((int) monthYear.toTotalMonths(), buff); } private static Interval binaryDecodeINTERVAL(int index, int len, ByteBuf buff) { Duration duration = Duration.of(buff.getLong(index), ChronoUnit.MICROS); final long hours = duration.toHours(); duration = duration.minusHours(hours); final long minutes = duration.toMinutes(); duration = duration.minusMinutes(minutes); final long seconds = NANOSECONDS.toSeconds(duration.toNanos()); duration = duration.minusSeconds(seconds); final long microseconds = NANOSECONDS.toMicros(duration.toNanos()); int days = buff.getInt(index + 8); int months = buff.getInt(index + 12); Period monthYear = Period.of(0, months, days).normalized(); return new Interval(monthYear.getYears(), monthYear.getMonths(), monthYear.getDays(), (int) hours, (int) minutes, (int) seconds, (int) microseconds); } private static UUID binaryDecodeUUID(int index, int len, ByteBuf buff) { return new UUID(buff.getLong(index), buff.getLong(index + 8)); } private static UUID textDecodeUUID(int index, int len, ByteBuf buff) { return java.util.UUID.fromString(buff.getCharSequence(index, len, StandardCharsets.UTF_8).toString()); } private static Json textDecodeJSON(int index, int len, ByteBuf buff) { return textDecodeJSONB(index, len, buff); } private static Json binaryDecodeJSON(int index, int len, ByteBuf buff) { return textDecodeJSONB(index, len, buff); } private static void binaryEncodeJSON(Json value, ByteBuf buff) { String s = io.vertx.core.json.Json.encode(value.value()); buff.writeCharSequence(s, StandardCharsets.UTF_8); } private static Json textDecodeJSONB(int index, int len, ByteBuf buff) { // Try to do without the intermediary String (?) CharSequence cs = buff.getCharSequence(index, len, StandardCharsets.UTF_8); Object value = null; String s = cs.toString(); int pos = 0; while (pos < s.length() && Character.isWhitespace(s.charAt(pos))) { pos++; } if (pos == s.length()) { return null; } else if (s.charAt(pos) == '{') { value = new JsonObject(s); } else if (s.charAt(pos) == '[') { value = new JsonArray(s); } else { try { JsonNode jsonNode = io.vertx.core.json.Json.mapper.readTree(s); if (jsonNode.isNumber()) { value = jsonNode.numberValue(); } else if (jsonNode.isBoolean()) { value = jsonNode.booleanValue(); } else if (jsonNode.isTextual()) { value = jsonNode.textValue(); } } catch (IOException e) { // do nothing } } return Json.create(value); } private static Json binaryDecodeJSONB(int index, int len, ByteBuf buff) { // Skip 1 byte for version (which is 1) return textDecodeJSONB(index + 1, len - 1, buff); } private static void binaryEncodeJSONB(Json value, ByteBuf buff) { String s = io.vertx.core.json.Json.encode(value.value()); buff.writeByte(1); // version buff.writeCharSequence(s, StandardCharsets.UTF_8); } /** * Decode the specified {@code buff} formatted as a decimal string starting at the readable index * with the specified {@code length} to a long. * * @param index the hex string index * @param len the hex string length * @param buff the byte buff to read from * @return the decoded value as a long */ private static long decodeDecStringToLong(int index, int len, ByteBuf buff) { long value = 0; if (len > 0) { int to = index + len; boolean neg = false; if (buff.getByte(index) == '-') { neg = true; index++; } while (index < to) { byte ch = buff.getByte(index++); byte nibble = (byte)(ch - '0'); value = value * 10 + nibble; } if (neg) { value = -value; } } return value; } /** * Decode the specified {@code buff} formatted as an hex string starting at the buffer readable index * with the specified {@code length} to a {@link Buffer}. * * @param len the hex string length * @param buff the byte buff to read from * @return the decoded value as a Buffer */ private static Buffer decodeHexStringToBytes(int index, int len, ByteBuf buff) { len = len >> 1; Buffer buffer = Buffer.buffer(len); for (int i = 0; i < len; i++) { byte b0 = decodeHexChar(buff.getByte(index++)); byte b1 = decodeHexChar(buff.getByte(index++)); buffer.appendByte((byte) (b0 * 16 + b1)); } return buffer; } private static byte decodeHexChar(byte ch) { return (byte)(((ch & 0x1F) + ((ch >> 6) * 0x19) - 0x10) & 0x0F); } private static boolean isHexFormat(int index, int len, ByteBuf buff) { return len >= 2 && buff.getByte(index) == '\\' && buff.getByte(index + 1) == 'x'; } private static Buffer decodeEscapeByteaStringToBuffer(int index, int len, ByteBuf buff) { Buffer buffer = Buffer.buffer(); int pos = 0; while (pos < len) { byte current = buff.getByte(pos + index); if (current == '\\') { if (pos + 2 <= len && buff.getByte(pos + index + 1) == '\\') { // check double backslashes buffer.appendByte((byte) '\\'); pos += 2; } else if (pos + 4 <= len) { // a preceded backslash with three-digit octal value int high = Character.digit(buff.getByte(pos + index + 1), 8) << 6; int medium = Character.digit(buff.getByte(pos + index + 2), 8) << 3; int low = Character.digit(buff.getByte(pos + index + 3), 8); int escapedValue = high + medium + low; buffer.appendByte((byte) escapedValue); pos += 4; } else { throw new DecoderException("Decoding unexpected BYTEA escape format"); } } else { // printable octets buffer.appendByte(current); pos++; } } return buffer; } private static T[] binaryDecodeArray(IntFunction supplier, DataType type, int index, int len, ByteBuf buff) { if (len == 12) { return supplier.apply(0); } int dim = buff.getInt(index); // read ndim index += 4; index += 4; // skip dataoffset index += 4; // skip elemtype int length = buff.getInt(index); // read dimensions index += 4; index += 4; // skip lower bnds if (dim != 1) { logger.warn("Only arrays of dimension 1 are supported"); return null; } T[] array = supplier.apply(length); for (int i = 0; i < array.length; i++) { int l = buff.getInt(index); index += 4; if (l != -1) { array[i] = (T) decodeBinary(type, index, l, buff); index += l; } } return array; } private static void binaryEncodeArray(T[] values, DataType type, ByteBuf buff){ int startIndex = buff.writerIndex(); buff.writeInt(1); // ndim buff.writeInt(0); // dataoffset buff.writeInt(type.id); // elemtype buff.writeInt(values.length); // dimension buff.writeInt(1); // lower bnds boolean hasNulls = false; for (T value : values) { if (value == null) { hasNulls = true; buff.writeInt(-1); } else { int idx = buff.writerIndex(); buff.writeInt(0); encodeBinary(type, value, buff); buff.setInt(idx, buff.writerIndex() - idx - 4); } } if (hasNulls) { buff.setInt(startIndex + 4, 1); } } private static T[] textDecodeArray(IntFunction supplier, DataType type, int index, int len, ByteBuf buff) { List list = new ArrayList<>(); int from = index + 1; // Set index after '{' int to = index + len - 1; // Set index before '}' while (from < to) { // Escaped content ? boolean escaped = buff.getByte(from) == '"'; int idx; if (escaped) { idx = buff.forEachByte(from, to - from, new UTF8StringEndDetector()); idx = buff.indexOf(idx, to, (byte) ','); // SEE iF WE CAN GET RID oF IT } else { idx = buff.indexOf(from, to, (byte) ','); } if (idx == -1) { idx = to; } T elt = textDecodeArrayElement(type, from, idx - from, buff); list.add(elt); from = idx + 1; } return list.toArray(supplier.apply(list.size())); } private static T textDecodeArrayElement(DataType type, int index, int len, ByteBuf buff) { if (len == 4 && Character.toUpperCase(buff.getByte(index)) == 'N' && Character.toUpperCase(buff.getByte(index + 1)) == 'U' && Character.toUpperCase(buff.getByte(index + 2)) == 'L' && Character.toUpperCase(buff.getByte(index + 3)) == 'L' ) { return null; } else { boolean escaped = buff.getByte(index) == '"'; if (escaped) { // Some escaping - improve that later... String s = buff.toString(index + 1, len - 2, StandardCharsets.UTF_8); StringBuilder sb = new StringBuilder(); for (int i = 0;i < s.length();i++) { char c = s.charAt(i); if (c == '\\') { c = s.charAt(++i); } sb.append(c); } buff = Unpooled.copiedBuffer(sb, StandardCharsets.UTF_8); index = 0; len = buff.readableBytes(); } return (T) decodeText(type, index, len, buff); } } private static void textEncodeArray(T[] values, DataType type, ByteBuf buff){ buff.writeByte('{'); int len = values.length; for (int i = 0; i < len; i++) { if (i > 0) { buff.writeByte(','); } T value = values[i]; if (value != null) { textEncode(type, value, buff); } else { buff.writeByte('N'); buff.writeByte('U'); buff.writeByte('L'); buff.writeByte('L'); } } buff.writeByte('}'); } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/TxStatus.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec; /** * * @author Emad Alblueshi * */ public enum TxStatus { IDLE, ACTIVE, FAILED; } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/decoder/ErrorResponse.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.decoder; /** * @author Emad Alblueshi */ public class ErrorResponse extends Response { @Override public String toString() { return "ErrorResponse{" + "severity='" + getSeverity() + '\'' + ", code='" + getCode() + '\'' + ", message='" + getMessage() + '\'' + ", detail='" + getDetail() + '\'' + ", hint='" + getHint() + '\'' + ", position='" + getPosition() + '\'' + ", internalPosition='" + getInternalPosition() + '\'' + ", internalQuery='" + getInternalQuery() + '\'' + ", where='" + getWhere() + '\'' + ", file='" + getFile() + '\'' + ", line='" + getLine() + '\'' + ", routine='" + getRoutine() + '\'' + ", schema='" + getSchema() + '\'' + ", table='" + getTable() + '\'' + ", column='" + getColumn() + '\'' + ", dataType='" + getDataType() + '\'' + ", constraint='" + getConstraint() + '\'' + '}'; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/decoder/InboundMessage.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.decoder; /** * An interface that should be implemented for decoding and encoding messages * * @author Emad Alblueshi */ public interface InboundMessage {} ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/decoder/InitiateSslHandler.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.decoder; import io.reactiverse.pgclient.impl.SocketConnection; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.codec.DecoderException; import io.reactiverse.pgclient.impl.codec.decoder.type.MessageType; import io.vertx.core.Future; import io.vertx.core.VertxException; public class InitiateSslHandler extends ChannelInboundHandlerAdapter { private static final int code = 80877103; private final SocketConnection conn; private final Future upgradeFuture; public InitiateSslHandler(SocketConnection conn, Future upgradeFuture) { this.conn = conn; this.upgradeFuture = upgradeFuture; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ByteBuf byteBuf = Unpooled.buffer(); byteBuf.writeInt(0); byteBuf.writeInt(code); // out.writeInt(0x12345679); byteBuf.setInt(0, byteBuf.writerIndex()); ctx.writeAndFlush(byteBuf); super.channelActive(ctx); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // This must be a single byte buffer - after that follow the SSL handshake ByteBuf byteBuf = (ByteBuf) msg; byte b = byteBuf.getByte(0); byteBuf.release(); switch (b) { case MessageType.SSL_YES: { conn.socket().upgradeToSsl(v -> { ctx.pipeline().remove(this); upgradeFuture.complete(); }); break; } case MessageType.SSL_NO: { upgradeFuture.fail(new Exception("Postgres Server does not handle SSL connection")); break; } default: upgradeFuture.fail(new Exception("Invalid SSL connection message")); break; } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (cause instanceof DecoderException) { DecoderException err = (DecoderException) cause; cause = err.getCause(); } upgradeFuture.tryFail(cause); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); // Work around for https://github.com/eclipse-vertx/vert.x/issues/2748 upgradeFuture.tryFail(new VertxException("SSL handshake failed", true)); } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/decoder/MessageDecoder.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.decoder; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.CompositeByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.reactiverse.pgclient.impl.CommandBase; import io.reactiverse.pgclient.impl.CommandResponse; import io.reactiverse.pgclient.impl.QueryCommandBase; import io.reactiverse.pgclient.impl.codec.ColumnDesc; import io.reactiverse.pgclient.impl.codec.DataFormat; import io.reactiverse.pgclient.impl.codec.DataType; import io.reactiverse.pgclient.impl.codec.TxStatus; import io.reactiverse.pgclient.impl.codec.util.Util; import io.netty.buffer.ByteBuf; import io.netty.util.ByteProcessor; import io.reactiverse.pgclient.impl.codec.decoder.type.AuthenticationType; import io.reactiverse.pgclient.impl.codec.decoder.type.ErrorOrNoticeType; import io.reactiverse.pgclient.impl.codec.decoder.type.MessageType; import io.vertx.core.Handler; import java.util.Deque; /** * * Decoder for PostgreSQL protocol * * @author Emad Alblueshi */ public class MessageDecoder extends ChannelInboundHandlerAdapter { private final Deque> inflight; private final ByteBufAllocator alloc; private Handler> commandResponseHandler; private Handler noticeHandler; private ByteBuf in; public MessageDecoder(Deque> inflight, ByteBufAllocator alloc) { this.inflight = inflight; this.alloc = alloc; } public void run(CommandBase cmd) { cmd.completionHandler = commandResponseHandler; cmd.noticeHandler = noticeHandler; } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { commandResponseHandler = ctx::fireChannelRead; noticeHandler = ctx::fireChannelRead; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf buff = (ByteBuf) msg; if (in == null) { in = buff; } else { CompositeByteBuf composite; if (in instanceof CompositeByteBuf) { composite = (CompositeByteBuf) in; } else { composite = alloc.compositeBuffer(); composite.addComponent(true, in); in = composite; } composite.addComponent(true, buff); } while (true) { int available = in.readableBytes(); if (available < 5) { break; } int beginIdx = in.readerIndex(); int length = in.getInt(beginIdx + 1); if (length + 1 > available) { break; } byte id = in.getByte(beginIdx); int endIdx = beginIdx + length + 1; final int writerIndex = in.writerIndex(); try { in.setIndex(beginIdx + 5, endIdx); switch (id) { case MessageType.READY_FOR_QUERY: { decodeReadyForQuery(in); break; } case MessageType.DATA_ROW: { decodeDataRow(in); break; } case MessageType.COMMAND_COMPLETE: { decodeCommandComplete(in); break; } case MessageType.BIND_COMPLETE: { decodeBindComplete(); break; } default: { decodeMessage(ctx, id, in); } } } finally { in.setIndex(endIdx, writerIndex); } } if (in != null && !in.isReadable()) { in.release(); in = null; } } private void decodeMessage(ChannelHandlerContext ctx, byte id, ByteBuf in) { switch (id) { case MessageType.ROW_DESCRIPTION: { decodeRowDescription(in); break; } case MessageType.ERROR_RESPONSE: { decodeError(in); break; } case MessageType.NOTICE_RESPONSE: { decodeNotice(in); break; } case MessageType.AUTHENTICATION: { decodeAuthentication(in); break; } case MessageType.EMPTY_QUERY_RESPONSE: { decodeEmptyQueryResponse(); break; } case MessageType.PARSE_COMPLETE: { decodeParseComplete(); break; } case MessageType.CLOSE_COMPLETE: { decodeCloseComplete(); break; } case MessageType.NO_DATA: { decodeNoData(); break; } case MessageType.PORTAL_SUSPENDED: { decodePortalSuspended(); break; } case MessageType.PARAMETER_DESCRIPTION: { decodeParameterDescription(in); break; } case MessageType.PARAMETER_STATUS: { decodeParameterStatus(in); break; } case MessageType.BACKEND_KEY_DATA: { decodeBackendKeyData(in); break; } case MessageType.NOTIFICATION_RESPONSE: { decodeNotificationResponse(ctx, in); break; } default: { throw new UnsupportedOperationException(); } } } private void decodePortalSuspended() { inflight.peek().handlePortalSuspended(); } private void decodeCommandComplete(ByteBuf in) { int updated = processor.parse(in); inflight.peek().handleCommandComplete(updated); } private void decodeDataRow(ByteBuf in) { QueryCommandBase cmd = (QueryCommandBase) inflight.peek(); int len = in.readUnsignedShort(); cmd.decoder.decodeRow(len, in); } private void decodeRowDescription(ByteBuf in) { ColumnDesc[] columns = new ColumnDesc[in.readUnsignedShort()]; for (int c = 0; c < columns.length; ++c) { String fieldName = Util.readCStringUTF8(in); int tableOID = in.readInt(); short columnAttributeNumber = in.readShort(); int typeOID = in.readInt(); short typeSize = in.readShort(); int typeModifier = in.readInt(); int textOrBinary = in.readUnsignedShort(); // Useless for now ColumnDesc column = new ColumnDesc( fieldName, tableOID, columnAttributeNumber, DataType.valueOf(typeOID), typeSize, typeModifier, DataFormat.valueOf(textOrBinary) ); columns[c] = column; } RowDescription rowDesc = new RowDescription(columns); inflight.peek().handleRowDescription(rowDesc); } private static final byte I = (byte) 'I', T = (byte) 'T'; private void decodeReadyForQuery(ByteBuf in) { byte id = in.readByte(); TxStatus txStatus; if (id == I) { txStatus = TxStatus.IDLE; } else if (id == T) { txStatus = TxStatus.ACTIVE; } else { txStatus = TxStatus.FAILED; } inflight.peek().handleReadyForQuery(txStatus); } private void decodeError(ByteBuf in) { ErrorResponse response = new ErrorResponse(); decodeErrorOrNotice(response, in); inflight.peek().handleErrorResponse(response); } private void decodeNotice(ByteBuf in) { NoticeResponse response = new NoticeResponse(); decodeErrorOrNotice(response, in); inflight.peek().handleNoticeResponse(response); } private void decodeErrorOrNotice(Response response, ByteBuf in) { byte type; while ((type = in.readByte()) != 0) { switch (type) { case ErrorOrNoticeType.SEVERITY: response.setSeverity(Util.readCStringUTF8(in)); break; case ErrorOrNoticeType.CODE: response.setCode(Util.readCStringUTF8(in)); break; case ErrorOrNoticeType.MESSAGE: response.setMessage(Util.readCStringUTF8(in)); break; case ErrorOrNoticeType.DETAIL: response.setDetail(Util.readCStringUTF8(in)); break; case ErrorOrNoticeType.HINT: response.setHint(Util.readCStringUTF8(in)); break; case ErrorOrNoticeType.INTERNAL_POSITION: response.setInternalPosition(Util.readCStringUTF8(in)); break; case ErrorOrNoticeType.INTERNAL_QUERY: response.setInternalQuery(Util.readCStringUTF8(in)); break; case ErrorOrNoticeType.POSITION: response.setPosition(Util.readCStringUTF8(in)); break; case ErrorOrNoticeType.WHERE: response.setWhere(Util.readCStringUTF8(in)); break; case ErrorOrNoticeType.FILE: response.setFile(Util.readCStringUTF8(in)); break; case ErrorOrNoticeType.LINE: response.setLine(Util.readCStringUTF8(in)); break; case ErrorOrNoticeType.ROUTINE: response.setRoutine(Util.readCStringUTF8(in)); break; case ErrorOrNoticeType.SCHEMA: response.setSchema(Util.readCStringUTF8(in)); break; case ErrorOrNoticeType.TABLE: response.setTable(Util.readCStringUTF8(in)); break; case ErrorOrNoticeType.COLUMN: response.setColumn(Util.readCStringUTF8(in)); break; case ErrorOrNoticeType.DATA_TYPE: response.setDataType(Util.readCStringUTF8(in)); break; case ErrorOrNoticeType.CONSTRAINT: response.setConstraint(Util.readCStringUTF8(in)); break; default: Util.readCStringUTF8(in); break; } } } private void decodeAuthentication(ByteBuf in) { int type = in.readInt(); switch (type) { case AuthenticationType.OK: { inflight.peek().handleAuthenticationOk(); } break; case AuthenticationType.MD5_PASSWORD: { byte[] salt = new byte[4]; in.readBytes(salt); inflight.peek().handleAuthenticationMD5Password(salt); } break; case AuthenticationType.CLEARTEXT_PASSWORD: { inflight.peek().handleAuthenticationClearTextPassword(); } break; case AuthenticationType.KERBEROS_V5: case AuthenticationType.SCM_CREDENTIAL: case AuthenticationType.GSS: case AuthenticationType.GSS_CONTINUE: case AuthenticationType.SSPI: default: throw new UnsupportedOperationException("Authentication type " + type + " is not supported in the client"); } } private CommandCompleteProcessor processor = new CommandCompleteProcessor(); static class CommandCompleteProcessor implements ByteProcessor { private static final byte SPACE = 32; private int rows; boolean afterSpace; int parse(ByteBuf in) { afterSpace = false; rows = 0; in.forEachByte(in.readerIndex(), in.readableBytes() - 1, this); return rows; } @Override public boolean process(byte value) throws Exception { boolean space = value == SPACE; if (afterSpace) { if (space) { rows = 0; } else { rows = rows * 10 + (value - '0'); } } else { afterSpace = space; } return true; } } private void decodeParseComplete() { inflight.peek().handleParseComplete(); } private void decodeBindComplete() { inflight.peek().handleBindComplete(); } private void decodeCloseComplete() { inflight.peek().handleCloseComplete(); } private void decodeNoData() { inflight.peek().handleNoData(); } private void decodeParameterDescription(ByteBuf in) { DataType[] paramDataTypes = new DataType[in.readUnsignedShort()]; for (int c = 0; c < paramDataTypes.length; ++c) { paramDataTypes[c] = DataType.valueOf(in.readInt()); } inflight.peek().handleParameterDescription(new ParameterDescription(paramDataTypes)); } private void decodeParameterStatus(ByteBuf in) { String key = Util.readCStringUTF8(in); String value = Util.readCStringUTF8(in); inflight.peek().handleParameterStatus(key, value); } private void decodeEmptyQueryResponse() { inflight.peek().handleEmptyQueryResponse(); } private void decodeBackendKeyData(ByteBuf in) { int processId = in.readInt(); int secretKey = in.readInt(); inflight.peek().handleBackendKeyData(processId, secretKey); } private void decodeNotificationResponse(ChannelHandlerContext ctx, ByteBuf in) { ctx.fireChannelRead(new NotificationResponse(in.readInt(), Util.readCStringUTF8(in), Util.readCStringUTF8(in))); } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/decoder/NoticeResponse.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.decoder; /** * @author Emad Alblueshi */ public class NoticeResponse extends Response { @Override public String toString() { return "NoticeResponse{" + "severity='" + getSeverity() + '\'' + ", code='" + getCode() + '\'' + ", message='" + getMessage() + '\'' + ", detail='" + getDetail() + '\'' + ", hint='" + getHint() + '\'' + ", position='" + getPosition() + '\'' + ", internalPosition='" + getInternalPosition() + '\'' + ", internalQuery='" + getInternalQuery() + '\'' + ", where='" + getWhere() + '\'' + ", file='" + getFile() + '\'' + ", line='" + getLine() + '\'' + ", routine='" + getRoutine() + '\'' + ", schema='" + getSchema() + '\'' + ", table='" + getTable() + '\'' + ", column='" + getColumn() + '\'' + ", dataType='" + getDataType() + '\'' + ", constraint='" + getConstraint() + '\'' + '}'; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/decoder/NotificationResponse.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.decoder; import java.util.Objects; /** * @author Emad Alblueshi */ public class NotificationResponse { private final int processId; private final String channel; private final String payload; public NotificationResponse(int processId, String channel, String payload) { this.processId = processId; this.channel = channel; this.payload = payload; } public int getProcessId() { return processId; } public String getChannel() { return channel; } public String getPayload() { return payload; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NotificationResponse that = (NotificationResponse) o; return processId == that.processId && Objects.equals(channel, that.channel) && Objects.equals(payload, that.payload); } @Override public int hashCode() { return Objects.hash(processId, channel, payload); } @Override public String toString() { return "NotificationResponse{" + "processId=" + processId + ", channel='" + channel + '\'' + ", payload='" + payload + '\'' + '}'; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/decoder/ParameterDescription.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.decoder; import io.reactiverse.pgclient.impl.codec.DataTypeCodec; import io.reactiverse.pgclient.impl.codec.DataType; import io.reactiverse.pgclient.impl.codec.util.Util; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; /** * @author Emad Alblueshi */ public class ParameterDescription { // OIDs private final DataType[] paramDataTypes; public ParameterDescription(DataType[] paramDataTypes) { this.paramDataTypes = paramDataTypes; } public DataType[] getParamDataTypes() { return paramDataTypes; } public String prepare(List values) { if (values.size() != paramDataTypes.length) { return buildReport(values); } for (int i = 0;i < paramDataTypes.length;i++) { DataType paramDataType = paramDataTypes[i]; Object value = values.get(i); Object val = DataTypeCodec.prepare(paramDataType, value); if (val != value) { if (val == DataTypeCodec.REFUSED_SENTINEL) { return buildReport(values); } else { values.set(i, val); } } } return null; } private String buildReport(List values) { return Util.buildInvalidArgsError(values.stream(), Stream.of(paramDataTypes).map(type -> type.decodingType)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ParameterDescription that = (ParameterDescription) o; return Arrays.equals(paramDataTypes, that.paramDataTypes); } @Override public int hashCode() { return Arrays.hashCode(paramDataTypes); } @Override public String toString() { return "ParameterDescription{" + "paramDataTypes=" + Arrays.toString(paramDataTypes) + '}'; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/decoder/Response.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.decoder; import java.util.Objects; /** * *

        * A common response message for PostgreSQL * Error and Notice Message Fields * * @author Emad Alblueshi */ public abstract class Response { private String severity; private String code; private String message; private String detail; private String hint; private String position; private String internalPosition; private String internalQuery; private String where; private String file; private String line; private String routine; private String schema; private String table; private String column; private String dataType; private String constraint; public String getSeverity() { return severity; } public void setSeverity(String severity) { this.severity = severity; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } public String getHint() { return hint; } public void setHint(String hint) { this.hint = hint; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public String getWhere() { return where; } public void setWhere(String where) { this.where = where; } public String getFile() { return file; } public void setFile(String file) { this.file = file; } public String getLine() { return line; } public void setLine(String line) { this.line = line; } public String getRoutine() { return routine; } public void setRoutine(String routine) { this.routine = routine; } public String getSchema() { return schema; } public void setSchema(String schema) { this.schema = schema; } public String getTable() { return table; } public void setTable(String table) { this.table = table; } public String getColumn() { return column; } public void setColumn(String column) { this.column = column; } public String getDataType() { return dataType; } public void setDataType(String dataType) { this.dataType = dataType; } public String getConstraint() { return constraint; } public void setConstraint(String constraint) { this.constraint = constraint; } public String getInternalPosition() { return internalPosition; } public void setInternalPosition(String internalPosition) { this.internalPosition = internalPosition; } public String getInternalQuery() { return internalQuery; } public void setInternalQuery(String internalQuery) { this.internalQuery = internalQuery; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Response that = (Response) o; return Objects.equals(severity, that.severity) && Objects.equals(code, that.code) && Objects.equals(message, that.message) && Objects.equals(detail, that.detail) && Objects.equals(hint, that.hint) && Objects.equals(position, that.position) && Objects.equals(internalPosition, that.internalPosition) && Objects.equals(internalQuery, that.internalQuery) && Objects.equals(where, that.where) && Objects.equals(file, that.file) && Objects.equals(line, that.line) && Objects.equals(routine, that.routine) && Objects.equals(schema, that.schema) && Objects.equals(table, that.table) && Objects.equals(column, that.column) && Objects.equals(dataType, that.dataType) && Objects.equals(constraint, that.constraint); } @Override public int hashCode() { return Objects.hash(severity, code, message, detail, hint, position, internalPosition, internalQuery, where, file, line, routine, schema, table, column, dataType, constraint); } @Override public String toString() { return "Response{" + "severity='" + severity + '\'' + ", code='" + code + '\'' + ", message='" + message + '\'' + ", detail='" + detail + '\'' + ", hint='" + hint + '\'' + ", position='" + position + '\'' + ", internalPosition='" + internalPosition + '\'' + ", internalQuery='" + internalQuery + '\'' + ", where='" + where + '\'' + ", file='" + file + '\'' + ", line='" + line + '\'' + ", routine='" + routine + '\'' + ", schema='" + schema + '\'' + ", table='" + table + '\'' + ", column='" + column + '\'' + ", dataType='" + dataType + '\'' + ", constraint='" + constraint + '\'' + '}'; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/decoder/RowDecoder.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.decoder; import io.netty.buffer.ByteBuf; public interface RowDecoder { void decodeRow(int len, ByteBuf in); } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/decoder/RowDescription.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.decoder; import io.reactiverse.pgclient.impl.codec.ColumnDesc; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author Emad Alblueshi */ public class RowDescription { private final ColumnDesc[] columns; private final List columnNames; public RowDescription(ColumnDesc[] columns) { this.columns = columns; this.columnNames = Collections.unmodifiableList(Stream.of(columns) .map(ColumnDesc::getName) .collect(Collectors.toList())); } public int columnIndex(String columnName) { if (columnName == null) { throw new NullPointerException("Column name must not be null"); } return columnNames.indexOf(columnName); } public ColumnDesc[] columns() { return columns; } public List columnNames() { return columnNames; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RowDescription that = (RowDescription) o; return Arrays.equals(columns, that.columns); } @Override public int hashCode() { return Arrays.hashCode(columns); } @Override public String toString() { return "RowDescription{" + "columns=" + Arrays.toString(columns) + '}'; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/decoder/type/AuthenticationType.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.decoder.type; /** * @author Emad Alblueshi */ public class AuthenticationType { public static final int OK = 0; public static final int KERBEROS_V5 = 2; public static final int CLEARTEXT_PASSWORD = 3; public static final int MD5_PASSWORD = 5; public static final int SCM_CREDENTIAL = 6; public static final int GSS = 7; public static final int GSS_CONTINUE = 8; public static final int SSPI = 9; } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/decoder/type/CommandCompleteType.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.decoder.type; /** * @author Emad Alblueshi */ public class CommandCompleteType { public static final String INSERT = "INSERT"; public static final String DELETE = "DELETE"; public static final String UPDATE = "UPDATE"; public static final String SELECT = "SELECT"; public static final String MOVE = "MOVE"; public static final String FETCH = "FETCH"; public static final String COPY = "COPY"; } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/decoder/type/ErrorOrNoticeType.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.decoder.type; /** * @author Emad Alblueshi */ public class ErrorOrNoticeType { public static final byte SEVERITY = 'S'; public static final byte CODE = 'C'; public static final byte MESSAGE = 'M'; public static final byte DETAIL = 'D'; public static final byte HINT = 'H'; public static final byte POSITION = 'P'; public static final byte INTERNAL_POSITION = 'p'; public static final byte INTERNAL_QUERY = 'q'; public static final byte WHERE = 'W'; public static final byte FILE = 'F'; public static final byte LINE = 'L'; public static final byte ROUTINE = 'R'; public static final byte SCHEMA = 's'; public static final byte TABLE = 't'; public static final byte COLUMN = 'c'; public static final byte DATA_TYPE = 'd'; public static final byte CONSTRAINT = 'n'; } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/decoder/type/MessageType.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.decoder.type; import io.reactiverse.pgclient.impl.codec.decoder.MessageDecoder; /** * * Backend message types for {@link MessageDecoder} * * @author Emad Alblueshi */ public class MessageType { public static final byte BACKEND_KEY_DATA = 'K'; public static final byte AUTHENTICATION = 'R'; public static final byte ERROR_RESPONSE = 'E'; public static final byte NOTICE_RESPONSE = 'N'; public static final byte NOTIFICATION_RESPONSE = 'A'; public static final byte COMMAND_COMPLETE = 'C'; public static final byte PARAMETER_STATUS = 'S'; public static final byte READY_FOR_QUERY = 'Z'; public static final byte PARAMETER_DESCRIPTION = 't'; public static final byte ROW_DESCRIPTION = 'T'; public static final byte DATA_ROW = 'D'; public static final byte PORTAL_SUSPENDED = 's'; public static final byte NO_DATA = 'n'; public static final byte EMPTY_QUERY_RESPONSE = 'I'; public static final byte PARSE_COMPLETE = '1'; public static final byte BIND_COMPLETE = '2'; public static final byte CLOSE_COMPLETE = '3'; public static final byte FUNCTION_RESULT = 'V'; public static final byte SSL_YES = 'S'; public static final byte SSL_NO = 'N'; } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/encoder/Bind.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.encoder; import io.reactiverse.pgclient.impl.codec.ColumnDesc; import io.reactiverse.pgclient.impl.codec.DataType; /** * @author Emad Alblueshi */ public class Bind { public final long statement; public final DataType[] paramTypes; public final ColumnDesc[] resultColumns; public Bind(long statement, DataType[] paramTypes, ColumnDesc[] resultColumns) { this.statement = statement; this.paramTypes = paramTypes; this.resultColumns = resultColumns; } public long getStatement() { return statement; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/encoder/Describe.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.encoder; /** * @author Emad Alblueshi */ public class Describe { public final long statement; public final String portal; public Describe(long statement, String portal) { this.statement = statement; this.portal = portal; } public Describe(long statement) { this.statement = statement; this.portal = null; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/encoder/MessageEncoder.java ================================================ /* * Copyright (C) 2018 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.encoder; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.reactiverse.pgclient.impl.codec.ColumnDesc; import io.reactiverse.pgclient.impl.codec.DataType; import io.reactiverse.pgclient.impl.codec.DataTypeCodec; import io.reactiverse.pgclient.impl.codec.TxStatus; import io.reactiverse.pgclient.impl.codec.decoder.ErrorResponse; import io.reactiverse.pgclient.impl.codec.decoder.NoticeResponse; import io.reactiverse.pgclient.impl.codec.decoder.ParameterDescription; import io.reactiverse.pgclient.impl.codec.decoder.RowDescription; import io.reactiverse.pgclient.impl.codec.util.Util; import java.nio.charset.StandardCharsets; import java.util.List; import static io.reactiverse.pgclient.impl.codec.util.Util.writeCString; /** * @author Emad Alblueshi * @author Julien Viet */ public final class MessageEncoder { // Frontend message types for {@link io.reactiverse.pgclient.impl.codec.encoder.MessageEncoder} private static final byte PASSWORD_MESSAGE = 'p'; private static final byte QUERY = 'Q'; private static final byte TERMINATE = 'X'; private static final byte PARSE = 'P'; private static final byte BIND = 'B'; private static final byte DESCRIBE = 'D'; private static final byte EXECUTE = 'E'; private static final byte CLOSE = 'C'; private static final byte SYNC = 'S'; private final ChannelHandlerContext ctx; private ByteBuf out; public MessageEncoder(ChannelHandlerContext ctx) { this.ctx = ctx; } public void flush() { if (out != null) { ByteBuf buff = out; out = null; ctx.writeAndFlush(buff); } } /** * This message immediately closes the connection. On receipt of this message, * the backend closes the connection and terminates. */ public void writeTerminate() { ensureBuffer(); out.writeByte(TERMINATE); out.writeInt(4); } /** *

        * The purpose of this message is to provide a resynchronization point for error recovery. * When an error is detected while processing any extended-query message, the backend issues {@link ErrorResponse}, * then reads and discards messages until this message is reached, then issues {@link ReadyForQuery} and returns to normal * message processing. *

        * Note that no skipping occurs if an error is detected while processing this message which ensures that there is one * and only one {@link ReadyForQuery} sent for each of this message. *

        * Note this message does not cause a transaction block opened with BEGIN to be closed. It is possible to detect this * situation in {@link ReadyForQuery#txStatus()} that includes {@link TxStatus} information. */ public void writeSync() { ensureBuffer(); out.writeByte(SYNC); out.writeInt(4); } /** *

        * The message closes an existing prepared statement or portal and releases resources. * Note that closing a prepared statement implicitly closes any open portals that were constructed from that statement. *

        * The response is either {@link CloseComplete} or {@link ErrorResponse} * * @param portal */ public void writeClosePortal(String portal) { ensureBuffer(); int pos = out.writerIndex(); out.writeByte(CLOSE); out.writeInt(0); out.writeByte('P'); // 'S' to close a prepared statement or 'P' to close a portal Util.writeCStringUTF8(out, portal); out.setInt(pos + 1, out.writerIndex() - pos - 1); } public void writeStartupMessage(StartupMessage msg) { ensureBuffer(); int pos = out.writerIndex(); out.writeInt(0); // protocol version out.writeShort(3); out.writeShort(0); writeCString(out, StartupMessage.BUFF_USER); Util.writeCStringUTF8(out, msg.username); writeCString(out, StartupMessage.BUFF_DATABASE); Util.writeCStringUTF8(out, msg.database); writeCString(out, StartupMessage.BUFF_APPLICATION_NAME); writeCString(out, StartupMessage.BUFF_VERTX_PG_CLIENT); writeCString(out, StartupMessage.BUFF_CLIENT_ENCODING); writeCString(out, StartupMessage.BUFF_UTF8); writeCString(out, StartupMessage.BUFF_DATE_STYLE); writeCString(out, StartupMessage.BUFF_ISO); writeCString(out, StartupMessage.BUFF_INTERVAL_STYLE); writeCString(out, StartupMessage.BUFF_INTERVAL_STYLE_TYPE); writeCString(out, StartupMessage.BUFF_EXTRA_FLOAT_DIGITS); writeCString(out, StartupMessage.BUFF_2); out.writeByte(0); out.setInt(pos, out.writerIndex() - pos); } public void writePasswordMessage(PasswordMessage msg) { ensureBuffer(); int pos = out.writerIndex(); out.writeByte(PASSWORD_MESSAGE); out.writeInt(0); Util.writeCStringUTF8(out, msg.hash); out.setInt(pos + 1, out.writerIndex() - pos- 1); } /** *

        * This message includes an SQL command (or commands) expressed as a text string. *

        * The possible response messages from the backend are * {@link CommandComplete}, {@link RowDescription}, {@link DataRow}, {@link EmptyQueryResponse}, {@link ErrorResponse}, * {@link ReadyForQuery} and {@link NoticeResponse} */ public void writeQuery(Query query) { ensureBuffer(); int pos = out.writerIndex(); out.writeByte(QUERY); out.writeInt(0); Util.writeCStringUTF8(out, query.sql); out.setInt(pos + 1, out.writerIndex() - pos - 1); } /** *

        * The message that using "statement" variant specifies the name of an existing prepared statement. *

        * The response is a {@link ParameterDescription} message describing the parameters needed by the statement, * followed by a {@link RowDescription} message describing the rows that will be returned when the statement is eventually * executed or a {@link NoData} message if the statement will not return rows. * {@link ErrorResponse} is issued if there is no such prepared statement. *

        * Note that since {@link Bind} has not yet been issued, the formats to be used for returned columns are not yet known to * the backend; the format code fields in the {@link RowDescription} message will be zeroes in this case. *

        * The message that using "portal" variant specifies the name of an existing portal. *

        * The response is a {@link RowDescription} message describing the rows that will be returned by executing the portal; * or a {@link NoData} message if the portal does not contain a query that will return rows; or {@link ErrorResponse} * if there is no such portal. */ public void writeDescribe(Describe describe) { ensureBuffer(); int pos = out.writerIndex(); out.writeByte(DESCRIBE); out.writeInt(0); if (describe.statement != 0) { out.writeByte('S'); out.writeLong(describe.statement); } else if (describe.portal != null) { out.writeByte('P'); Util.writeCStringUTF8(out, describe.portal); } else { out.writeByte('S'); Util.writeCStringUTF8(out, ""); } out.setInt(pos + 1, out.writerIndex() - pos- 1); } /** *

        * The message contains a textual SQL query string. *

        * The response is either {@link ParseComplete} or {@link ErrorResponse} */ public void writeParse(Parse parse) { ensureBuffer(); int pos = out.writerIndex(); out.writeByte(PARSE); out.writeInt(0); if (parse.statement == 0) { out.writeByte(0); } else { out.writeLong(parse.statement); } Util.writeCStringUTF8(out, parse.query); // no parameter data types (OIDs) // if(paramDataTypes == null) { out.writeShort(0); // } else { // // Parameter data types (OIDs) // out.writeShort(paramDataTypes.length); // for (int paramDataType : paramDataTypes) { // out.writeInt(paramDataType); // } // } out.setInt(pos + 1, out.writerIndex() - pos - 1); } /** * The message specifies the portal and a maximum row count (zero meaning "fetch all rows") of the result. *

        * The row count of the result is only meaningful for portals containing commands that return row sets; * in other cases the command is always executed to completion, and the row count of the result is ignored. *

        * The possible responses to this message are the same as {@link Query} message, except that * it doesn't cause {@link ReadyForQuery} or {@link RowDescription} to be issued. *

        * If Execute terminates before completing the execution of a portal, it will send a {@link PortalSuspended} message; * the appearance of this message tells the frontend that another Execute should be issued against the same portal to * complete the operation. The {@link CommandComplete} message indicating completion of the source SQL command * is not sent until the portal's execution is completed. Therefore, This message is always terminated by * the appearance of exactly one of these messages: {@link CommandComplete}, * {@link EmptyQueryResponse}, {@link ErrorResponse} or {@link PortalSuspended}. * * @author Emad Alblueshi */ public void writeExecute(String portal, int rowCount) { ensureBuffer(); int pos = out.writerIndex(); out.writeByte(EXECUTE); out.writeInt(0); if (portal != null) { out.writeCharSequence(portal, StandardCharsets.UTF_8); } out.writeByte(0); out.writeInt(rowCount); // Zero denotes "no limit" maybe for ReadStream out.setInt(pos + 1, out.writerIndex() - pos - 1); } /** *

        * The message gives the name of the prepared statement, the name of portal, * and the values to use for any parameter values present in the prepared statement. * The supplied parameter set must match those needed by the prepared statement. *

        * The response is either {@link BindComplete} or {@link ErrorResponse}. */ public void writeBind(Bind bind, String portal, List paramValues) { ensureBuffer(); int pos = out.writerIndex(); out.writeByte(BIND); out.writeInt(0); if (portal != null) { out.writeCharSequence(portal, StandardCharsets.UTF_8); } out.writeByte(0); if (bind.statement == 0) { out.writeByte(0); } else { out.writeLong(bind.statement); } int paramLen = paramValues.size(); out.writeShort(paramLen); // Parameter formats for (int c = 0;c < paramLen;c++) { // for now each format is Binary out.writeShort(bind.paramTypes[c].supportsBinary ? 1 : 0); } out.writeShort(paramLen); for (int c = 0;c < paramLen;c++) { Object param = paramValues.get(c); if (param == null) { // NULL value out.writeInt(-1); } else { DataType dataType = bind.paramTypes[c]; if (dataType.supportsBinary) { int idx = out.writerIndex(); out.writeInt(0); DataTypeCodec.encodeBinary(dataType, param, out); out.setInt(idx, out.writerIndex() - idx - 4); } else { DataTypeCodec.encodeText(dataType, param, out); } } } // MAKE resultColumsn non null to avoid null check // Result columns are all in Binary format if (bind.resultColumns.length > 0) { out.writeShort(bind.resultColumns.length); for (ColumnDesc resultColumn : bind.resultColumns) { out.writeShort(resultColumn.getDataType().supportsBinary ? 1 : 0); } } else { out.writeShort(1); out.writeShort(1); } out.setInt(pos + 1, out.writerIndex() - pos - 1); } private void ensureBuffer() { if (out == null) { out = ctx.alloc().ioBuffer(); } } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/encoder/Parse.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.encoder; /** * @author Emad Alblueshi */ public final class Parse { public final String query; public final long statement; public Parse(String query, long statement) { this.query = query; this.statement = statement; } public Parse(String query) { this.query = query; this.statement = 0; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/encoder/PasswordMessage.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.encoder; import io.reactiverse.pgclient.impl.codec.util.MD5Authentication; /** * @author Emad Alblueshi */ public class PasswordMessage { public final String hash; public PasswordMessage(String username, String password, byte[] salt) { this.hash = salt != null ? MD5Authentication.encode(username, password, salt) : password; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/encoder/Query.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.encoder; /** * @author Emad Alblueshi */ public class Query { public final String sql; public Query(String sql) { this.sql = sql; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/encoder/StartupMessage.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.encoder; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static java.nio.charset.StandardCharsets.UTF_8; /** * @author Emad Alblueshi */ public class StartupMessage { public static final ByteBuf BUFF_USER = Unpooled.copiedBuffer("user", UTF_8).asReadOnly(); public static final ByteBuf BUFF_DATABASE = Unpooled.copiedBuffer("database", UTF_8).asReadOnly(); public static final ByteBuf BUFF_APPLICATION_NAME = Unpooled.copiedBuffer("application_name", UTF_8).asReadOnly(); public static final ByteBuf BUFF_VERTX_PG_CLIENT = Unpooled.copiedBuffer("vertx-pg-client", UTF_8).asReadOnly(); public static final ByteBuf BUFF_CLIENT_ENCODING = Unpooled.copiedBuffer("client_encoding", UTF_8).asReadOnly(); public static final ByteBuf BUFF_UTF8 = Unpooled.copiedBuffer("utf8", UTF_8).asReadOnly(); public static final ByteBuf BUFF_DATE_STYLE = Unpooled.copiedBuffer("DateStyle", UTF_8).asReadOnly(); public static final ByteBuf BUFF_ISO = Unpooled.copiedBuffer("ISO", UTF_8).asReadOnly(); public static final ByteBuf BUFF_INTERVAL_STYLE = Unpooled.copiedBuffer("intervalStyle", UTF_8).asReadOnly(); public static final ByteBuf BUFF_INTERVAL_STYLE_TYPE = Unpooled.copiedBuffer("postgres", UTF_8).asReadOnly(); public static final ByteBuf BUFF_EXTRA_FLOAT_DIGITS = Unpooled.copiedBuffer("extra_float_digits", UTF_8).asReadOnly(); public static final ByteBuf BUFF_2 = Unpooled.copiedBuffer("2", UTF_8).asReadOnly(); public final String username; public final String database; public StartupMessage(String username, String database) { this.username = username; this.database = database; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/formatter/DateTimeFormatter.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.formatter; import java.time.format.DateTimeFormatterBuilder; import static java.time.format.DateTimeFormatter.*; /** * @author Emad Alblueshi */ public class DateTimeFormatter { public static final java.time.format.DateTimeFormatter TIMESTAMP_FORMAT = new DateTimeFormatterBuilder() .parseCaseInsensitive() .append(ISO_LOCAL_DATE) .appendLiteral(' ') .append(ISO_LOCAL_TIME) .toFormatter(); public static final java.time.format.DateTimeFormatter TIMESTAMPTZ_FORMAT = new DateTimeFormatterBuilder() .append(TIMESTAMP_FORMAT) .appendOffset("+HH:mm", "00:00") .toFormatter(); } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/formatter/TimeFormatter.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.formatter; import java.time.format.DateTimeFormatterBuilder; import static java.time.format.DateTimeFormatter.ISO_LOCAL_TIME; /** * @author Emad Alblueshi */ public class TimeFormatter { public static final java.time.format.DateTimeFormatter TIMETZ_FORMAT = new DateTimeFormatterBuilder() .parseCaseInsensitive() .append(ISO_LOCAL_TIME) .appendOffset("+HH:mm", "00:00") .toFormatter(); } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/util/MD5Authentication.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import static java.nio.charset.StandardCharsets.*; public class MD5Authentication { private final static char[] HEX_ALPHABET = "0123456789abcdef".toCharArray(); private static String toHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for ( int j = 0; j < bytes.length; j++ ) { int v = bytes[j] & 0xFF; hexChars[j * 2] = HEX_ALPHABET[v >>> 4]; hexChars[j * 2 + 1] = HEX_ALPHABET[v & 0x0F]; } return new String(hexChars); } public static String encode(String username, String password, byte[] salt) { byte[] digest, passDigest; MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } messageDigest.update(password.getBytes(UTF_8)); messageDigest.update(username.getBytes(UTF_8)); digest = messageDigest.digest(); byte[] hexDigest = toHex(digest).getBytes(US_ASCII); messageDigest.update(hexDigest); messageDigest.update(salt); passDigest = messageDigest.digest(); return "md5" + toHex(passDigest); } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/util/UTF8StringEndDetector.java ================================================ /* * Copyright (C) 2018 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.util; import io.netty.util.ByteProcessor; /** * A processor that detects the end of a well formed UTF8 string, starting end ending with a {@code "}. *

        * It process all bytes until it finds the ending {@code "}. */ public class UTF8StringEndDetector implements ByteProcessor { private boolean inString; private boolean escaped; @Override public boolean process(byte value) { boolean wasEscaped = escaped; escaped = false; // In UTF-8 low ASCII have their 8th bit == 0 if ((value & 0b10000000) == 0) { switch (value) { case '"': if (!wasEscaped) { if (inString) { return false; } else { inString = true; } } break; case '\\': if (inString) { escaped = true; } break; } } return true; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/codec/util/Util.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.codec.util; import io.netty.buffer.ByteBuf; import io.vertx.core.buffer.Buffer; import java.nio.charset.Charset; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.nio.charset.StandardCharsets.*; public class Util { private static final byte ZERO = 0; public static String readCString(ByteBuf src, Charset charset) { int len = src.bytesBefore(ZERO); String s = src.readCharSequence(len, charset).toString(); src.readByte(); return s; } public static String readCStringUTF8(ByteBuf src) { int len = src.bytesBefore(ZERO); String s = src.readCharSequence(len, UTF_8).toString(); src.readByte(); return s; } public static void writeCString(ByteBuf dst, String s, Charset charset) { dst.writeCharSequence(s, charset); dst.writeByte(0); } public static void writeCString(ByteBuf dst, ByteBuf buf) { // Important : won't not change data index dst.writeBytes(buf, buf.readerIndex(), buf.readableBytes()); dst.writeByte(0); } public static void writeCStringUTF8(ByteBuf dst, String s) { dst.writeCharSequence(s, UTF_8); dst.writeByte(0); } public static void writeCString(ByteBuf dst, byte[] bytes) { dst.writeBytes(bytes, 0, bytes.length); dst.writeByte(0); } public static String buildInvalidArgsError(Stream values, Stream types) { return "Values [" + values.map(String::valueOf).collect(Collectors.joining(", ")) + "] cannot be coerced to [" + types .map(Class::getSimpleName) .collect(Collectors.joining(", ")) + "]"; } private static final int FIRST_HALF_BYTE_MASK = 0x0F; public static int writeHexString(Buffer buffer, ByteBuf to) { int len = buffer.length(); for (int i = 0; i < len; i++) { final int b = Byte.toUnsignedInt(buffer.getByte(i)); final int firstDigit = b >> 4; final byte firstHexDigit = (byte)bin2hex(firstDigit); final int secondDigit = b & FIRST_HALF_BYTE_MASK; final byte secondHexDigit = (byte)bin2hex(secondDigit); to.writeByte(firstHexDigit); to.writeByte(secondHexDigit); } return len; } private static int bin2hex(int digit){ final int isLessOrEqual9 =(digit-10)>>31; //isLessOrEqual9==0xff<->digit<=9 //bin2hexAsciiDistance=digit<=9?48:87; final int bin2hexAsciiDistance = 48+((~isLessOrEqual9)&39); return digit+bin2hexAsciiDistance; } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/data/JsonImpl.java ================================================ /* * Copyright (C) 2018 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.data; import io.reactiverse.pgclient.data.Json; import java.util.Objects; public class JsonImpl implements Json { public static final JsonImpl NULL = new JsonImpl(null); private final Object value; public JsonImpl(Object value) { this.value = value; } @Override public Object value() { return value; } @Override public int hashCode() { return Objects.hashCode(value); } @Override public boolean equals(Object obj) { return obj instanceof Json && Objects.equals(value, ((Json) obj).value()); } @Override public String toString() { return String.valueOf(value); } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/impl/pubsub/PgSubscriberImpl.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.impl.pubsub; import io.reactiverse.pgclient.*; import io.reactiverse.pgclient.pubsub.PgSubscriber; import io.reactiverse.pgclient.pubsub.PgChannel; import io.vertx.core.*; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.core.streams.ReadStream; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; public class PgSubscriberImpl implements PgSubscriber { private static Logger log = LoggerFactory.getLogger(PgSubscriberImpl.class); private static final Function DEFAULT_RECONNECT_POLICY = count -> -1L; private final Vertx vertx; private final PgConnectOptions options; private Map channels = new HashMap<>(); private Function reconnectPolicy = DEFAULT_RECONNECT_POLICY; private PgConnection conn; private boolean connecting; private boolean closed = true; private Handler closeHandler; public PgSubscriberImpl(Vertx vertx, PgConnectOptions options) { this.vertx = vertx; this.options = new PgConnectOptions(options); } // Identifiers in PostgreSQL are currently limited to NAMEDATALEN-1 = 63 // characters (see PostgreSQL lexical structure documentation) public static final int NAMEDATALEN = 64; public static final int MAX_CHANNEL_NAME_LENGTH = NAMEDATALEN - 1; public static String applyIdLengthLimit(String channelName) { return channelName.length() > MAX_CHANNEL_NAME_LENGTH ? channelName.substring(0, MAX_CHANNEL_NAME_LENGTH) : channelName; } private void handleNotification(PgNotification notif) { List> handlers = new ArrayList<>(); synchronized (this) { ChannelList channel = channels.get(notif.getChannel()); if (channel != null) { channel.subs.forEach(sub -> { if (!sub.paused) { Handler handler = sub.eventHandler; if (handler != null) { handlers.add(handler); } else { // Race ? } } }); } else { // Race ? } } handlers.forEach(handler -> { handler.handle(notif.getPayload()); }); } @Override public synchronized PgSubscriber closeHandler(Handler handler) { closeHandler = handler; return this; } @Override public synchronized PgSubscriber reconnectPolicy(Function policy) { if (policy == null) { reconnectPolicy = DEFAULT_RECONNECT_POLICY; } else { reconnectPolicy = policy; } return this; } private synchronized void handleClose(Void v) { conn = null; checkReconnect(0); } private void checkReconnect(int count) { if (!closed) { Long val = reconnectPolicy.apply(count); if (val >= 0) { tryConnect(val, ar -> { if (ar.failed()) { checkReconnect(count + 1); } }); return; } closed = true; } List> all = channels .values() .stream() .flatMap(channel -> channel.subs.stream()) .map(sub -> sub.endHandler) .filter(Objects::nonNull) .collect(Collectors.toList()); channels.clear(); all.forEach(handler -> handler.handle(null)); Handler handler = closeHandler; if (handler != null) { handler.handle(null); } } @Override public synchronized boolean closed() { return closed; } @Override public synchronized PgConnection actualConnection() { return conn; } @Override public synchronized PgSubscriber connect(Handler> handler) { if (closed) { closed = false; tryConnect(0, handler); } return this; } private void tryConnect(long delayMillis, Handler> handler) { if (!connecting) { connecting = true; if (delayMillis > 0) { vertx.setTimer(delayMillis, v -> doConnect(handler)); } else { doConnect(handler); } } } private void doConnect(Handler> completionHandler) { PgClient.connect(vertx, options, ar -> handleConnectResult(completionHandler, ar)); } private synchronized void handleConnectResult(Handler> completionHandler, AsyncResult ar1) { connecting = false; if (ar1.succeeded()) { conn = ar1.result(); conn.notificationHandler(PgSubscriberImpl.this::handleNotification); conn.closeHandler(PgSubscriberImpl.this::handleClose); if (channels.size() > 0) { List> handlers = channels.values() .stream() .flatMap(channel -> channel.subs.stream()) .map(sub -> sub.subscribeHandler) .filter(Objects::nonNull) .collect(Collectors.toList()); String sql = channels.values() .stream() .map(channel -> { channel.subscribed = true; return channel.quotedName; }) .collect(Collectors.joining(";LISTEN ", "LISTEN ", "")); conn.query(sql, ar2 -> { if (ar2.failed()) { log.error("Cannot LISTEN to channels", ar2.cause()); conn.close(); } else { handlers.forEach(vertx::runOnContext); } completionHandler.handle(ar2.mapEmpty()); }); return; } } completionHandler.handle(ar1.mapEmpty()); } private class ChannelList { final String name; final String quotedName; final ArrayList subs = new ArrayList<>(); boolean subscribed; ChannelList(String name) { this.name = name; quotedName = "\"" + name.replace("\"", "\"\"") + "\""; } void add(ChannelImpl sub) { subs.add(sub); if (!subscribed) { if (conn != null) { subscribed = true; String sql = "LISTEN " + quotedName; conn.query(sql, ar -> { if (ar.succeeded()) { Handler handler = sub.subscribeHandler; if (handler != null) { handler.handle(null); } } else { log.error("Cannot LISTEN to channel " + name, ar.cause()); } }); } } } void remove(ChannelImpl sub) { subs.remove(sub); if (subs.isEmpty()) { channels.remove(name, this); if (conn != null) { conn.query("UNLISTEN " + quotedName, ar -> { if (ar.failed()) { log.error("Cannot UNLISTEN channel " + name, ar.cause()); } }); } } } } private class ChannelImpl implements PgChannel { private final String name; private Handler subscribeHandler; private Handler eventHandler; private Handler endHandler; private ChannelList channel; private boolean paused; ChannelImpl(String name) { this.name = applyIdLengthLimit(name); } @Override public PgChannel subscribeHandler(Handler handler) { synchronized (PgSubscriberImpl.this) { subscribeHandler = handler; } return this; } @Override public ChannelImpl exceptionHandler(Handler handler) { return this; } @Override public ChannelImpl handler(Handler handler) { synchronized (PgSubscriberImpl.this) { if (handler != null) { eventHandler = handler; if (channel == null) { channel = channels.computeIfAbsent(name, ChannelList::new); channel.add(this); } } else { if (channel != null) { ChannelList ch = channel; channel = null; ch.remove(this); Handler _handler = endHandler; if (_handler != null) { _handler.handle(null); } } } } return this; } @Override public ChannelImpl endHandler(Handler handler) { synchronized (PgSubscriberImpl.this) { endHandler = handler; } return this; } @Override public ChannelImpl pause() { synchronized (PgSubscriberImpl.this) { paused = true; } return this; } @Override public ChannelImpl resume() { synchronized (PgSubscriberImpl.this) { paused = false; } return this; } // Since Vert.x 3.6.0 : todo public ReadStream fetch(long amount) { throw new UnsupportedOperationException(); } } @Override public void close() { synchronized (PgSubscriberImpl.this) { if (!closed) { closed = true; if (conn != null) { conn.close(); } } } } @Override public PgChannel channel(String name) { return new ChannelImpl(name); } } ================================================ FILE: src/main/java/io/reactiverse/pgclient/package-info.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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. * */ @ModuleGen(name = "reactive-pg-client", groupPackage = "io.reactiverse") package io.reactiverse.pgclient; import io.vertx.codegen.annotations.ModuleGen; ================================================ FILE: src/main/java/io/reactiverse/pgclient/pubsub/PgChannel.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.pubsub; import io.vertx.codegen.annotations.Fluent; import io.vertx.codegen.annotations.VertxGen; import io.vertx.core.Handler; import io.vertx.core.streams.ReadStream; /** * A channel to Postgres that tracks the subscription to a given Postgres channel using the {@code LISTEN/UNLISTEN} commands. *

        * When paused the channel discards the messages. */ @VertxGen public interface PgChannel extends ReadStream { /** * Set an handler called when the the channel get subscribed. * * @param handler the handler * @return a reference to this, so the API can be used fluently */ @Fluent PgChannel subscribeHandler(Handler handler); /** * Set or unset an handler to be called when a the channel is notified by Postgres. *

        *

          *
        • when the handler is set, the subscriber sends a {@code LISTEN} command if needed
        • *
        • when the handler is unset, the subscriber sends a {@code UNLISTEN} command if needed
        • *
        * * @param handler the handler * @return a reference to this, so the API can be used fluently */ @Override PgChannel handler(Handler handler); /** * Pause the channel, all notifications are discarded. * * @return a reference to this, so the API can be used fluently */ @Override PgChannel pause(); /** * Resume the channel. * * @return a reference to this, so the API can be used fluently */ @Override PgChannel resume(); /** * Set an handler to be called when no more notifications will be received. * * @param endHandler the handler * @return a reference to this, so the API can be used fluently */ @Override PgChannel endHandler(Handler endHandler); @Override PgChannel exceptionHandler(Handler handler); } ================================================ FILE: src/main/java/io/reactiverse/pgclient/pubsub/PgSubscriber.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.pubsub; import io.reactiverse.pgclient.PgConnectOptions; import io.reactiverse.pgclient.PgConnection; import io.reactiverse.pgclient.impl.pubsub.PgSubscriberImpl; import io.vertx.codegen.annotations.Fluent; import io.vertx.codegen.annotations.VertxGen; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import io.vertx.core.Vertx; import java.util.function.Function; /** * A class for managing subscriptions using {@code LISTEN/UNLISTEN} to Postgres channels. *

        * The subscriber manages a single connection to Postgres. */ @VertxGen public interface PgSubscriber { /** * Create a subscriber. * * @param vertx the vertx instance * @param options the connect options * @return the subscriber */ static PgSubscriber subscriber(Vertx vertx, PgConnectOptions options) { return new PgSubscriberImpl(vertx, options); } /** * Return a channel for the given {@code name}. * * @param name the channel name *

        * This will be the name of the channel exactly as held by Postgres for sending * notifications. Internally this name will be truncated to the Postgres identifier * maxiumum length of {@code (NAMEDATALEN = 64) - 1 == 63} characters, and prepared * as a quoted identifier without unicode escape sequence support for use in * {@code LISTEN/UNLISTEN} commands. Examples of channel names and corresponding * {@code NOTIFY} commands: *

          *
        • when {@code name == "the_channel"}: {@code NOTIFY the_channel, 'msg'}, * {@code NOTIFY The_Channel, 'msg'}, or {@code NOTIFY "the_channel", 'msg'} * succeed in delivering a message to the created channel *
        • *
        • when {@code name == "The_Channel"}: {@code NOTIFY "The_Channel", 'msg'}, * succeeds in delivering a message to the created channel *
        • *
        • *
        * @return the channel */ PgChannel channel(String name); /** * Connect the subscriber to Postgres. * * @param handler the handler notified of the connection success or failure * @return a reference to this, so the API can be used fluently */ @Fluent PgSubscriber connect(Handler> handler); /** * Set the reconnect policy that is executed when the subscriber is disconnected. *

        * When the subscriber is disconnected, the {@code policy} function is called with the actual * number of retries and returns an {@code amountOfTime} value: *

          *
        • when {@code amountOfTime < 0}: the subscriber is closed and there is no retry
        • *
        • when {@code amountOfTime == 0}: the subscriber retries to connect immediately
        • *
        • when {@code amountOfTime > 0}: the subscriber retries after {@code amountOfTime} milliseconds
        • *
        *

        * The default policy does not perform any retries. * * @param policy the policy to set * @return a reference to this, so the API can be used fluently */ @Fluent PgSubscriber reconnectPolicy(Function policy); /** * Set an handler called when the subscriber is closed. * * @param handler the handler * @return a reference to this, so the API can be used fluently */ @Fluent PgSubscriber closeHandler(Handler handler); /** * @return the actual connection to Postgres, it might be {@code null} */ PgConnection actualConnection(); /** * @return whether the subscriber is closed */ boolean closed(); /** * Close the subscriber, the retry policy will not be invoked. */ void close(); } ================================================ FILE: src/main/kotlin/io/reactiverse/kotlin/pgclient/PgClient.kt ================================================ /* * Copyright 2019 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.reactiverse.kotlin.pgclient import io.reactiverse.pgclient.PgClient as PgClientVertxAlias import io.reactiverse.pgclient.PgConnectOptions import io.reactiverse.pgclient.PgConnection import io.reactiverse.pgclient.PgRowSet import io.reactiverse.pgclient.Tuple import io.vertx.core.Vertx import io.vertx.kotlin.coroutines.awaitResult /** * Suspending version of method [io.reactiverse.pgclient.PgClient.query] * * @param sql the query SQL * @return [PgRowSet] * * NOTE: This function has been automatically generated from [io.reactiverse.pgclient.PgClient] using Vert.x codegen. */ suspend fun PgClientVertxAlias.queryAwait(sql: String): PgRowSet { return awaitResult { this.query(sql, it) } } /** * Suspending version of method [io.reactiverse.pgclient.PgClient.preparedQuery] * * @param sql the prepared query SQL * @return [PgRowSet] * * NOTE: This function has been automatically generated from [io.reactiverse.pgclient.PgClient] using Vert.x codegen. */ suspend fun PgClientVertxAlias.preparedQueryAwait(sql: String): PgRowSet { return awaitResult { this.preparedQuery(sql, it) } } /** * Suspending version of method [io.reactiverse.pgclient.PgClient.preparedQuery] * * @param sql the prepared query SQL * @param arguments the list of arguments * @return [PgRowSet] * * NOTE: This function has been automatically generated from [io.reactiverse.pgclient.PgClient] using Vert.x codegen. */ suspend fun PgClientVertxAlias.preparedQueryAwait(sql: String, arguments: Tuple): PgRowSet { return awaitResult { this.preparedQuery(sql, arguments, it) } } /** * Suspending version of method [io.reactiverse.pgclient.PgClient.preparedBatch] * * @param sql the prepared query SQL * @param batch the batch of tuples * @return [PgRowSet] * * NOTE: This function has been automatically generated from [io.reactiverse.pgclient.PgClient] using Vert.x codegen. */ suspend fun PgClientVertxAlias.preparedBatchAwait(sql: String, batch: List): PgRowSet { return awaitResult { this.preparedBatch(sql, batch, it) } } object PgClient { /** * Suspending version of method [io.reactiverse.pgclient.PgClient.connect] * * @param vertx the vertx instance * @param options the connect options * @return [PgConnection] * * NOTE: This function has been automatically generated from [io.reactiverse.pgclient.PgClient] using Vert.x codegen. */ suspend fun connectAwait(vertx: Vertx, options: PgConnectOptions): PgConnection { return awaitResult { PgClientVertxAlias.connect(vertx, options, it) } } /** * Suspending version of method [io.reactiverse.pgclient.PgClient.connect] * * @param vertx * @return [PgConnection] * * NOTE: This function has been automatically generated from [io.reactiverse.pgclient.PgClient] using Vert.x codegen. */ suspend fun connectAwait(vertx: Vertx): PgConnection { return awaitResult { PgClientVertxAlias.connect(vertx, it) } } /** * Suspending version of method [io.reactiverse.pgclient.PgClient.connect] * * @param vertx * @param connectionUri * @return [PgConnection] * * NOTE: This function has been automatically generated from [io.reactiverse.pgclient.PgClient] using Vert.x codegen. */ suspend fun connectAwait(vertx: Vertx, connectionUri: String): PgConnection { return awaitResult { PgClientVertxAlias.connect(vertx, connectionUri, it) } } } ================================================ FILE: src/main/kotlin/io/reactiverse/kotlin/pgclient/PgConnectOptions.kt ================================================ /* * Copyright 2019 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.reactiverse.kotlin.pgclient import io.reactiverse.pgclient.PgConnectOptions import io.reactiverse.pgclient.SslMode import io.vertx.core.net.JdkSSLEngineOptions import io.vertx.core.net.JksOptions import io.vertx.core.net.OpenSSLEngineOptions import io.vertx.core.net.PemKeyCertOptions import io.vertx.core.net.PemTrustOptions import io.vertx.core.net.PfxOptions import io.vertx.core.net.ProxyOptions import java.util.concurrent.TimeUnit /** * A function providing a DSL for building [io.reactiverse.pgclient.PgConnectOptions] objects. * * * @param cachePreparedStatements * @param connectTimeout * @param crlPaths * @param crlValues * @param database * @param enabledCipherSuites * @param enabledSecureTransportProtocols * @param host * @param hostnameVerificationAlgorithm * @param idleTimeout * @param idleTimeoutUnit * @param jdkSslEngineOptions * @param keyStoreOptions * @param localAddress * @param logActivity * @param metricsName * @param openSslEngineOptions * @param password * @param pemKeyCertOptions * @param pemTrustOptions * @param pfxKeyCertOptions * @param pfxTrustOptions * @param pipeliningLimit * @param port * @param proxyOptions * @param receiveBufferSize * @param reconnectAttempts * @param reconnectInterval * @param reuseAddress * @param reusePort * @param sendBufferSize * @param soLinger * @param ssl * @param sslHandshakeTimeout * @param sslHandshakeTimeoutUnit * @param sslMode Set [io.reactiverse.pgclient.SslMode] for the client, this option can be used to provide different levels of secure protection. * @param tcpCork * @param tcpFastOpen * @param tcpKeepAlive * @param tcpNoDelay * @param tcpQuickAck * @param trafficClass * @param trustAll * @param trustStoreOptions * @param useAlpn * @param usePooledBuffers * @param user * *

        * NOTE: This function has been automatically generated from the [io.reactiverse.pgclient.PgConnectOptions original] using Vert.x codegen. */ fun pgConnectOptionsOf( cachePreparedStatements: Boolean? = null, connectTimeout: Int? = null, crlPaths: Iterable? = null, crlValues: Iterable? = null, database: String? = null, enabledCipherSuites: Iterable? = null, enabledSecureTransportProtocols: Iterable? = null, host: String? = null, hostnameVerificationAlgorithm: String? = null, idleTimeout: Int? = null, idleTimeoutUnit: TimeUnit? = null, jdkSslEngineOptions: io.vertx.core.net.JdkSSLEngineOptions? = null, keyStoreOptions: io.vertx.core.net.JksOptions? = null, localAddress: String? = null, logActivity: Boolean? = null, metricsName: String? = null, openSslEngineOptions: io.vertx.core.net.OpenSSLEngineOptions? = null, password: String? = null, pemKeyCertOptions: io.vertx.core.net.PemKeyCertOptions? = null, pemTrustOptions: io.vertx.core.net.PemTrustOptions? = null, pfxKeyCertOptions: io.vertx.core.net.PfxOptions? = null, pfxTrustOptions: io.vertx.core.net.PfxOptions? = null, pipeliningLimit: Int? = null, port: Int? = null, proxyOptions: io.vertx.core.net.ProxyOptions? = null, receiveBufferSize: Int? = null, reconnectAttempts: Int? = null, reconnectInterval: Long? = null, reuseAddress: Boolean? = null, reusePort: Boolean? = null, sendBufferSize: Int? = null, soLinger: Int? = null, ssl: Boolean? = null, sslHandshakeTimeout: Long? = null, sslHandshakeTimeoutUnit: TimeUnit? = null, sslMode: SslMode? = null, tcpCork: Boolean? = null, tcpFastOpen: Boolean? = null, tcpKeepAlive: Boolean? = null, tcpNoDelay: Boolean? = null, tcpQuickAck: Boolean? = null, trafficClass: Int? = null, trustAll: Boolean? = null, trustStoreOptions: io.vertx.core.net.JksOptions? = null, useAlpn: Boolean? = null, usePooledBuffers: Boolean? = null, user: String? = null): PgConnectOptions = io.reactiverse.pgclient.PgConnectOptions().apply { if (cachePreparedStatements != null) { this.setCachePreparedStatements(cachePreparedStatements) } if (connectTimeout != null) { this.setConnectTimeout(connectTimeout) } if (crlPaths != null) { for (item in crlPaths) { this.addCrlPath(item) } } if (crlValues != null) { for (item in crlValues) { this.addCrlValue(item) } } if (database != null) { this.setDatabase(database) } if (enabledCipherSuites != null) { for (item in enabledCipherSuites) { this.addEnabledCipherSuite(item) } } if (enabledSecureTransportProtocols != null) { this.setEnabledSecureTransportProtocols(enabledSecureTransportProtocols.toSet()) } if (host != null) { this.setHost(host) } if (hostnameVerificationAlgorithm != null) { this.setHostnameVerificationAlgorithm(hostnameVerificationAlgorithm) } if (idleTimeout != null) { this.setIdleTimeout(idleTimeout) } if (idleTimeoutUnit != null) { this.setIdleTimeoutUnit(idleTimeoutUnit) } if (jdkSslEngineOptions != null) { this.setJdkSslEngineOptions(jdkSslEngineOptions) } if (keyStoreOptions != null) { this.setKeyStoreOptions(keyStoreOptions) } if (localAddress != null) { this.setLocalAddress(localAddress) } if (logActivity != null) { this.setLogActivity(logActivity) } if (metricsName != null) { this.setMetricsName(metricsName) } if (openSslEngineOptions != null) { this.setOpenSslEngineOptions(openSslEngineOptions) } if (password != null) { this.setPassword(password) } if (pemKeyCertOptions != null) { this.setPemKeyCertOptions(pemKeyCertOptions) } if (pemTrustOptions != null) { this.setPemTrustOptions(pemTrustOptions) } if (pfxKeyCertOptions != null) { this.setPfxKeyCertOptions(pfxKeyCertOptions) } if (pfxTrustOptions != null) { this.setPfxTrustOptions(pfxTrustOptions) } if (pipeliningLimit != null) { this.setPipeliningLimit(pipeliningLimit) } if (port != null) { this.setPort(port) } if (proxyOptions != null) { this.setProxyOptions(proxyOptions) } if (receiveBufferSize != null) { this.setReceiveBufferSize(receiveBufferSize) } if (reconnectAttempts != null) { this.setReconnectAttempts(reconnectAttempts) } if (reconnectInterval != null) { this.setReconnectInterval(reconnectInterval) } if (reuseAddress != null) { this.setReuseAddress(reuseAddress) } if (reusePort != null) { this.setReusePort(reusePort) } if (sendBufferSize != null) { this.setSendBufferSize(sendBufferSize) } if (soLinger != null) { this.setSoLinger(soLinger) } if (ssl != null) { this.setSsl(ssl) } if (sslHandshakeTimeout != null) { this.setSslHandshakeTimeout(sslHandshakeTimeout) } if (sslHandshakeTimeoutUnit != null) { this.setSslHandshakeTimeoutUnit(sslHandshakeTimeoutUnit) } if (sslMode != null) { this.setSslMode(sslMode) } if (tcpCork != null) { this.setTcpCork(tcpCork) } if (tcpFastOpen != null) { this.setTcpFastOpen(tcpFastOpen) } if (tcpKeepAlive != null) { this.setTcpKeepAlive(tcpKeepAlive) } if (tcpNoDelay != null) { this.setTcpNoDelay(tcpNoDelay) } if (tcpQuickAck != null) { this.setTcpQuickAck(tcpQuickAck) } if (trafficClass != null) { this.setTrafficClass(trafficClass) } if (trustAll != null) { this.setTrustAll(trustAll) } if (trustStoreOptions != null) { this.setTrustStoreOptions(trustStoreOptions) } if (useAlpn != null) { this.setUseAlpn(useAlpn) } if (usePooledBuffers != null) { this.setUsePooledBuffers(usePooledBuffers) } if (user != null) { this.setUser(user) } } /** * A function providing a DSL for building [io.reactiverse.pgclient.PgConnectOptions] objects. * * * @param cachePreparedStatements * @param connectTimeout * @param crlPaths * @param crlValues * @param database * @param enabledCipherSuites * @param enabledSecureTransportProtocols * @param host * @param hostnameVerificationAlgorithm * @param idleTimeout * @param idleTimeoutUnit * @param jdkSslEngineOptions * @param keyStoreOptions * @param localAddress * @param logActivity * @param metricsName * @param openSslEngineOptions * @param password * @param pemKeyCertOptions * @param pemTrustOptions * @param pfxKeyCertOptions * @param pfxTrustOptions * @param pipeliningLimit * @param port * @param proxyOptions * @param receiveBufferSize * @param reconnectAttempts * @param reconnectInterval * @param reuseAddress * @param reusePort * @param sendBufferSize * @param soLinger * @param ssl * @param sslHandshakeTimeout * @param sslHandshakeTimeoutUnit * @param sslMode Set [io.reactiverse.pgclient.SslMode] for the client, this option can be used to provide different levels of secure protection. * @param tcpCork * @param tcpFastOpen * @param tcpKeepAlive * @param tcpNoDelay * @param tcpQuickAck * @param trafficClass * @param trustAll * @param trustStoreOptions * @param useAlpn * @param usePooledBuffers * @param user * *

        * NOTE: This function has been automatically generated from the [io.reactiverse.pgclient.PgConnectOptions original] using Vert.x codegen. */ @Deprecated( message = "This function will be removed in a future version", replaceWith = ReplaceWith("pgConnectOptionsOf(cachePreparedStatements, connectTimeout, crlPaths, crlValues, database, enabledCipherSuites, enabledSecureTransportProtocols, host, hostnameVerificationAlgorithm, idleTimeout, idleTimeoutUnit, jdkSslEngineOptions, keyStoreOptions, localAddress, logActivity, metricsName, openSslEngineOptions, password, pemKeyCertOptions, pemTrustOptions, pfxKeyCertOptions, pfxTrustOptions, pipeliningLimit, port, proxyOptions, receiveBufferSize, reconnectAttempts, reconnectInterval, reuseAddress, reusePort, sendBufferSize, soLinger, ssl, sslHandshakeTimeout, sslHandshakeTimeoutUnit, sslMode, tcpCork, tcpFastOpen, tcpKeepAlive, tcpNoDelay, tcpQuickAck, trafficClass, trustAll, trustStoreOptions, useAlpn, usePooledBuffers, user)") ) fun PgConnectOptions( cachePreparedStatements: Boolean? = null, connectTimeout: Int? = null, crlPaths: Iterable? = null, crlValues: Iterable? = null, database: String? = null, enabledCipherSuites: Iterable? = null, enabledSecureTransportProtocols: Iterable? = null, host: String? = null, hostnameVerificationAlgorithm: String? = null, idleTimeout: Int? = null, idleTimeoutUnit: TimeUnit? = null, jdkSslEngineOptions: io.vertx.core.net.JdkSSLEngineOptions? = null, keyStoreOptions: io.vertx.core.net.JksOptions? = null, localAddress: String? = null, logActivity: Boolean? = null, metricsName: String? = null, openSslEngineOptions: io.vertx.core.net.OpenSSLEngineOptions? = null, password: String? = null, pemKeyCertOptions: io.vertx.core.net.PemKeyCertOptions? = null, pemTrustOptions: io.vertx.core.net.PemTrustOptions? = null, pfxKeyCertOptions: io.vertx.core.net.PfxOptions? = null, pfxTrustOptions: io.vertx.core.net.PfxOptions? = null, pipeliningLimit: Int? = null, port: Int? = null, proxyOptions: io.vertx.core.net.ProxyOptions? = null, receiveBufferSize: Int? = null, reconnectAttempts: Int? = null, reconnectInterval: Long? = null, reuseAddress: Boolean? = null, reusePort: Boolean? = null, sendBufferSize: Int? = null, soLinger: Int? = null, ssl: Boolean? = null, sslHandshakeTimeout: Long? = null, sslHandshakeTimeoutUnit: TimeUnit? = null, sslMode: SslMode? = null, tcpCork: Boolean? = null, tcpFastOpen: Boolean? = null, tcpKeepAlive: Boolean? = null, tcpNoDelay: Boolean? = null, tcpQuickAck: Boolean? = null, trafficClass: Int? = null, trustAll: Boolean? = null, trustStoreOptions: io.vertx.core.net.JksOptions? = null, useAlpn: Boolean? = null, usePooledBuffers: Boolean? = null, user: String? = null): PgConnectOptions = io.reactiverse.pgclient.PgConnectOptions().apply { if (cachePreparedStatements != null) { this.setCachePreparedStatements(cachePreparedStatements) } if (connectTimeout != null) { this.setConnectTimeout(connectTimeout) } if (crlPaths != null) { for (item in crlPaths) { this.addCrlPath(item) } } if (crlValues != null) { for (item in crlValues) { this.addCrlValue(item) } } if (database != null) { this.setDatabase(database) } if (enabledCipherSuites != null) { for (item in enabledCipherSuites) { this.addEnabledCipherSuite(item) } } if (enabledSecureTransportProtocols != null) { this.setEnabledSecureTransportProtocols(enabledSecureTransportProtocols.toSet()) } if (host != null) { this.setHost(host) } if (hostnameVerificationAlgorithm != null) { this.setHostnameVerificationAlgorithm(hostnameVerificationAlgorithm) } if (idleTimeout != null) { this.setIdleTimeout(idleTimeout) } if (idleTimeoutUnit != null) { this.setIdleTimeoutUnit(idleTimeoutUnit) } if (jdkSslEngineOptions != null) { this.setJdkSslEngineOptions(jdkSslEngineOptions) } if (keyStoreOptions != null) { this.setKeyStoreOptions(keyStoreOptions) } if (localAddress != null) { this.setLocalAddress(localAddress) } if (logActivity != null) { this.setLogActivity(logActivity) } if (metricsName != null) { this.setMetricsName(metricsName) } if (openSslEngineOptions != null) { this.setOpenSslEngineOptions(openSslEngineOptions) } if (password != null) { this.setPassword(password) } if (pemKeyCertOptions != null) { this.setPemKeyCertOptions(pemKeyCertOptions) } if (pemTrustOptions != null) { this.setPemTrustOptions(pemTrustOptions) } if (pfxKeyCertOptions != null) { this.setPfxKeyCertOptions(pfxKeyCertOptions) } if (pfxTrustOptions != null) { this.setPfxTrustOptions(pfxTrustOptions) } if (pipeliningLimit != null) { this.setPipeliningLimit(pipeliningLimit) } if (port != null) { this.setPort(port) } if (proxyOptions != null) { this.setProxyOptions(proxyOptions) } if (receiveBufferSize != null) { this.setReceiveBufferSize(receiveBufferSize) } if (reconnectAttempts != null) { this.setReconnectAttempts(reconnectAttempts) } if (reconnectInterval != null) { this.setReconnectInterval(reconnectInterval) } if (reuseAddress != null) { this.setReuseAddress(reuseAddress) } if (reusePort != null) { this.setReusePort(reusePort) } if (sendBufferSize != null) { this.setSendBufferSize(sendBufferSize) } if (soLinger != null) { this.setSoLinger(soLinger) } if (ssl != null) { this.setSsl(ssl) } if (sslHandshakeTimeout != null) { this.setSslHandshakeTimeout(sslHandshakeTimeout) } if (sslHandshakeTimeoutUnit != null) { this.setSslHandshakeTimeoutUnit(sslHandshakeTimeoutUnit) } if (sslMode != null) { this.setSslMode(sslMode) } if (tcpCork != null) { this.setTcpCork(tcpCork) } if (tcpFastOpen != null) { this.setTcpFastOpen(tcpFastOpen) } if (tcpKeepAlive != null) { this.setTcpKeepAlive(tcpKeepAlive) } if (tcpNoDelay != null) { this.setTcpNoDelay(tcpNoDelay) } if (tcpQuickAck != null) { this.setTcpQuickAck(tcpQuickAck) } if (trafficClass != null) { this.setTrafficClass(trafficClass) } if (trustAll != null) { this.setTrustAll(trustAll) } if (trustStoreOptions != null) { this.setTrustStoreOptions(trustStoreOptions) } if (useAlpn != null) { this.setUseAlpn(useAlpn) } if (usePooledBuffers != null) { this.setUsePooledBuffers(usePooledBuffers) } if (user != null) { this.setUser(user) } } ================================================ FILE: src/main/kotlin/io/reactiverse/kotlin/pgclient/PgConnection.kt ================================================ /* * Copyright 2019 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.reactiverse.kotlin.pgclient import io.reactiverse.pgclient.PgConnection import io.reactiverse.pgclient.PgPreparedQuery import io.reactiverse.pgclient.PgRowSet import io.reactiverse.pgclient.Tuple import io.vertx.kotlin.coroutines.awaitResult /** * Suspending version of method [io.reactiverse.pgclient.PgConnection.prepare] * * @param sql the sql * @return [PgPreparedQuery] * * NOTE: This function has been automatically generated from [io.reactiverse.pgclient.PgConnection] using Vert.x codegen. */ suspend fun PgConnection.prepareAwait(sql: String): PgPreparedQuery { return awaitResult { this.prepare(sql, it) } } suspend fun PgConnection.preparedQueryAwait(sql: String): PgRowSet { return awaitResult { this.preparedQuery(sql, it) } } suspend fun PgConnection.queryAwait(sql: String): PgRowSet { return awaitResult { this.query(sql, it) } } suspend fun PgConnection.preparedQueryAwait(sql: String, arguments: Tuple): PgRowSet { return awaitResult { this.preparedQuery(sql, arguments, it) } } suspend fun PgConnection.preparedBatchAwait(sql: String, batch: List): PgRowSet { return awaitResult { this.preparedBatch(sql, batch, it) } } ================================================ FILE: src/main/kotlin/io/reactiverse/kotlin/pgclient/PgCursor.kt ================================================ /* * Copyright 2019 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.reactiverse.kotlin.pgclient import io.reactiverse.pgclient.PgCursor import io.reactiverse.pgclient.PgRowSet import io.vertx.kotlin.coroutines.awaitResult /** * Suspending version of method [io.reactiverse.pgclient.PgCursor.read] * * @param count the amount of rows to read * @return [PgRowSet] * * NOTE: This function has been automatically generated from [io.reactiverse.pgclient.PgCursor] using Vert.x codegen. */ suspend fun PgCursor.readAwait(count: Int): PgRowSet { return awaitResult { this.read(count, it) } } /** * Suspending version of method [io.reactiverse.pgclient.PgCursor.close] * * * NOTE: This function has been automatically generated from [io.reactiverse.pgclient.PgCursor] using Vert.x codegen. */ suspend fun PgCursor.closeAwait(): Unit { return awaitResult { this.close { ar -> it.handle(ar.mapEmpty()) } } } ================================================ FILE: src/main/kotlin/io/reactiverse/kotlin/pgclient/PgNotification.kt ================================================ /* * Copyright 2019 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.reactiverse.kotlin.pgclient import io.reactiverse.pgclient.PgNotification /** * A function providing a DSL for building [io.reactiverse.pgclient.PgNotification] objects. * * A notification emited by Postgres. * * @param channel Set the channel value. * @param payload Set the payload value. * @param processId Set the process id. * *

        * NOTE: This function has been automatically generated from the [io.reactiverse.pgclient.PgNotification original] using Vert.x codegen. */ fun pgNotificationOf( channel: String? = null, payload: String? = null, processId: Int? = null): PgNotification = io.reactiverse.pgclient.PgNotification().apply { if (channel != null) { this.setChannel(channel) } if (payload != null) { this.setPayload(payload) } if (processId != null) { this.setProcessId(processId) } } /** * A function providing a DSL for building [io.reactiverse.pgclient.PgNotification] objects. * * A notification emited by Postgres. * * @param channel Set the channel value. * @param payload Set the payload value. * @param processId Set the process id. * *

        * NOTE: This function has been automatically generated from the [io.reactiverse.pgclient.PgNotification original] using Vert.x codegen. */ @Deprecated( message = "This function will be removed in a future version", replaceWith = ReplaceWith("pgNotificationOf(channel, payload, processId)") ) fun PgNotification( channel: String? = null, payload: String? = null, processId: Int? = null): PgNotification = io.reactiverse.pgclient.PgNotification().apply { if (channel != null) { this.setChannel(channel) } if (payload != null) { this.setPayload(payload) } if (processId != null) { this.setProcessId(processId) } } ================================================ FILE: src/main/kotlin/io/reactiverse/kotlin/pgclient/PgPool.kt ================================================ /* * Copyright 2019 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.reactiverse.kotlin.pgclient import io.reactiverse.pgclient.PgConnection import io.reactiverse.pgclient.PgPool import io.reactiverse.pgclient.PgRowSet import io.reactiverse.pgclient.PgTransaction import io.reactiverse.pgclient.Tuple import io.vertx.kotlin.coroutines.awaitResult suspend fun PgPool.preparedQueryAwait(sql: String): PgRowSet { return awaitResult { this.preparedQuery(sql, it) } } suspend fun PgPool.queryAwait(sql: String): PgRowSet { return awaitResult { this.query(sql, it) } } suspend fun PgPool.preparedQueryAwait(sql: String, arguments: Tuple): PgRowSet { return awaitResult { this.preparedQuery(sql, arguments, it) } } suspend fun PgPool.preparedBatchAwait(sql: String, batch: List): PgRowSet { return awaitResult { this.preparedBatch(sql, batch, it) } } /** * Suspending version of method [io.reactiverse.pgclient.PgPool.getConnection] * * @return [PgConnection] * * NOTE: This function has been automatically generated from [io.reactiverse.pgclient.PgPool] using Vert.x codegen. */ suspend fun PgPool.getConnectionAwait(): PgConnection { return awaitResult { this.getConnection(it) } } /** * Suspending version of method [io.reactiverse.pgclient.PgPool.begin] * * @return [PgTransaction] * * NOTE: This function has been automatically generated from [io.reactiverse.pgclient.PgPool] using Vert.x codegen. */ suspend fun PgPool.beginAwait(): PgTransaction { return awaitResult { this.begin(it) } } ================================================ FILE: src/main/kotlin/io/reactiverse/kotlin/pgclient/PgPoolOptions.kt ================================================ /* * Copyright 2019 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.reactiverse.kotlin.pgclient import io.reactiverse.pgclient.PgPoolOptions import io.reactiverse.pgclient.SslMode import io.vertx.core.net.JdkSSLEngineOptions import io.vertx.core.net.JksOptions import io.vertx.core.net.OpenSSLEngineOptions import io.vertx.core.net.PemKeyCertOptions import io.vertx.core.net.PemTrustOptions import io.vertx.core.net.PfxOptions import io.vertx.core.net.ProxyOptions import java.util.concurrent.TimeUnit /** * A function providing a DSL for building [io.reactiverse.pgclient.PgPoolOptions] objects. * * The options for configuring a connection pool. * * @param cachePreparedStatements * @param connectTimeout * @param crlPaths * @param crlValues * @param database * @param enabledCipherSuites * @param enabledSecureTransportProtocols * @param host * @param hostnameVerificationAlgorithm * @param idleTimeout * @param idleTimeoutUnit * @param jdkSslEngineOptions * @param keyStoreOptions * @param localAddress * @param logActivity * @param maxSize Set the maximum pool size * @param maxWaitQueueSize Set the maximum connection request allowed in the wait queue, any requests beyond the max size will result in an failure. If the value is set to a negative number then the queue will be unbounded. * @param metricsName * @param openSslEngineOptions * @param password * @param pemKeyCertOptions * @param pemTrustOptions * @param pfxKeyCertOptions * @param pfxTrustOptions * @param pipeliningLimit * @param port * @param proxyOptions * @param receiveBufferSize * @param reconnectAttempts * @param reconnectInterval * @param reuseAddress * @param reusePort * @param sendBufferSize * @param soLinger * @param ssl * @param sslHandshakeTimeout * @param sslHandshakeTimeoutUnit * @param sslMode Set [io.reactiverse.pgclient.SslMode] for the client, this option can be used to provide different levels of secure protection. * @param tcpCork * @param tcpFastOpen * @param tcpKeepAlive * @param tcpNoDelay * @param tcpQuickAck * @param trafficClass * @param trustAll * @param trustStoreOptions * @param useAlpn * @param usePooledBuffers * @param user * *

        * NOTE: This function has been automatically generated from the [io.reactiverse.pgclient.PgPoolOptions original] using Vert.x codegen. */ fun pgPoolOptionsOf( cachePreparedStatements: Boolean? = null, connectTimeout: Int? = null, crlPaths: Iterable? = null, crlValues: Iterable? = null, database: String? = null, enabledCipherSuites: Iterable? = null, enabledSecureTransportProtocols: Iterable? = null, host: String? = null, hostnameVerificationAlgorithm: String? = null, idleTimeout: Int? = null, idleTimeoutUnit: TimeUnit? = null, jdkSslEngineOptions: io.vertx.core.net.JdkSSLEngineOptions? = null, keyStoreOptions: io.vertx.core.net.JksOptions? = null, localAddress: String? = null, logActivity: Boolean? = null, maxSize: Int? = null, maxWaitQueueSize: Int? = null, metricsName: String? = null, openSslEngineOptions: io.vertx.core.net.OpenSSLEngineOptions? = null, password: String? = null, pemKeyCertOptions: io.vertx.core.net.PemKeyCertOptions? = null, pemTrustOptions: io.vertx.core.net.PemTrustOptions? = null, pfxKeyCertOptions: io.vertx.core.net.PfxOptions? = null, pfxTrustOptions: io.vertx.core.net.PfxOptions? = null, pipeliningLimit: Int? = null, port: Int? = null, proxyOptions: io.vertx.core.net.ProxyOptions? = null, receiveBufferSize: Int? = null, reconnectAttempts: Int? = null, reconnectInterval: Long? = null, reuseAddress: Boolean? = null, reusePort: Boolean? = null, sendBufferSize: Int? = null, soLinger: Int? = null, ssl: Boolean? = null, sslHandshakeTimeout: Long? = null, sslHandshakeTimeoutUnit: TimeUnit? = null, sslMode: SslMode? = null, tcpCork: Boolean? = null, tcpFastOpen: Boolean? = null, tcpKeepAlive: Boolean? = null, tcpNoDelay: Boolean? = null, tcpQuickAck: Boolean? = null, trafficClass: Int? = null, trustAll: Boolean? = null, trustStoreOptions: io.vertx.core.net.JksOptions? = null, useAlpn: Boolean? = null, usePooledBuffers: Boolean? = null, user: String? = null): PgPoolOptions = io.reactiverse.pgclient.PgPoolOptions().apply { if (cachePreparedStatements != null) { this.setCachePreparedStatements(cachePreparedStatements) } if (connectTimeout != null) { this.setConnectTimeout(connectTimeout) } if (crlPaths != null) { for (item in crlPaths) { this.addCrlPath(item) } } if (crlValues != null) { for (item in crlValues) { this.addCrlValue(item) } } if (database != null) { this.setDatabase(database) } if (enabledCipherSuites != null) { for (item in enabledCipherSuites) { this.addEnabledCipherSuite(item) } } if (enabledSecureTransportProtocols != null) { this.setEnabledSecureTransportProtocols(enabledSecureTransportProtocols.toSet()) } if (host != null) { this.setHost(host) } if (hostnameVerificationAlgorithm != null) { this.setHostnameVerificationAlgorithm(hostnameVerificationAlgorithm) } if (idleTimeout != null) { this.setIdleTimeout(idleTimeout) } if (idleTimeoutUnit != null) { this.setIdleTimeoutUnit(idleTimeoutUnit) } if (jdkSslEngineOptions != null) { this.setJdkSslEngineOptions(jdkSslEngineOptions) } if (keyStoreOptions != null) { this.setKeyStoreOptions(keyStoreOptions) } if (localAddress != null) { this.setLocalAddress(localAddress) } if (logActivity != null) { this.setLogActivity(logActivity) } if (maxSize != null) { this.setMaxSize(maxSize) } if (maxWaitQueueSize != null) { this.setMaxWaitQueueSize(maxWaitQueueSize) } if (metricsName != null) { this.setMetricsName(metricsName) } if (openSslEngineOptions != null) { this.setOpenSslEngineOptions(openSslEngineOptions) } if (password != null) { this.setPassword(password) } if (pemKeyCertOptions != null) { this.setPemKeyCertOptions(pemKeyCertOptions) } if (pemTrustOptions != null) { this.setPemTrustOptions(pemTrustOptions) } if (pfxKeyCertOptions != null) { this.setPfxKeyCertOptions(pfxKeyCertOptions) } if (pfxTrustOptions != null) { this.setPfxTrustOptions(pfxTrustOptions) } if (pipeliningLimit != null) { this.setPipeliningLimit(pipeliningLimit) } if (port != null) { this.setPort(port) } if (proxyOptions != null) { this.setProxyOptions(proxyOptions) } if (receiveBufferSize != null) { this.setReceiveBufferSize(receiveBufferSize) } if (reconnectAttempts != null) { this.setReconnectAttempts(reconnectAttempts) } if (reconnectInterval != null) { this.setReconnectInterval(reconnectInterval) } if (reuseAddress != null) { this.setReuseAddress(reuseAddress) } if (reusePort != null) { this.setReusePort(reusePort) } if (sendBufferSize != null) { this.setSendBufferSize(sendBufferSize) } if (soLinger != null) { this.setSoLinger(soLinger) } if (ssl != null) { this.setSsl(ssl) } if (sslHandshakeTimeout != null) { this.setSslHandshakeTimeout(sslHandshakeTimeout) } if (sslHandshakeTimeoutUnit != null) { this.setSslHandshakeTimeoutUnit(sslHandshakeTimeoutUnit) } if (sslMode != null) { this.setSslMode(sslMode) } if (tcpCork != null) { this.setTcpCork(tcpCork) } if (tcpFastOpen != null) { this.setTcpFastOpen(tcpFastOpen) } if (tcpKeepAlive != null) { this.setTcpKeepAlive(tcpKeepAlive) } if (tcpNoDelay != null) { this.setTcpNoDelay(tcpNoDelay) } if (tcpQuickAck != null) { this.setTcpQuickAck(tcpQuickAck) } if (trafficClass != null) { this.setTrafficClass(trafficClass) } if (trustAll != null) { this.setTrustAll(trustAll) } if (trustStoreOptions != null) { this.setTrustStoreOptions(trustStoreOptions) } if (useAlpn != null) { this.setUseAlpn(useAlpn) } if (usePooledBuffers != null) { this.setUsePooledBuffers(usePooledBuffers) } if (user != null) { this.setUser(user) } } /** * A function providing a DSL for building [io.reactiverse.pgclient.PgPoolOptions] objects. * * The options for configuring a connection pool. * * @param cachePreparedStatements * @param connectTimeout * @param crlPaths * @param crlValues * @param database * @param enabledCipherSuites * @param enabledSecureTransportProtocols * @param host * @param hostnameVerificationAlgorithm * @param idleTimeout * @param idleTimeoutUnit * @param jdkSslEngineOptions * @param keyStoreOptions * @param localAddress * @param logActivity * @param maxSize Set the maximum pool size * @param maxWaitQueueSize Set the maximum connection request allowed in the wait queue, any requests beyond the max size will result in an failure. If the value is set to a negative number then the queue will be unbounded. * @param metricsName * @param openSslEngineOptions * @param password * @param pemKeyCertOptions * @param pemTrustOptions * @param pfxKeyCertOptions * @param pfxTrustOptions * @param pipeliningLimit * @param port * @param proxyOptions * @param receiveBufferSize * @param reconnectAttempts * @param reconnectInterval * @param reuseAddress * @param reusePort * @param sendBufferSize * @param soLinger * @param ssl * @param sslHandshakeTimeout * @param sslHandshakeTimeoutUnit * @param sslMode Set [io.reactiverse.pgclient.SslMode] for the client, this option can be used to provide different levels of secure protection. * @param tcpCork * @param tcpFastOpen * @param tcpKeepAlive * @param tcpNoDelay * @param tcpQuickAck * @param trafficClass * @param trustAll * @param trustStoreOptions * @param useAlpn * @param usePooledBuffers * @param user * *

        * NOTE: This function has been automatically generated from the [io.reactiverse.pgclient.PgPoolOptions original] using Vert.x codegen. */ @Deprecated( message = "This function will be removed in a future version", replaceWith = ReplaceWith("pgPoolOptionsOf(cachePreparedStatements, connectTimeout, crlPaths, crlValues, database, enabledCipherSuites, enabledSecureTransportProtocols, host, hostnameVerificationAlgorithm, idleTimeout, idleTimeoutUnit, jdkSslEngineOptions, keyStoreOptions, localAddress, logActivity, maxSize, maxWaitQueueSize, metricsName, openSslEngineOptions, password, pemKeyCertOptions, pemTrustOptions, pfxKeyCertOptions, pfxTrustOptions, pipeliningLimit, port, proxyOptions, receiveBufferSize, reconnectAttempts, reconnectInterval, reuseAddress, reusePort, sendBufferSize, soLinger, ssl, sslHandshakeTimeout, sslHandshakeTimeoutUnit, sslMode, tcpCork, tcpFastOpen, tcpKeepAlive, tcpNoDelay, tcpQuickAck, trafficClass, trustAll, trustStoreOptions, useAlpn, usePooledBuffers, user)") ) fun PgPoolOptions( cachePreparedStatements: Boolean? = null, connectTimeout: Int? = null, crlPaths: Iterable? = null, crlValues: Iterable? = null, database: String? = null, enabledCipherSuites: Iterable? = null, enabledSecureTransportProtocols: Iterable? = null, host: String? = null, hostnameVerificationAlgorithm: String? = null, idleTimeout: Int? = null, idleTimeoutUnit: TimeUnit? = null, jdkSslEngineOptions: io.vertx.core.net.JdkSSLEngineOptions? = null, keyStoreOptions: io.vertx.core.net.JksOptions? = null, localAddress: String? = null, logActivity: Boolean? = null, maxSize: Int? = null, maxWaitQueueSize: Int? = null, metricsName: String? = null, openSslEngineOptions: io.vertx.core.net.OpenSSLEngineOptions? = null, password: String? = null, pemKeyCertOptions: io.vertx.core.net.PemKeyCertOptions? = null, pemTrustOptions: io.vertx.core.net.PemTrustOptions? = null, pfxKeyCertOptions: io.vertx.core.net.PfxOptions? = null, pfxTrustOptions: io.vertx.core.net.PfxOptions? = null, pipeliningLimit: Int? = null, port: Int? = null, proxyOptions: io.vertx.core.net.ProxyOptions? = null, receiveBufferSize: Int? = null, reconnectAttempts: Int? = null, reconnectInterval: Long? = null, reuseAddress: Boolean? = null, reusePort: Boolean? = null, sendBufferSize: Int? = null, soLinger: Int? = null, ssl: Boolean? = null, sslHandshakeTimeout: Long? = null, sslHandshakeTimeoutUnit: TimeUnit? = null, sslMode: SslMode? = null, tcpCork: Boolean? = null, tcpFastOpen: Boolean? = null, tcpKeepAlive: Boolean? = null, tcpNoDelay: Boolean? = null, tcpQuickAck: Boolean? = null, trafficClass: Int? = null, trustAll: Boolean? = null, trustStoreOptions: io.vertx.core.net.JksOptions? = null, useAlpn: Boolean? = null, usePooledBuffers: Boolean? = null, user: String? = null): PgPoolOptions = io.reactiverse.pgclient.PgPoolOptions().apply { if (cachePreparedStatements != null) { this.setCachePreparedStatements(cachePreparedStatements) } if (connectTimeout != null) { this.setConnectTimeout(connectTimeout) } if (crlPaths != null) { for (item in crlPaths) { this.addCrlPath(item) } } if (crlValues != null) { for (item in crlValues) { this.addCrlValue(item) } } if (database != null) { this.setDatabase(database) } if (enabledCipherSuites != null) { for (item in enabledCipherSuites) { this.addEnabledCipherSuite(item) } } if (enabledSecureTransportProtocols != null) { this.setEnabledSecureTransportProtocols(enabledSecureTransportProtocols.toSet()) } if (host != null) { this.setHost(host) } if (hostnameVerificationAlgorithm != null) { this.setHostnameVerificationAlgorithm(hostnameVerificationAlgorithm) } if (idleTimeout != null) { this.setIdleTimeout(idleTimeout) } if (idleTimeoutUnit != null) { this.setIdleTimeoutUnit(idleTimeoutUnit) } if (jdkSslEngineOptions != null) { this.setJdkSslEngineOptions(jdkSslEngineOptions) } if (keyStoreOptions != null) { this.setKeyStoreOptions(keyStoreOptions) } if (localAddress != null) { this.setLocalAddress(localAddress) } if (logActivity != null) { this.setLogActivity(logActivity) } if (maxSize != null) { this.setMaxSize(maxSize) } if (maxWaitQueueSize != null) { this.setMaxWaitQueueSize(maxWaitQueueSize) } if (metricsName != null) { this.setMetricsName(metricsName) } if (openSslEngineOptions != null) { this.setOpenSslEngineOptions(openSslEngineOptions) } if (password != null) { this.setPassword(password) } if (pemKeyCertOptions != null) { this.setPemKeyCertOptions(pemKeyCertOptions) } if (pemTrustOptions != null) { this.setPemTrustOptions(pemTrustOptions) } if (pfxKeyCertOptions != null) { this.setPfxKeyCertOptions(pfxKeyCertOptions) } if (pfxTrustOptions != null) { this.setPfxTrustOptions(pfxTrustOptions) } if (pipeliningLimit != null) { this.setPipeliningLimit(pipeliningLimit) } if (port != null) { this.setPort(port) } if (proxyOptions != null) { this.setProxyOptions(proxyOptions) } if (receiveBufferSize != null) { this.setReceiveBufferSize(receiveBufferSize) } if (reconnectAttempts != null) { this.setReconnectAttempts(reconnectAttempts) } if (reconnectInterval != null) { this.setReconnectInterval(reconnectInterval) } if (reuseAddress != null) { this.setReuseAddress(reuseAddress) } if (reusePort != null) { this.setReusePort(reusePort) } if (sendBufferSize != null) { this.setSendBufferSize(sendBufferSize) } if (soLinger != null) { this.setSoLinger(soLinger) } if (ssl != null) { this.setSsl(ssl) } if (sslHandshakeTimeout != null) { this.setSslHandshakeTimeout(sslHandshakeTimeout) } if (sslHandshakeTimeoutUnit != null) { this.setSslHandshakeTimeoutUnit(sslHandshakeTimeoutUnit) } if (sslMode != null) { this.setSslMode(sslMode) } if (tcpCork != null) { this.setTcpCork(tcpCork) } if (tcpFastOpen != null) { this.setTcpFastOpen(tcpFastOpen) } if (tcpKeepAlive != null) { this.setTcpKeepAlive(tcpKeepAlive) } if (tcpNoDelay != null) { this.setTcpNoDelay(tcpNoDelay) } if (tcpQuickAck != null) { this.setTcpQuickAck(tcpQuickAck) } if (trafficClass != null) { this.setTrafficClass(trafficClass) } if (trustAll != null) { this.setTrustAll(trustAll) } if (trustStoreOptions != null) { this.setTrustStoreOptions(trustStoreOptions) } if (useAlpn != null) { this.setUseAlpn(useAlpn) } if (usePooledBuffers != null) { this.setUsePooledBuffers(usePooledBuffers) } if (user != null) { this.setUser(user) } } ================================================ FILE: src/main/kotlin/io/reactiverse/kotlin/pgclient/PgPreparedQuery.kt ================================================ /* * Copyright 2019 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.reactiverse.kotlin.pgclient import io.reactiverse.pgclient.PgPreparedQuery import io.reactiverse.pgclient.PgRowSet import io.reactiverse.pgclient.Tuple import io.vertx.kotlin.coroutines.awaitResult /** * Suspending version of method [io.reactiverse.pgclient.PgPreparedQuery.execute] * * @return [PgRowSet] * * NOTE: This function has been automatically generated from [io.reactiverse.pgclient.PgPreparedQuery] using Vert.x codegen. */ suspend fun PgPreparedQuery.executeAwait(): PgRowSet { return awaitResult { this.execute(it) } } /** * Suspending version of method [io.reactiverse.pgclient.PgPreparedQuery.execute] * * @param args the list of arguments * @return [PgRowSet] * * NOTE: This function has been automatically generated from [io.reactiverse.pgclient.PgPreparedQuery] using Vert.x codegen. */ suspend fun PgPreparedQuery.executeAwait(args: Tuple): PgRowSet { return awaitResult { this.execute(args, it) } } /** * Suspending version of method [io.reactiverse.pgclient.PgPreparedQuery.batch] * * @param argsList the list of tuple for the batch * @return [PgRowSet] * * NOTE: This function has been automatically generated from [io.reactiverse.pgclient.PgPreparedQuery] using Vert.x codegen. */ suspend fun PgPreparedQuery.batchAwait(argsList: List): PgRowSet { return awaitResult { this.batch(argsList, it) } } /** * Suspending version of method [io.reactiverse.pgclient.PgPreparedQuery.close] * * * NOTE: This function has been automatically generated from [io.reactiverse.pgclient.PgPreparedQuery] using Vert.x codegen. */ suspend fun PgPreparedQuery.closeAwait(): Unit { return awaitResult { this.close { ar -> it.handle(ar.mapEmpty()) } } } ================================================ FILE: src/main/kotlin/io/reactiverse/kotlin/pgclient/PgStream.kt ================================================ /* * Copyright 2019 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.reactiverse.kotlin.pgclient import io.reactiverse.pgclient.PgStream import io.vertx.core.streams.WriteStream import io.vertx.kotlin.coroutines.awaitResult suspend fun PgStream.pipeToAwait(dst: WriteStream): Unit { return awaitResult { this.pipeTo(dst) { ar -> it.handle(ar.mapEmpty()) } } } /** * Suspending version of method [io.reactiverse.pgclient.PgStream.close] * * * NOTE: This function has been automatically generated from [io.reactiverse.pgclient.PgStream] using Vert.x codegen. */ suspend fun PgStream.closeAwait(): Unit { return awaitResult { this.close { ar -> it.handle(ar.mapEmpty()) } } } ================================================ FILE: src/main/kotlin/io/reactiverse/kotlin/pgclient/PgTransaction.kt ================================================ /* * Copyright 2019 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.reactiverse.kotlin.pgclient import io.reactiverse.pgclient.PgPreparedQuery import io.reactiverse.pgclient.PgRowSet import io.reactiverse.pgclient.PgTransaction import io.reactiverse.pgclient.Tuple import io.vertx.kotlin.coroutines.awaitResult /** * Suspending version of method [io.reactiverse.pgclient.PgTransaction.prepare] * * @param sql the sql * @return [PgPreparedQuery] * * NOTE: This function has been automatically generated from [io.reactiverse.pgclient.PgTransaction] using Vert.x codegen. */ suspend fun PgTransaction.prepareAwait(sql: String): PgPreparedQuery { return awaitResult { this.prepare(sql, it) } } /** * Suspending version of method [io.reactiverse.pgclient.PgTransaction.commit] * * * NOTE: This function has been automatically generated from [io.reactiverse.pgclient.PgTransaction] using Vert.x codegen. */ suspend fun PgTransaction.commitAwait(): Unit { return awaitResult { this.commit { ar -> it.handle(ar.mapEmpty()) } } } /** * Suspending version of method [io.reactiverse.pgclient.PgTransaction.rollback] * * * NOTE: This function has been automatically generated from [io.reactiverse.pgclient.PgTransaction] using Vert.x codegen. */ suspend fun PgTransaction.rollbackAwait(): Unit { return awaitResult { this.rollback { ar -> it.handle(ar.mapEmpty()) } } } suspend fun PgTransaction.queryAwait(sql: String): PgRowSet { return awaitResult { this.query(sql, it) } } suspend fun PgTransaction.preparedQueryAwait(sql: String): PgRowSet { return awaitResult { this.preparedQuery(sql, it) } } suspend fun PgTransaction.preparedQueryAwait(sql: String, arguments: Tuple): PgRowSet { return awaitResult { this.preparedQuery(sql, arguments, it) } } suspend fun PgTransaction.preparedBatchAwait(sql: String, batch: List): PgRowSet { return awaitResult { this.preparedBatch(sql, batch, it) } } ================================================ FILE: src/main/kotlin/io/reactiverse/kotlin/pgclient/data/Box.kt ================================================ /* * Copyright 2019 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.reactiverse.kotlin.pgclient.data import io.reactiverse.pgclient.data.Box import io.reactiverse.pgclient.data.Point /** * A function providing a DSL for building [io.reactiverse.pgclient.data.Box] objects. * * Rectangular box data type in Postgres represented by pairs of [io.reactiverse.pgclient.data.Point]s that are opposite corners of the box. * * @param lowerLeftCorner * @param upperRightCorner * *

        * NOTE: This function has been automatically generated from the [io.reactiverse.pgclient.data.Box original] using Vert.x codegen. */ fun boxOf( lowerLeftCorner: io.reactiverse.pgclient.data.Point? = null, upperRightCorner: io.reactiverse.pgclient.data.Point? = null): Box = io.reactiverse.pgclient.data.Box().apply { if (lowerLeftCorner != null) { this.setLowerLeftCorner(lowerLeftCorner) } if (upperRightCorner != null) { this.setUpperRightCorner(upperRightCorner) } } /** * A function providing a DSL for building [io.reactiverse.pgclient.data.Box] objects. * * Rectangular box data type in Postgres represented by pairs of [io.reactiverse.pgclient.data.Point]s that are opposite corners of the box. * * @param lowerLeftCorner * @param upperRightCorner * *

        * NOTE: This function has been automatically generated from the [io.reactiverse.pgclient.data.Box original] using Vert.x codegen. */ @Deprecated( message = "This function will be removed in a future version", replaceWith = ReplaceWith("boxOf(lowerLeftCorner, upperRightCorner)") ) fun Box( lowerLeftCorner: io.reactiverse.pgclient.data.Point? = null, upperRightCorner: io.reactiverse.pgclient.data.Point? = null): Box = io.reactiverse.pgclient.data.Box().apply { if (lowerLeftCorner != null) { this.setLowerLeftCorner(lowerLeftCorner) } if (upperRightCorner != null) { this.setUpperRightCorner(upperRightCorner) } } ================================================ FILE: src/main/kotlin/io/reactiverse/kotlin/pgclient/data/Circle.kt ================================================ /* * Copyright 2019 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.reactiverse.kotlin.pgclient.data import io.reactiverse.pgclient.data.Circle import io.reactiverse.pgclient.data.Point /** * A function providing a DSL for building [io.reactiverse.pgclient.data.Circle] objects. * * Circle data type in Postgres represented by a center [io.reactiverse.pgclient.data.Point] and radius. * * @param centerPoint * @param radius * *

        * NOTE: This function has been automatically generated from the [io.reactiverse.pgclient.data.Circle original] using Vert.x codegen. */ fun circleOf( centerPoint: io.reactiverse.pgclient.data.Point? = null, radius: Double? = null): Circle = io.reactiverse.pgclient.data.Circle().apply { if (centerPoint != null) { this.setCenterPoint(centerPoint) } if (radius != null) { this.setRadius(radius) } } /** * A function providing a DSL for building [io.reactiverse.pgclient.data.Circle] objects. * * Circle data type in Postgres represented by a center [io.reactiverse.pgclient.data.Point] and radius. * * @param centerPoint * @param radius * *

        * NOTE: This function has been automatically generated from the [io.reactiverse.pgclient.data.Circle original] using Vert.x codegen. */ @Deprecated( message = "This function will be removed in a future version", replaceWith = ReplaceWith("circleOf(centerPoint, radius)") ) fun Circle( centerPoint: io.reactiverse.pgclient.data.Point? = null, radius: Double? = null): Circle = io.reactiverse.pgclient.data.Circle().apply { if (centerPoint != null) { this.setCenterPoint(centerPoint) } if (radius != null) { this.setRadius(radius) } } ================================================ FILE: src/main/kotlin/io/reactiverse/kotlin/pgclient/data/Interval.kt ================================================ /* * Copyright 2019 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.reactiverse.kotlin.pgclient.data import io.reactiverse.pgclient.data.Interval /** * A function providing a DSL for building [io.reactiverse.pgclient.data.Interval] objects. * * Postgres Interval is date and time based * such as 120 years 3 months 332 days 20 hours 20 minutes 20.999999 seconds * * @param days * @param hours * @param microseconds * @param minutes * @param months * @param seconds * @param years * *

        * NOTE: This function has been automatically generated from the [io.reactiverse.pgclient.data.Interval original] using Vert.x codegen. */ fun intervalOf( days: Int? = null, hours: Int? = null, microseconds: Int? = null, minutes: Int? = null, months: Int? = null, seconds: Int? = null, years: Int? = null): Interval = io.reactiverse.pgclient.data.Interval().apply { if (days != null) { this.setDays(days) } if (hours != null) { this.setHours(hours) } if (microseconds != null) { this.setMicroseconds(microseconds) } if (minutes != null) { this.setMinutes(minutes) } if (months != null) { this.setMonths(months) } if (seconds != null) { this.setSeconds(seconds) } if (years != null) { this.setYears(years) } } /** * A function providing a DSL for building [io.reactiverse.pgclient.data.Interval] objects. * * Postgres Interval is date and time based * such as 120 years 3 months 332 days 20 hours 20 minutes 20.999999 seconds * * @param days * @param hours * @param microseconds * @param minutes * @param months * @param seconds * @param years * *

        * NOTE: This function has been automatically generated from the [io.reactiverse.pgclient.data.Interval original] using Vert.x codegen. */ @Deprecated( message = "This function will be removed in a future version", replaceWith = ReplaceWith("intervalOf(days, hours, microseconds, minutes, months, seconds, years)") ) fun Interval( days: Int? = null, hours: Int? = null, microseconds: Int? = null, minutes: Int? = null, months: Int? = null, seconds: Int? = null, years: Int? = null): Interval = io.reactiverse.pgclient.data.Interval().apply { if (days != null) { this.setDays(days) } if (hours != null) { this.setHours(hours) } if (microseconds != null) { this.setMicroseconds(microseconds) } if (minutes != null) { this.setMinutes(minutes) } if (months != null) { this.setMonths(months) } if (seconds != null) { this.setSeconds(seconds) } if (years != null) { this.setYears(years) } } ================================================ FILE: src/main/kotlin/io/reactiverse/kotlin/pgclient/data/Line.kt ================================================ /* * Copyright 2019 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.reactiverse.kotlin.pgclient.data import io.reactiverse.pgclient.data.Line /** * A function providing a DSL for building [io.reactiverse.pgclient.data.Line] objects. * * Line data type in Postgres represented by the linear equation Ax + By + C = 0, where A and B are not both zero. * * @param a * @param b * @param c * *

        * NOTE: This function has been automatically generated from the [io.reactiverse.pgclient.data.Line original] using Vert.x codegen. */ fun lineOf( a: Double? = null, b: Double? = null, c: Double? = null): Line = io.reactiverse.pgclient.data.Line().apply { if (a != null) { this.setA(a) } if (b != null) { this.setB(b) } if (c != null) { this.setC(c) } } /** * A function providing a DSL for building [io.reactiverse.pgclient.data.Line] objects. * * Line data type in Postgres represented by the linear equation Ax + By + C = 0, where A and B are not both zero. * * @param a * @param b * @param c * *

        * NOTE: This function has been automatically generated from the [io.reactiverse.pgclient.data.Line original] using Vert.x codegen. */ @Deprecated( message = "This function will be removed in a future version", replaceWith = ReplaceWith("lineOf(a, b, c)") ) fun Line( a: Double? = null, b: Double? = null, c: Double? = null): Line = io.reactiverse.pgclient.data.Line().apply { if (a != null) { this.setA(a) } if (b != null) { this.setB(b) } if (c != null) { this.setC(c) } } ================================================ FILE: src/main/kotlin/io/reactiverse/kotlin/pgclient/data/LineSegment.kt ================================================ /* * Copyright 2019 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.reactiverse.kotlin.pgclient.data import io.reactiverse.pgclient.data.LineSegment import io.reactiverse.pgclient.data.Point /** * A function providing a DSL for building [io.reactiverse.pgclient.data.LineSegment] objects. * * Finite line segment data type in Postgres represented by pairs of [io.reactiverse.pgclient.data.Point]s that are the endpoints of the segment. * * @param p1 * @param p2 * *

        * NOTE: This function has been automatically generated from the [io.reactiverse.pgclient.data.LineSegment original] using Vert.x codegen. */ fun lineSegmentOf( p1: io.reactiverse.pgclient.data.Point? = null, p2: io.reactiverse.pgclient.data.Point? = null): LineSegment = io.reactiverse.pgclient.data.LineSegment().apply { if (p1 != null) { this.setP1(p1) } if (p2 != null) { this.setP2(p2) } } /** * A function providing a DSL for building [io.reactiverse.pgclient.data.LineSegment] objects. * * Finite line segment data type in Postgres represented by pairs of [io.reactiverse.pgclient.data.Point]s that are the endpoints of the segment. * * @param p1 * @param p2 * *

        * NOTE: This function has been automatically generated from the [io.reactiverse.pgclient.data.LineSegment original] using Vert.x codegen. */ @Deprecated( message = "This function will be removed in a future version", replaceWith = ReplaceWith("lineSegmentOf(p1, p2)") ) fun LineSegment( p1: io.reactiverse.pgclient.data.Point? = null, p2: io.reactiverse.pgclient.data.Point? = null): LineSegment = io.reactiverse.pgclient.data.LineSegment().apply { if (p1 != null) { this.setP1(p1) } if (p2 != null) { this.setP2(p2) } } ================================================ FILE: src/main/kotlin/io/reactiverse/kotlin/pgclient/data/Path.kt ================================================ /* * Copyright 2019 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.reactiverse.kotlin.pgclient.data import io.reactiverse.pgclient.data.Path import io.reactiverse.pgclient.data.Point /** * A function providing a DSL for building [io.reactiverse.pgclient.data.Path] objects. * * Path data type in Postgres represented by lists of connected points. * Paths can be open, where the first and last points in the list are considered not connected, * or closed, where the first and last points are considered connected. * * @param open * @param points * *

        * NOTE: This function has been automatically generated from the [io.reactiverse.pgclient.data.Path original] using Vert.x codegen. */ fun pathOf( open: Boolean? = null, points: Iterable? = null): Path = io.reactiverse.pgclient.data.Path().apply { if (open != null) { this.setOpen(open) } if (points != null) { this.setPoints(points.toList()) } } /** * A function providing a DSL for building [io.reactiverse.pgclient.data.Path] objects. * * Path data type in Postgres represented by lists of connected points. * Paths can be open, where the first and last points in the list are considered not connected, * or closed, where the first and last points are considered connected. * * @param open * @param points * *

        * NOTE: This function has been automatically generated from the [io.reactiverse.pgclient.data.Path original] using Vert.x codegen. */ @Deprecated( message = "This function will be removed in a future version", replaceWith = ReplaceWith("pathOf(open, points)") ) fun Path( open: Boolean? = null, points: Iterable? = null): Path = io.reactiverse.pgclient.data.Path().apply { if (open != null) { this.setOpen(open) } if (points != null) { this.setPoints(points.toList()) } } ================================================ FILE: src/main/kotlin/io/reactiverse/kotlin/pgclient/data/Point.kt ================================================ /* * Copyright 2019 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.reactiverse.kotlin.pgclient.data import io.reactiverse.pgclient.data.Point /** * A function providing a DSL for building [io.reactiverse.pgclient.data.Point] objects. * * A Postgresql point. * * @param x * @param y * *

        * NOTE: This function has been automatically generated from the [io.reactiverse.pgclient.data.Point original] using Vert.x codegen. */ fun pointOf( x: Double? = null, y: Double? = null): Point = io.reactiverse.pgclient.data.Point().apply { if (x != null) { this.setX(x) } if (y != null) { this.setY(y) } } /** * A function providing a DSL for building [io.reactiverse.pgclient.data.Point] objects. * * A Postgresql point. * * @param x * @param y * *

        * NOTE: This function has been automatically generated from the [io.reactiverse.pgclient.data.Point original] using Vert.x codegen. */ @Deprecated( message = "This function will be removed in a future version", replaceWith = ReplaceWith("pointOf(x, y)") ) fun Point( x: Double? = null, y: Double? = null): Point = io.reactiverse.pgclient.data.Point().apply { if (x != null) { this.setX(x) } if (y != null) { this.setY(y) } } ================================================ FILE: src/main/kotlin/io/reactiverse/kotlin/pgclient/data/Polygon.kt ================================================ /* * Copyright 2019 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.reactiverse.kotlin.pgclient.data import io.reactiverse.pgclient.data.Polygon import io.reactiverse.pgclient.data.Point /** * A function providing a DSL for building [io.reactiverse.pgclient.data.Polygon] objects. * * Polygon data type in Postgres represented by lists of points (the vertexes of the polygon). * Polygons are very similar to closed paths, but are stored differently and have their own set of support routines. * * @param points * *

        * NOTE: This function has been automatically generated from the [io.reactiverse.pgclient.data.Polygon original] using Vert.x codegen. */ fun polygonOf( points: Iterable? = null): Polygon = io.reactiverse.pgclient.data.Polygon().apply { if (points != null) { this.setPoints(points.toList()) } } /** * A function providing a DSL for building [io.reactiverse.pgclient.data.Polygon] objects. * * Polygon data type in Postgres represented by lists of points (the vertexes of the polygon). * Polygons are very similar to closed paths, but are stored differently and have their own set of support routines. * * @param points * *

        * NOTE: This function has been automatically generated from the [io.reactiverse.pgclient.data.Polygon original] using Vert.x codegen. */ @Deprecated( message = "This function will be removed in a future version", replaceWith = ReplaceWith("polygonOf(points)") ) fun Polygon( points: Iterable? = null): Polygon = io.reactiverse.pgclient.data.Polygon().apply { if (points != null) { this.setPoints(points.toList()) } } ================================================ FILE: src/main/kotlin/io/reactiverse/kotlin/pgclient/pubsub/PgChannel.kt ================================================ /* * Copyright 2019 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.reactiverse.kotlin.pgclient.pubsub import io.reactiverse.pgclient.pubsub.PgChannel import io.vertx.core.streams.WriteStream import io.vertx.kotlin.coroutines.awaitResult suspend fun PgChannel.pipeToAwait(dst: WriteStream): Unit { return awaitResult { this.pipeTo(dst) { ar -> it.handle(ar.mapEmpty()) } } } ================================================ FILE: src/main/kotlin/io/reactiverse/kotlin/pgclient/pubsub/PgSubscriber.kt ================================================ /* * Copyright 2019 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.reactiverse.kotlin.pgclient.pubsub import io.reactiverse.pgclient.pubsub.PgSubscriber import io.vertx.kotlin.coroutines.awaitResult /** * Suspending version of method [io.reactiverse.pgclient.pubsub.PgSubscriber.connect] * * * NOTE: This function has been automatically generated from [io.reactiverse.pgclient.pubsub.PgSubscriber] using Vert.x codegen. */ suspend fun PgSubscriber.connectAwait(): Unit { return awaitResult { this.connect { ar -> it.handle(ar.mapEmpty()) } } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/ErrorCodes.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; /** * @author Julien Viet */ public class ErrorCodes { public static final String syntax_error = "42601"; public static final String invalid_text_representation = "22P02"; } ================================================ FILE: src/test/java/io/reactiverse/pgclient/JdbcTest.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import org.junit.Ignore; import org.junit.Test; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import static org.junit.Assert.assertEquals; public class JdbcTest extends JdbcTestBase { @Ignore @Test public void testInsertBatch() throws SQLException { PreparedStatement ps = con.prepareStatement("INSERT INTO Test (id, val) VALUES (?, ?)"); ps.setInt(1, 2000); ps.setString(2, "Hello"); ps.addBatch(); ps.setInt(1, 2001); ps.setString(2, "Vert.x"); ps.addBatch(); ps.setInt(1, 2002); ps.setString(2, "World"); ps.addBatch(); ps.executeBatch(); assertEquals(-1, ps.getUpdateCount()); ps.close(); assertEquals(true, ps.isClosed()); } @Ignore @Test public void testInsertPreparedStmtWithId() throws SQLException { PreparedStatement ps = con.prepareStatement("INSERT INTO Fortune (id , message) VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS); ps.setInt(1, 9000); ps.setString(2, "Hello World"); assertEquals(1, ps.executeUpdate()); ResultSet re = ps.getGeneratedKeys(); re.next(); assertEquals(9000, re.getInt(1)); assertEquals("Hello World", re.getString(2)); ps.close(); } @Ignore @Test public void testUpdatePreparedStmtWithId() throws SQLException { con.setAutoCommit(false); PreparedStatement ps = con.prepareStatement("UPDATE Fortune SET message = ? WHERE id = ?", Statement.RETURN_GENERATED_KEYS); ps.setString(1, "Hello World"); ps.setInt(2, 1); assertEquals(1, ps.executeUpdate()); con.commit(); ResultSet re = ps.getGeneratedKeys(); re.next(); assertEquals(1, re.getInt(1)); assertEquals("Hello World", re.getString(2)); ps.close(); } @Test public void testPreparedQuery() throws SQLException { PreparedStatement ps = con.prepareStatement("SELECT * FROM Fortune WHERE id=(?)"); ps.setInt(1, 1); ResultSet resultSet = ps.executeQuery(); ps.close(); } @Test public void testPreparedQueryWithFetch() throws SQLException { con.setAutoCommit(false); PreparedStatement ps = con.prepareStatement( "SELECT * FROM World", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.FETCH_FORWARD); ps.setFetchSize(2); ResultSet resultSet = ps.executeQuery(); int count = 4; while (resultSet.next()) { if (count-- == 0) { break; } } resultSet.close(); ps.close(); } @Test public void testCursor() throws SQLException { con.setAutoCommit(false); Statement ps = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); ps.setFetchSize(3); ResultSet rs = ps.executeQuery("SELECT * FROM Fortune"); int count = 0; while (rs.next()) { count++; } System.out.println("got result " + count); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/JdbcTestBase.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import org.junit.After; import org.junit.Before; import org.postgresql.PGProperty; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; public class JdbcTestBase extends PgTestBase { Connection con; @Before public void setUp() throws Exception { Properties props = new Properties(); PGProperty.PREPARE_THRESHOLD.set(props, -1); PGProperty.BINARY_TRANSFER.set(props, "true"); // PGProperty.BINARY_TRANSFER_ENABLE.set(props, "true"); PGProperty.USER.set(props, "postgres"); PGProperty.PASSWORD.set(props, "postgres"); con = DriverManager.getConnection("jdbc:postgresql://" + options.getHost() + ":" + options.getPort() + "/postgres", props); } @After public void tearDown() throws SQLException { if (con != null) { con.close(); } } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/NumericTest.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.reactiverse.pgclient.data.Numeric; import org.junit.Test; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.Random; import java.util.function.Consumer; import java.util.function.Function; import static org.junit.Assert.*; public class NumericTest { private Random random = new Random(); private BigDecimal bigDecimalValue = new BigDecimal(new BigInteger(100, random), 50); private BigInteger bigIntegerValue = new BigInteger(100, random); private long longValue = random.nextLong(); private short shortValue = (short) random.nextInt(); private int intValue = random.nextInt(); private double doubleValue = random.nextDouble(); private float floatValue = random.nextFloat(); @Test public void testCreate() { assertEquals(shortValue, Numeric.create(shortValue).shortValue()); assertEquals(intValue, Numeric.create(intValue).intValue()); assertEquals(longValue, Numeric.create(longValue).longValue()); assertEquals(floatValue, Numeric.create(floatValue).floatValue(), 0.01f); assertEquals(doubleValue, Numeric.create(doubleValue).doubleValue(), 0.01f); assertEquals(bigIntegerValue, Numeric.create(bigIntegerValue).bigIntegerValue()); assertEquals(bigDecimalValue, Numeric.create(bigDecimalValue).bigDecimalValue()); } @Test public void testParse() { assertEquals(Numeric.NaN, Numeric.parse("NaN")); assertEquals(Numeric.create(bigDecimalValue), Numeric.parse(bigDecimalValue.toString())); assertEquals(Numeric.create(bigIntegerValue), Numeric.parse(bigIntegerValue.toString())); assertEquals(Numeric.create(longValue), Numeric.parse("" + longValue)); assertEquals(Numeric.create(shortValue), Numeric.parse("" + shortValue)); assertEquals(Numeric.create(intValue), Numeric.parse("" + intValue)); assertEquals(Numeric.create(floatValue), Numeric.parse("" + floatValue)); assertEquals(Numeric.create(doubleValue), Numeric.parse("" + doubleValue)); } @Test public void testMethods() { Number[] numbers = { Double.NaN, Double.NaN, Float.NaN, bigDecimalValue, bigIntegerValue, longValue, shortValue, intValue, doubleValue, floatValue, }; Numeric[] test = { Numeric.NaN, Numeric.create(Double.NaN), Numeric.create(Float.NaN), Numeric.create(bigDecimalValue), Numeric.create(bigIntegerValue), Numeric.create(longValue), Numeric.create(shortValue), Numeric.create(intValue), Numeric.create(doubleValue), Numeric.create(floatValue), }; for (int i = 0;i < numbers.length;i++) { assertEquals(Double.isNaN(numbers[i].doubleValue()), test[i].isNaN()); assertEquals(numbers[i].byteValue(), test[i].byteValue()); assertEquals(numbers[i].intValue(), test[i].intValue()); assertEquals(numbers[i].shortValue(), test[i].shortValue()); assertEquals(numbers[i].longValue(), test[i].longValue()); assertEquals(numbers[i].floatValue(), test[i].floatValue(), 0.01f); assertEquals(numbers[i].doubleValue(), test[i].doubleValue(), 0.01d); assertEquals(Numeric.create(numbers[i]), test[i]); assertEquals(test[i], Numeric.create(numbers[i])); assertEquals(numbers[i].toString(), test[i].toString()); } } @Test public void testFormatException() { Consumer checker = r -> { try { r.run(); fail(); } catch (NumberFormatException ignore) { } }; for (Number number : Arrays.asList( Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY)) { checker.accept(() -> { Numeric.create(number); }); } checker.accept(() -> { Numeric.parse("foobar"); }); } @Test public void testNull() { Function f1 = Numeric::create; Function f2 = Numeric::parse; for (Function c : Arrays.>asList(f1, f2)) try { c.apply(null); fail(); } catch (NullPointerException ignore) { } } @Test public void testEqualsAndHashCode() { int intValue = random.nextInt(1000); Numeric[] numerics = { Numeric.create(intValue), Numeric.create((short)intValue), Numeric.create((double)intValue), Numeric.create((long)intValue), Numeric.create((float)intValue), Numeric.create(new BigInteger("" + intValue)), Numeric.create(new BigDecimal("" + intValue)), }; for (Numeric l : numerics) { for (Numeric r : numerics) { assertEquals(l, r); assertEquals(l.hashCode(), r.hashCode()); } } assertEquals(Numeric.create(Double.NaN), Numeric.create(Float.NaN)); for (Numeric l : numerics) { assertNotSame(Numeric.NaN, l); assertNotSame(l, Numeric.NaN); assertNotSame(Numeric.create(Float.NaN), l); assertNotSame(l, Numeric.create(Float.NaN)); assertNotSame(Numeric.create(Double.NaN), l); assertNotSame(l, Numeric.create(Double.NaN)); } } /** * Compute the lenght of the array in bytes. * * @param size * @return */ private static int len(int size) { int d = (int) (((double)size * Math.log(10000) / Math.log(2))); return d; } @Test public void testFoo() { } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/PgClientTestBase.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.reactiverse.pgclient.impl.ArrayTuple; import io.vertx.core.*; import io.vertx.core.net.NetSocket; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * @author Julien Viet */ @RunWith(VertxUnitRunner.class) public abstract class PgClientTestBase extends PgTestBase { Vertx vertx; Consumer>> connector; PgConnectOptions options; @Before public void setup() { vertx = Vertx.vertx(); options = new PgConnectOptions(PgTestBase.options); } @After public void teardown(TestContext ctx) { vertx.close(ctx.asyncAssertSuccess()); } @Test public void testConnect(TestContext ctx) { Async async = ctx.async(); connector.accept(ctx.asyncAssertSuccess(conn -> { async.complete(); })); } @Test public void testConnectInvalidDatabase(TestContext ctx) { Async async = ctx.async(); options.setDatabase("blah_db"); connector.accept(ctx.asyncAssertFailure(conn -> { ctx.assertEquals("database \"blah_db\" does not exist", conn.getMessage()); async.complete(); })); } @Test public void testConnectInvalidPassword(TestContext ctx) { Async async = ctx.async(); options.setPassword("incorrect"); connector.accept(ctx.asyncAssertFailure(conn -> { ctx.assertEquals("password authentication failed for user \"postgres\"", conn.getMessage()); async.complete(); })); } @Test public void testConnectInvalidUsername(TestContext ctx) { Async async = ctx.async(); options.setUser("vertx"); connector.accept(ctx.asyncAssertFailure(err -> { PgException ex = (PgException) err; // Class 28 — Invalid Authorization Specification ctx.assertEquals(ex.getCode().substring(0, 2), "28"); ctx.assertEquals(ex.getSeverity(), "FATAL"); async.complete(); })); } @Test public void testConnectNonSSLServer(TestContext ctx) { Async async = ctx.async(); options.setSslMode(SslMode.REQUIRE).setTrustAll(true); connector.accept(ctx.asyncAssertFailure(err -> { ctx.assertEquals("Postgres Server does not handle SSL connection", err.getMessage()); async.complete(); })); } @Test public void testQuery(TestContext ctx) { Async async = ctx.async(); connector.accept(ctx.asyncAssertSuccess(conn -> { conn.query("SELECT id, randomnumber from WORLD", ctx.asyncAssertSuccess(result -> { ctx.assertEquals(10000, result.size()); Iterator it = result.iterator(); for (int i = 0; i < 10000; i++) { Row row = it.next(); ctx.assertEquals(2, row.size()); ctx.assertTrue(row.getValue(0) instanceof Integer); ctx.assertEquals(row.getValue("id"), row.getValue(0)); ctx.assertTrue(row.getValue(1) instanceof Integer); ctx.assertEquals(row.getValue("randomnumber"), row.getValue(1)); } async.complete(); })); })); } @Test public void testMultipleQuery(TestContext ctx) { Async async = ctx.async(); connector.accept(ctx.asyncAssertSuccess(conn -> { conn.query("SELECT id, message from FORTUNE LIMIT 1;SELECT message, id from FORTUNE LIMIT 1", ctx.asyncAssertSuccess(result1 -> { ctx.assertEquals(1, result1.size()); ctx.assertEquals(Arrays.asList("id", "message"), result1.columnsNames()); Tuple row1 = result1.iterator().next(); ctx.assertTrue(row1.getValue(0) instanceof Integer); ctx.assertTrue(row1.getValue(1) instanceof String); PgRowSet result2 = result1.next(); ctx.assertNotNull(result2); ctx.assertEquals(1, result2.size()); ctx.assertEquals(Arrays.asList("message", "id"), result2.columnsNames()); Tuple row2 = result2.iterator().next(); ctx.assertTrue(row2.getValue(0) instanceof String); ctx.assertTrue(row2.getValue(1) instanceof Integer); ctx.assertNull(result2.next()); async.complete(); })); })); } @Test public void testQueryError(TestContext ctx) { Async async = ctx.async(); connector.accept(ctx.asyncAssertSuccess(conn -> { conn.query("SELECT whatever from DOES_NOT_EXIST", ctx.asyncAssertFailure(err -> { async.complete(); })); })); } @Test public void testUpdate(TestContext ctx) { Async async = ctx.async(); connector.accept(ctx.asyncAssertSuccess(client -> { deleteFromTestTable(ctx, client, () -> { client.query("INSERT INTO Test (id, val) VALUES (1, 'Whatever')", ctx.asyncAssertSuccess(r1 -> { ctx.assertEquals(1, r1.rowCount()); client.query("UPDATE Test SET val = 'Whatever' WHERE id = 1", ctx.asyncAssertSuccess(r2 -> { ctx.assertEquals(1, r2.rowCount()); async.complete(); })); })); }); })); } @Test public void testInsert(TestContext ctx) { Async async = ctx.async(); connector.accept(ctx.asyncAssertSuccess(client -> { deleteFromTestTable(ctx, client, () -> { client.query("INSERT INTO Test (id, val) VALUES (1, 'Whatever')", ctx.asyncAssertSuccess(r1 -> { ctx.assertEquals(1, r1.rowCount()); async.complete(); })); }); })); } @Test public void testInsertReturning(TestContext ctx) { Async async = ctx.async(); connector.accept(ctx.asyncAssertSuccess(client -> { deleteFromTestTable(ctx, client, () -> { client.preparedQuery("INSERT INTO Test (id, val) VALUES ($1, $2) RETURNING id", Tuple.of(14, "SomeMessage"), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(14, result.iterator().next().getInteger("id")); async.complete(); })); }); })); } @Test public void testInsertReturningError(TestContext ctx) { Async async = ctx.async(); connector.accept(ctx.asyncAssertSuccess(client -> { deleteFromTestTable(ctx, client, () -> { client.preparedQuery("INSERT INTO Test (id, val) VALUES ($1, $2) RETURNING id", Tuple.of(15, "SomeMessage"), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(15, result.iterator().next().getInteger("id")); client.preparedQuery("INSERT INTO Test (id, val) VALUES ($1, $2) RETURNING id", Tuple.of(15, "SomeMessage"), ctx.asyncAssertFailure(err -> { ctx.assertEquals("23505", ((PgException) err).getCode()); async.complete(); })); })); }); })); } @Test public void testDelete(TestContext ctx) { Async async = ctx.async(); connector.accept(ctx.asyncAssertSuccess(client -> { deleteFromTestTable(ctx, client, () -> { insertIntoTestTable(ctx, client, 10, () -> { client.query("DELETE FROM Test where id = 6", ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.rowCount()); async.complete(); })); }); }); })); } static int randomWorld() { return 1 + ThreadLocalRandom.current().nextInt(10000); } @Test public void testBatchSelect(TestContext ctx) { Async async = ctx.async(); connector.accept(ctx.asyncAssertSuccess(conn -> { List batch = new ArrayList<>(); batch.add(Tuple.tuple()); batch.add(Tuple.tuple()); conn.preparedBatch("SELECT count(id) FROM World", batch, ctx.asyncAssertSuccess(result -> { ctx.assertEquals(result.size(), result.next().size()); async.complete(); })); })); } @Test public void testDisconnectAbruptlyDuringStartup(TestContext ctx) { Async async = ctx.async(); ProxyServer proxy = ProxyServer.create(vertx, options.getPort(), options.getHost()); proxy.proxyHandler(conn -> { NetSocket clientSo = conn.clientSocket(); clientSo.handler(buff -> { clientSo.close(); }); clientSo.resume(); }); proxy.listen(8080, "localhost", ctx.asyncAssertSuccess(v1 -> { options.setPort(8080).setHost("localhost"); connector.accept(ctx.asyncAssertFailure(err -> async.complete())); })); } @Test public void testTx(TestContext ctx) { Async async = ctx.async(); connector.accept(ctx.asyncAssertSuccess(conn -> { conn.query("BEGIN", ctx.asyncAssertSuccess(result1 -> { ctx.assertEquals(0, result1.size()); ctx.assertNotNull(result1.iterator()); conn.query("COMMIT", ctx.asyncAssertSuccess(result2 -> { ctx.assertEquals(0, result2.size()); async.complete(); })); })); })); } @Test public void testPreparedUpdate(TestContext ctx) { Async async = ctx.async(); connector.accept(ctx.asyncAssertSuccess(client -> { deleteFromTestTable(ctx, client, () -> { client.query("INSERT INTO Test (id, val) VALUES (2, 'Whatever')", ctx.asyncAssertSuccess(r1 -> { ctx.assertEquals(1, r1.rowCount()); client.preparedQuery("UPDATE Test SET val = 'PgClient Rocks!' WHERE id = 2", ctx.asyncAssertSuccess(res1 -> { ctx.assertEquals(1, res1.rowCount()); client.preparedQuery("SELECT val FROM Test WHERE id = 2", ctx.asyncAssertSuccess(res2 -> { ctx.assertEquals("PgClient Rocks!", res2.iterator().next().getValue(0)); async.complete(); })); })); })); }); })); } @Test public void testPreparedUpdateWithParams(TestContext ctx) { Async async = ctx.async(); connector.accept(ctx.asyncAssertSuccess(client -> { client.query("INSERT INTO Test (id, val) VALUES (2, 'Whatever')", ctx.asyncAssertSuccess(r1 -> { ctx.assertEquals(1, r1.rowCount()); client.preparedQuery("UPDATE Test SET val = $1 WHERE id = $2", Tuple.of("PgClient Rocks Again!!", 2), ctx.asyncAssertSuccess(res1 -> { ctx.assertEquals(1, res1.rowCount()); client.preparedQuery("SELECT val FROM Test WHERE id = $1", Tuple.of(2), ctx.asyncAssertSuccess(res2 -> { ctx.assertEquals("PgClient Rocks Again!!", res2.iterator().next().getValue(0)); async.complete(); })); })); })); })); } @Test public void testPreparedUpdateWithNullParams(TestContext ctx) { Async async = ctx.async(); connector.accept(ctx.asyncAssertSuccess(client -> client.preparedQuery( "INSERT INTO \"AllDataTypes\" (boolean, int2, int4, int8, float4, float8, char, varchar, text, enum, name, numeric, uuid, date, time, timetz, timestamp, timestamptz, interval, bytea, json, jsonb, point, line, lseg, box, path, polygon, circle) " + "VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, $29)", new ArrayTuple(IntStream.range(1, 30).mapToObj(index -> null).collect(Collectors.toList())), ctx.asyncAssertSuccess(insertResult -> { ctx.assertEquals(1, insertResult.rowCount()); async.complete(); }) ) )); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/PgConnectOptionsProviderTest.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import org.junit.Test; import static org.junit.Assert.*; /** * @author Billy Yuan */ public class PgConnectOptionsProviderTest { private String connectionUri; private PgConnectOptions expectedConfiguration; private PgConnectOptions actualConfiguration; @Test public void testValidUri1() { connectionUri = "postgresql://"; actualConfiguration = PgConnectOptions.fromUri(connectionUri); expectedConfiguration = new PgConnectOptions(); assertEquals(expectedConfiguration, actualConfiguration); } @Test public void testValidUri2() { connectionUri = "postgresql://myhost"; actualConfiguration = PgConnectOptions.fromUri(connectionUri); expectedConfiguration = new PgConnectOptions() .setHost("myhost"); assertEquals(expectedConfiguration, actualConfiguration); } @Test public void testValidUri3() { connectionUri = "postgresql://myhost:5433"; actualConfiguration = PgConnectOptions.fromUri(connectionUri); expectedConfiguration = new PgConnectOptions() .setHost("myhost") .setPort(5433); assertEquals(expectedConfiguration, actualConfiguration); } @Test public void testValidUri4() { connectionUri = "postgresql://myhost/mydb"; actualConfiguration = PgConnectOptions.fromUri(connectionUri); expectedConfiguration = new PgConnectOptions() .setHost("myhost") .setDatabase("mydb"); assertEquals(expectedConfiguration, actualConfiguration); } @Test public void testValidUri5() { connectionUri = "postgresql://user@myhost"; actualConfiguration = PgConnectOptions.fromUri(connectionUri); expectedConfiguration = new PgConnectOptions() .setUser("user") .setHost("myhost"); assertEquals(expectedConfiguration, actualConfiguration); } @Test public void testValidUri6() { connectionUri = "postgresql://user:secret@myhost"; actualConfiguration = PgConnectOptions.fromUri(connectionUri); expectedConfiguration = new PgConnectOptions() .setUser("user") .setPassword("secret") .setHost("myhost"); assertEquals(expectedConfiguration, actualConfiguration); } @Test public void testValidUri7() { connectionUri = "postgresql://other@localhost/otherdb?port=5433&password=secret"; actualConfiguration = PgConnectOptions.fromUri(connectionUri); expectedConfiguration = new PgConnectOptions() .setUser("other") .setPassword("secret") .setHost("localhost") .setPort(5433) .setDatabase("otherdb"); assertEquals(expectedConfiguration, actualConfiguration); } @Test public void testValidUri8() { connectionUri = "postgresql:///dbname?host=/var/lib/postgresql"; actualConfiguration = PgConnectOptions.fromUri(connectionUri); expectedConfiguration = new PgConnectOptions() .setHost("/var/lib/postgresql") .setDatabase("dbname"); assertEquals(expectedConfiguration, actualConfiguration); } @Test public void testValidUri9() { connectionUri = "postgresql://%2Fvar%2Flib%2Fpostgresql/dbname"; actualConfiguration = PgConnectOptions.fromUri(connectionUri); expectedConfiguration = new PgConnectOptions() .setHost("/var/lib/postgresql") .setDatabase("dbname"); assertEquals(expectedConfiguration, actualConfiguration); } @Test public void testValidUri10() { connectionUri = "postgresql://user@myhost?sslmode=require"; actualConfiguration = PgConnectOptions.fromUri(connectionUri); expectedConfiguration = new PgConnectOptions() .setHost("myhost") .setUser("user") .setSslMode(SslMode.REQUIRE); assertEquals(expectedConfiguration, actualConfiguration); } @Test(expected = IllegalArgumentException.class) public void testInvalidUri1() { connectionUri = "postgrsql://username"; actualConfiguration = PgConnectOptions.fromUri(connectionUri); } @Test(expected = IllegalArgumentException.class) public void testInvalidUri2() { connectionUri = "postgresql://username:password@loc//dbname"; actualConfiguration = PgConnectOptions.fromUri(connectionUri); } @Test(expected = IllegalArgumentException.class) public void testInvalidUri3() { connectionUri = "postgresql://user@:passowrd@localhost/dbname/qwer"; actualConfiguration = PgConnectOptions.fromUri(connectionUri); } @Test(expected = IllegalArgumentException.class) public void testInvalidUri4() { connectionUri = "postgresql://user:password@localhost:655355/dbname"; actualConfiguration = PgConnectOptions.fromUri(connectionUri); } @Test(expected = IllegalArgumentException.class) public void testInvalidUri5() { connectionUri = "postgresql://user@localhost?port=1234&port"; actualConfiguration = PgConnectOptions.fromUri(connectionUri); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/PgConnectionTest.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import org.junit.Test; import java.util.ArrayList; import java.util.List; /** * @author Julien Viet */ public class PgConnectionTest extends PgConnectionTestBase { public PgConnectionTest() { connector = (handler) -> PgClient.connect(vertx, options, handler); } @Test public void testBatchUpdate(TestContext ctx) { Async async = ctx.async(); connector.accept(ctx.asyncAssertSuccess(conn -> { deleteFromTestTable(ctx, conn, () -> { insertIntoTestTable(ctx, conn, 10, () -> { conn.prepare("UPDATE Test SET val=$1 WHERE id=$2", ctx.asyncAssertSuccess(ps -> { List batch = new ArrayList<>(); batch.add(Tuple.of("val0", 0)); batch.add(Tuple.of("val1", 1)); ps.batch(batch, ctx.asyncAssertSuccess(result -> { for (int i = 0;i < 2;i++) { ctx.assertEquals(1, result.rowCount()); result = result.next(); } ctx.assertNull(result); ps.close(ctx.asyncAssertSuccess(v -> { async.complete(); })); })); })); }); }); })); } @Test public void testClose(TestContext ctx) { Async async = ctx.async(); connector.accept(ctx.asyncAssertSuccess(conn -> { conn.closeHandler(v -> { async.complete(); }); conn.close(); })); } @Test public void testCloseWithErrorInProgress(TestContext ctx) { Async async = ctx.async(2); connector.accept(ctx.asyncAssertSuccess(conn -> { conn.query("SELECT whatever from DOES_NOT_EXIST", ctx.asyncAssertFailure(err -> { ctx.assertEquals(2, async.count()); async.countDown(); })); conn.closeHandler(v -> { ctx.assertEquals(1, async.count()); async.countDown(); }); conn.close(); })); } @Test public void testCloseWithQueryInProgress(TestContext ctx) { Async async = ctx.async(2); connector.accept(ctx.asyncAssertSuccess(conn -> { conn.query("SELECT id, randomnumber from WORLD", ctx.asyncAssertSuccess(result -> { ctx.assertEquals(2, async.count()); ctx.assertEquals(10000, result.size()); async.countDown(); })); conn.closeHandler(v -> { ctx.assertEquals(1, async.count()); async.countDown(); }); conn.close(); })); } @Test public void testQueueQueries(TestContext ctx) { int num = 1000; Async async = ctx.async(num + 1); connector.accept(ctx.asyncAssertSuccess(conn -> { for (int i = 0;i < num;i++) { conn.query("SELECT id, randomnumber from WORLD", ar -> { if (ar.succeeded()) { PgResult result = ar.result(); ctx.assertEquals(10000, result.size()); } else { ctx.assertEquals("closed", ar.cause().getMessage()); } async.countDown(); }); } conn.closeHandler(v -> { ctx.assertEquals(1, async.count()); async.countDown(); }); conn.close(); })); } @Test public void testCancelRequest(TestContext ctx) { Async async = ctx.async(2); connector.accept(ctx.asyncAssertSuccess(conn -> { conn.query("SELECT pg_sleep(10)", ctx.asyncAssertFailure(error -> { ctx.assertEquals("canceling statement due to user request", error.getMessage()); async.countDown(); })); conn.cancelRequest(ctx.asyncAssertSuccess()); conn.closeHandler(v -> { ctx.assertEquals(1, async.count()); async.countDown(); }); conn.close(); })); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/PgConnectionTestBase.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.vertx.core.*; import io.vertx.core.buffer.Buffer; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.Test; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; /** * @author Julien Viet */ @RunWith(VertxUnitRunner.class) public abstract class PgConnectionTestBase extends PgClientTestBase { @Test public void testDisconnectAbruptly(TestContext ctx) { Async async = ctx.async(); ProxyServer proxy = ProxyServer.create(vertx, options.getPort(), options.getHost()); proxy.proxyHandler(conn -> { vertx.setTimer(200, id -> { conn.close(); }); conn.connect(); }); proxy.listen(8080, "localhost", ctx.asyncAssertSuccess(v1 -> { options.setPort(8080).setHost("localhost"); connector.accept(ctx.asyncAssertSuccess(conn -> { conn.closeHandler(v2 -> { async.complete(); }); })); })); } @Test public void testProtocolError(TestContext ctx) { Async async = ctx.async(); ProxyServer proxy = ProxyServer.create(vertx, options.getPort(), options.getHost()); CompletableFuture connected = new CompletableFuture<>(); proxy.proxyHandler(conn -> { connected.thenAccept(v -> { System.out.println("send bogus"); Buffer bogusMsg = Buffer.buffer(); bogusMsg.appendByte((byte) 'R'); // Authentication bogusMsg.appendInt(0); bogusMsg.appendInt(1); bogusMsg.setInt(1, bogusMsg.length() - 1); conn.clientSocket().write(bogusMsg); }); conn.connect(); }); proxy.listen(8080, "localhost", ctx.asyncAssertSuccess(v1 -> { options.setPort(8080).setHost("localhost"); connector.accept(ctx.asyncAssertSuccess(conn -> { AtomicInteger count = new AtomicInteger(); conn.exceptionHandler(err -> { ctx.assertEquals(err.getClass(), UnsupportedOperationException.class); count.incrementAndGet(); }); conn.closeHandler(v -> { ctx.assertEquals(1, count.get()); async.complete(); }); connected.complete(null); })); })); } @Test public void testTx(TestContext ctx) { Async async = ctx.async(); connector.accept(ctx.asyncAssertSuccess(conn -> { conn.query("BEGIN", ctx.asyncAssertSuccess(result1 -> { ctx.assertEquals(0, result1.size()); ctx.assertNotNull(result1.iterator()); conn.query("COMMIT", ctx.asyncAssertSuccess(result2 -> { ctx.assertEquals(0, result2.size()); async.complete(); })); })); })); } /* @Test public void testSQLConnection(TestContext ctx) { Async async = ctx.async(); PgClientImpl client = (PgClientImpl) PgClient.create(vertx, options); client.connect(ctx.asyncAssertSuccess(conn -> { conn.query("SELECT 1", ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.rowCount()); async.complete(); })); })); } @Test public void testSelectForQueryWithParams(TestContext ctx) { Async async = ctx.async(); PgClientImpl client = (PgClientImpl) PgClient.create(vertx, options); client.connect(c -> { SQLConnection conn = c.result(); conn.queryWithParams("SELECT * FROM Fortune WHERE id=$1", new JsonArray().add(1) , ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.rowCount()); async.complete(); })); }); } @Test public void testInsertForUpdateWithParams(TestContext ctx) { Async async = ctx.async(); PgClientImpl client = (PgClientImpl) PgClient.create(vertx, options); client.connect(c -> { SQLConnection conn = c.result(); conn.updateWithParams("INSERT INTO Fortune (id, message) VALUES ($1, $2)", new JsonArray().add(1234).add("Yes!"), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.getUpdated()); async.complete(); })); }); } @Test public void testUpdateForUpdateWithParams(TestContext ctx) { Async async = ctx.async(); PgClientImpl client = (PgClientImpl) PgClient.create(vertx, options); client.connect(c -> { SQLConnection conn = c.result(); conn.updateWithParams("UPDATE Fortune SET message = $1 WHERE id = $2", new JsonArray().add("Hello").add(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.getUpdated()); async.complete(); })); }); } @Test public void testDeleteForUpdateWithParams(TestContext ctx) { Async async = ctx.async(); PgClientImpl client = (PgClientImpl) PgClient.create(vertx, options); client.connect(c -> { SQLConnection conn = c.result(); conn.updateWithParams("DELETE FROM Fortune WHERE id = $1", new JsonArray().add(3), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.getUpdated()); async.complete(); })); }); } @Test public void testGetDefaultTx(TestContext ctx) { Async async = ctx.async(); PgClientImpl client = (PgClientImpl) PgClient.create(vertx, options); client.connect(c -> { SQLConnection conn = c.result(); conn.getTransactionIsolation(ctx.asyncAssertSuccess(result -> { ctx.assertEquals(TransactionIsolation.READ_COMMITTED, result); async.complete(); })); }); } @Test public void testSetUnsupportedTx(TestContext ctx) { Async async = ctx.async(); PgClientImpl client = (PgClientImpl) PgClient.create(vertx, options); client.connect(c -> { SQLConnection conn = c.result(); conn.setTransactionIsolation(TransactionIsolation.NONE, ctx.asyncAssertFailure(result -> { ctx.assertEquals("None transaction isolation is not supported", result.getMessage()); async.complete(); })); }); } @Test public void testSetAndGetReadUncommittedTx(TestContext ctx) { Async async = ctx.async(); PgClientImpl client = (PgClientImpl) PgClient.create(vertx, options); client.connect(c -> { SQLConnection conn = c.result(); conn.setTransactionIsolation(TransactionIsolation.READ_UNCOMMITTED, ctx.asyncAssertSuccess(result -> { conn.getTransactionIsolation(ctx.asyncAssertSuccess(res -> { ctx.assertEquals(TransactionIsolation.READ_UNCOMMITTED, res); async.complete(); })); })); }); } @Test public void testSetAndGetReadCommittedTx(TestContext ctx) { Async async = ctx.async(); PgClientImpl client = (PgClientImpl) PgClient.create(vertx, options); client.connect(c -> { SQLConnection conn = c.result(); conn.setTransactionIsolation(TransactionIsolation.READ_COMMITTED, ctx.asyncAssertSuccess(result -> { conn.getTransactionIsolation(ctx.asyncAssertSuccess(res -> { ctx.assertEquals(TransactionIsolation.READ_COMMITTED, res); async.complete(); })); })); }); } @Test public void testSetAndGetRepeatableReadTx(TestContext ctx) { Async async = ctx.async(); PgClientImpl client = (PgClientImpl) PgClient.create(vertx, options); client.connect(c -> { SQLConnection conn = c.result(); conn.setTransactionIsolation(TransactionIsolation.REPEATABLE_READ, ctx.asyncAssertSuccess(result -> { conn.getTransactionIsolation(ctx.asyncAssertSuccess(res -> { ctx.assertEquals(TransactionIsolation.REPEATABLE_READ, res); async.complete(); })); })); }); } @Test public void testSetAndGetSerializableTx(TestContext ctx) { Async async = ctx.async(); PgClientImpl client = (PgClientImpl) PgClient.create(vertx, options); client.connect(c -> { SQLConnection conn = c.result(); conn.setTransactionIsolation(TransactionIsolation.SERIALIZABLE, ctx.asyncAssertSuccess(result -> { conn.getTransactionIsolation(ctx.asyncAssertSuccess(res -> { ctx.assertEquals(TransactionIsolation.SERIALIZABLE, res); async.complete(); })); })); }); } */ @Test public void testUpdateError(TestContext ctx) { Async async = ctx.async(); connector.accept(ctx.asyncAssertSuccess(conn -> { conn.query("INSERT INTO Fortune (id, message) VALUES (1, 'Duplicate')", ctx.asyncAssertFailure(err -> { ctx.assertEquals("23505", ((PgException) err).getCode()); conn.query("SELECT 1000", ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1000, result.iterator().next().getInteger(0)); async.complete(); })); })); })); } @Test public void testBatchInsertError(TestContext ctx) throws Exception { Async async = ctx.async(); connector.accept(ctx.asyncAssertSuccess(conn -> { int id = randomWorld(); List batch = new ArrayList<>(); batch.add(Tuple.of(id, 3)); conn.preparedBatch("INSERT INTO World (id, randomnumber) VALUES ($1, $2)", batch, ctx.asyncAssertFailure(err -> { ctx.assertEquals("23505", ((PgException) err).getCode()); conn.query("SELECT 1000", ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1000, result.iterator().next().getInteger(0)); async.complete(); })); })); })); } @Test public void testCloseOnUndeploy(TestContext ctx) { Async done = ctx.async(); vertx.deployVerticle(new AbstractVerticle() { @Override public void start(Future startFuture) throws Exception { connector.accept(ctx.asyncAssertSuccess(conn -> { conn.closeHandler(v -> { done.complete(); }); startFuture.complete(); })); } }, ctx.asyncAssertSuccess(id -> { vertx.undeploy(id); })); } @Test public void testTransactionCommit(TestContext ctx) { testTransactionCommit(ctx, Runnable::run); } @Test public void testTransactionCommitFromAnotherThread(TestContext ctx) { testTransactionCommit(ctx, t -> new Thread(t).start()); } private void testTransactionCommit(TestContext ctx, Executor exec) { Async done = ctx.async(); connector.accept(ctx.asyncAssertSuccess(conn -> { deleteFromTestTable(ctx, conn, () -> { exec.execute(() -> { PgTransaction tx = conn.begin(); AtomicInteger u1 = new AtomicInteger(); AtomicInteger u2 = new AtomicInteger(); conn.query("INSERT INTO Test (id, val) VALUES (1, 'val-1')", ctx.asyncAssertSuccess(res1 -> { u1.addAndGet(res1.rowCount()); exec.execute(() -> { conn.query("INSERT INTO Test (id, val) VALUES (2, 'val-2')", ctx.asyncAssertSuccess(res2 -> { u2.addAndGet(res2.rowCount()); exec.execute(() -> { tx.commit(ctx.asyncAssertSuccess(v -> { ctx.assertEquals(1, u1.get()); ctx.assertEquals(1, u2.get()); conn.query("SELECT id FROM Test WHERE id=1 OR id=2", ctx.asyncAssertSuccess(result -> { ctx.assertEquals(2, result.size()); done.complete(); })); })); }); })); }); })); }); }); })); } @Test public void testTransactionRollback(TestContext ctx) { testTransactionRollback(ctx, Runnable::run); } @Test public void testTransactionRollbackFromAnotherThread(TestContext ctx) { testTransactionRollback(ctx, t -> new Thread(t).start()); } private void testTransactionRollback(TestContext ctx, Executor exec) { Async done = ctx.async(); connector.accept(ctx.asyncAssertSuccess(conn -> { deleteFromTestTable(ctx, conn, () -> { exec.execute(() -> { PgTransaction tx = conn.begin(); AtomicInteger u1 = new AtomicInteger(); AtomicInteger u2 = new AtomicInteger(); conn.query("INSERT INTO Test (id, val) VALUES (1, 'val-1')", ctx.asyncAssertSuccess(res1 -> { u1.addAndGet(res1.rowCount()); exec.execute(() -> { }); conn.query("INSERT INTO Test (id, val) VALUES (2, 'val-2')", ctx.asyncAssertSuccess(res2 -> { u2.addAndGet(res2.rowCount()); exec.execute(() -> { tx.rollback(ctx.asyncAssertSuccess(v -> { ctx.assertEquals(1, u1.get()); ctx.assertEquals(1, u2.get()); conn.query("SELECT id FROM Test WHERE id=1 OR id=2", ctx.asyncAssertSuccess(result -> { ctx.assertEquals(0, result.size()); done.complete(); })); })); }); })); })); }); }); })); } @Test public void testTransactionAbort(TestContext ctx) { Async done = ctx.async(); connector.accept(ctx.asyncAssertSuccess(conn -> { deleteFromTestTable(ctx, conn, () -> { PgTransaction tx = conn.begin(); AtomicInteger failures = new AtomicInteger(); tx.abortHandler(v -> ctx.assertEquals(0, failures.getAndIncrement())); AtomicReference> queryAfterFailed = new AtomicReference<>(); AtomicReference> commit = new AtomicReference<>(); conn.query("INSERT INTO Test (id, val) VALUES (1, 'val-1')", ar1 -> { }); conn.query("INSERT INTO Test (id, val) VALUES (1, 'val-2')", ar2 -> { ctx.assertNotNull(queryAfterFailed.get()); ctx.assertTrue(queryAfterFailed.get().failed()); ctx.assertNotNull(commit.get()); ctx.assertTrue(commit.get().failed()); ctx.assertTrue(ar2.failed()); ctx.assertEquals(1, failures.get()); // This query won't be made in the same TX conn.query("SELECT id FROM Test WHERE id=1", ctx.asyncAssertSuccess(result -> { ctx.assertEquals(0, result.size()); done.complete(); })); }); conn.query("SELECT id FROM Test", queryAfterFailed::set); tx.commit(commit::set); }); })); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/PgConnectionUriParserTest.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.vertx.core.json.JsonObject; import org.junit.Test; import static io.reactiverse.pgclient.impl.PgConnectionUriParser.*; import static org.junit.Assert.*; /** * @author Billy Yuan */ public class PgConnectionUriParserTest { private String uri; private JsonObject actualParsedResult; private JsonObject expectedParsedResult; @Test public void testParsingUriSchemeDesignator() { uri = "postgresql://"; actualParsedResult = parse(uri); expectedParsedResult = new JsonObject(); assertEquals(expectedParsedResult, actualParsedResult); } @Test public void testParsingAnotherUriSchemeDesignator() { uri = "postgres://"; actualParsedResult = parse(uri); expectedParsedResult = new JsonObject(); assertEquals(expectedParsedResult, actualParsedResult); } @Test(expected = IllegalArgumentException.class) public void testParsingInvalidUriSchemeDesignator() { uri = "posttgres://localhost"; actualParsedResult = parse(uri); } @Test public void testParsingUser() { uri = "postgres://user@"; actualParsedResult = parse(uri); expectedParsedResult = new JsonObject() .put("user", "user"); assertEquals(expectedParsedResult, actualParsedResult); } @Test public void testParsingPassword() { uri = "postgresql://user:secret@"; actualParsedResult = parse(uri); expectedParsedResult = new JsonObject() .put("user", "user") .put("password", "secret"); assertEquals(expectedParsedResult, actualParsedResult); } @Test public void testParsingHost() { uri = "postgresql://localhost"; actualParsedResult = parse(uri); expectedParsedResult = new JsonObject() .put("host", "localhost"); assertEquals(expectedParsedResult, actualParsedResult); } @Test public void testParsingIpv4Address() { uri = "postgresql://192.168.1.1"; actualParsedResult = parse(uri); expectedParsedResult = new JsonObject() .put("host", "192.168.1.1"); assertEquals(expectedParsedResult, actualParsedResult); } @Test public void testParsingIpv6Address() { uri = "postgresql://[2001:db8::1234]"; actualParsedResult = parse(uri); expectedParsedResult = new JsonObject() .put("host", "2001:db8::1234"); assertEquals(expectedParsedResult, actualParsedResult); } @Test public void testParsingPort() { uri = "postgresql://:1234"; actualParsedResult = parse(uri); expectedParsedResult = new JsonObject() .put("port", 1234); assertEquals(expectedParsedResult, actualParsedResult); } @Test public void testParsingDbName() { uri = "postgres:///mydb"; actualParsedResult = parse(uri); expectedParsedResult = new JsonObject() .put("database", "mydb"); assertEquals(expectedParsedResult, actualParsedResult); } @Test public void testParsingOneParameter() { uri = "postgresql://?user=other"; actualParsedResult = parse(uri); expectedParsedResult = new JsonObject() .put("user", "other"); assertEquals(expectedParsedResult, actualParsedResult); } @Test public void testParsingParameters() { uri = "postgresql://?user=other&password=secret&port=1234"; actualParsedResult = parse(uri); expectedParsedResult = new JsonObject() .put("user", "other") .put("password", "secret") .put("port", 1234); assertEquals(expectedParsedResult, actualParsedResult); } @Test public void testParsingHostAndParameters() { uri = "postgresql://localhost?user=other&password=secret"; actualParsedResult = parse(uri); expectedParsedResult = new JsonObject() .put("host", "localhost") .put("user", "other") .put("password", "secret"); assertEquals(expectedParsedResult, actualParsedResult); } @Test public void testParsingUserWithoutPassword() { uri = "postgresql://user@"; actualParsedResult = parse(uri); expectedParsedResult = new JsonObject() .put("user", "user"); assertEquals(expectedParsedResult, actualParsedResult); } @Test(expected = IllegalArgumentException.class) public void testParsingPasswordWithoutUser() { uri = "postgresql://:secret@"; actualParsedResult = parse(uri); } @Test public void testParsingHostWithPort() { uri = "postgresql://localhost:1234"; actualParsedResult = parse(uri); expectedParsedResult = new JsonObject() .put("host", "localhost") .put("port", 1234); assertEquals(expectedParsedResult, actualParsedResult); } @Test public void testParsingPortAndDbName() { uri = "postgresql://:1234/mydb"; actualParsedResult = parse(uri); expectedParsedResult = new JsonObject() .put("port", 1234) .put("database", "mydb"); assertEquals(expectedParsedResult, actualParsedResult); } @Test public void testParsingUserAndParameters() { uri = "postgresql://user@?host=localhost&port=1234"; actualParsedResult = parse(uri); expectedParsedResult = new JsonObject() .put("user", "user") .put("host", "localhost") .put("port", 1234); assertEquals(expectedParsedResult, actualParsedResult); } @Test public void testParsingDomainSocket() { uri = "postgresql://%2Fvar%2Flib%2Fpostgresql"; actualParsedResult = parse(uri); expectedParsedResult = new JsonObject() .put("host", "/var/lib/postgresql"); assertEquals(expectedParsedResult, actualParsedResult); } @Test public void testParsingDomainSocketInParameter() { uri = "postgresql://?host=/var/lib/postgresql"; actualParsedResult = parse(uri); expectedParsedResult = new JsonObject() .put("host", "/var/lib/postgresql"); assertEquals(expectedParsedResult, actualParsedResult); } @Test public void testParsingUriWithOverridenParameters() { uri = "postgresql://localhost/mydb?host=myhost&port=1234"; actualParsedResult = parse(uri); expectedParsedResult = new JsonObject() .put("host", "myhost") .put("database", "mydb") .put("port", 1234); assertEquals(expectedParsedResult, actualParsedResult); } @Test public void testParsingFullUri() { uri = "postgresql://dbuser:secretpassword@database.server.com:3211/mydb"; actualParsedResult = parse(uri); expectedParsedResult = new JsonObject() .put("user", "dbuser") .put("password", "secretpassword") .put("host", "database.server.com") .put("port", 3211) .put("database", "mydb"); assertEquals(expectedParsedResult, actualParsedResult); } @Test public void testParsingParameterSslMode() { uri = "postgresql://?host=localhost&port=1234&sslmode=require"; actualParsedResult = parse(uri); expectedParsedResult = new JsonObject() .put("host", "localhost") .put("port", 1234) .put("sslMode", "REQUIRE"); assertEquals(expectedParsedResult, actualParsedResult); } @Test(expected = IllegalArgumentException.class) public void testParsingInvalidUri1() { uri = "postgresql://us@er@@"; actualParsedResult = parse(uri); } @Test(expected = IllegalArgumentException.class) public void testParsingInvalidUri2() { uri = "postgresql://user/mydb//"; actualParsedResult = parse(uri); } @Test(expected = IllegalArgumentException.class) public void testParsingInvalidUri3() { uri = "postgresql:///dbname/?host=localhost"; actualParsedResult = parse(uri); } @Test(expected = IllegalArgumentException.class) public void testParsingInvalidUri4() { uri = "postgresql://user::1234"; actualParsedResult = parse(uri); } @Test(expected = IllegalArgumentException.class) public void testParsingInvalidUri5() { uri = "postgresql://@:1234"; actualParsedResult = parse(uri); } @Test(expected = IllegalArgumentException.class) public void testParsingInvalidUri6() { uri = "postgresql://:123:"; actualParsedResult = parse(uri); } @Test(expected = IllegalArgumentException.class) public void testParsingInvalidUri7() { uri = "postgresql://@@/dbname?host"; actualParsedResult = parse(uri); } @Test(expected = IllegalArgumentException.class) public void testParsingInvalidSslmode() { uri = "postgresql://?sslmode=invalidsslmode"; actualParsedResult = parse(uri); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/PgPoolTest.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import org.junit.Test; import java.util.concurrent.atomic.AtomicReference; /** * @author Julien Viet */ public class PgPoolTest extends PgPoolTestBase { @Override protected PgPool createPool(PgConnectOptions options, int size) { return PgClient.pool(vertx, new PgPoolOptions(options).setMaxSize(size)); } @Test public void testReconnectQueued(TestContext ctx) { Async async = ctx.async(); ProxyServer proxy = ProxyServer.create(vertx, options.getPort(), options.getHost()); AtomicReference proxyConn = new AtomicReference<>(); proxy.proxyHandler(conn -> { proxyConn.set(conn); conn.connect(); }); proxy.listen(8080, "localhost", ctx.asyncAssertSuccess(v1 -> { PgPool pool = createPool(new PgConnectOptions(options).setPort(8080).setHost("localhost"), 1); pool.getConnection(ctx.asyncAssertSuccess(conn -> { proxyConn.get().close(); })); pool.getConnection(ctx.asyncAssertSuccess(conn -> { conn.query("SELECT id, randomnumber from WORLD", ctx.asyncAssertSuccess(v2 -> { async.complete(); })); })); })); } @Test public void testAuthFailure(TestContext ctx) { Async async = ctx.async(); PgPool pool = createPool(new PgConnectOptions(options).setPassword("wrong"), 1); pool.query("SELECT id, randomnumber from WORLD", ctx.asyncAssertFailure(v2 -> { async.complete(); })); } @Test public void testConnectionFailure(TestContext ctx) { Async async = ctx.async(); ProxyServer proxy = ProxyServer.create(vertx, options.getPort(), options.getHost()); AtomicReference proxyConn = new AtomicReference<>(); proxy.proxyHandler(conn -> { proxyConn.set(conn); conn.connect(); }); PgPool pool = PgClient.pool(vertx, new PgPoolOptions(options) .setPort(8080) .setHost("localhost") .setMaxSize(1) .setMaxWaitQueueSize(0) ); pool.getConnection(ctx.asyncAssertFailure(err -> { proxy.listen(8080, "localhost", ctx.asyncAssertSuccess(v1 -> { pool.getConnection(ctx.asyncAssertSuccess(conn -> { async.complete(); })); })); })); } @Test public void testRunWithExisting(TestContext ctx) { Async async = ctx.async(); vertx.runOnContext(v -> { try { PgClient.pool(new PgPoolOptions()); ctx.fail(); } catch (IllegalStateException ignore) { async.complete(); } }); } @Test public void testRunStandalone(TestContext ctx) { Async async = ctx.async(); PgPool pool = PgClient.pool(new PgPoolOptions(options)); try { pool.query("SELECT id, randomnumber from WORLD", ctx.asyncAssertSuccess(v -> { async.complete(); })); async.await(4000); } finally { pool.close(); } } @Test public void testMaxWaitQueueSize(TestContext ctx) { Async async = ctx.async(); PgPool pool = PgClient.pool(new PgPoolOptions(options).setMaxSize(1).setMaxWaitQueueSize(0)); try { pool.getConnection(ctx.asyncAssertSuccess(v -> { pool.getConnection(ctx.asyncAssertFailure(err -> { async.complete(); })); })); async.await(4000000); } finally { pool.close(); } } // This test check that when using pooled connections, the preparedQuery pool operation // will actually use the same connection for the prepare and the query commands @Test public void testConcurrentMultipleConnection(TestContext ctx) { PgPoolOptions options = new PgPoolOptions(new PgConnectOptions(PgTestBase.options).setCachePreparedStatements(true)).setMaxSize(2); PgPool pool = PgClient.pool(vertx, options); int numRequests = 2; Async async = ctx.async(numRequests); for (int i = 0;i < numRequests;i++) { pool.preparedQuery("SELECT * FROM Fortune WHERE id=$1", Tuple.of(1), ctx.asyncAssertSuccess(results -> { ctx.assertEquals(1, results.size()); Tuple row = results.iterator().next(); ctx.assertEquals(1, row.getInteger(0)); ctx.assertEquals("fortune: No such file or directory", row.getString(1)); async.countDown(); })); } } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/PgPoolTestBase.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.vertx.core.Vertx; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.concurrent.atomic.AtomicReference; /** * @author Julien Viet */ @RunWith(VertxUnitRunner.class) public abstract class PgPoolTestBase extends PgTestBase { Vertx vertx; @Before public void setup() { vertx = Vertx.vertx(); } @After public void teardown(TestContext ctx) { vertx.close(ctx.asyncAssertSuccess()); } protected abstract PgPool createPool(PgConnectOptions options, int size); @Test public void testPool(TestContext ctx) { int num = 1000; Async async = ctx.async(num); PgPool pool = createPool(options, 4); for (int i = 0;i < num;i++) { pool.getConnection(ctx.asyncAssertSuccess(conn -> { conn.query("SELECT id, randomnumber from WORLD", ar -> { if (ar.succeeded()) { PgResult result = ar.result(); ctx.assertEquals(10000, result.size()); } else { ctx.assertEquals("closed", ar.cause().getMessage()); } conn.close(); async.countDown(); }); })); } } @Test public void testQuery(TestContext ctx) { int num = 1000; Async async = ctx.async(num); PgPool pool = createPool(options, 4); for (int i = 0;i < num;i++) { pool.query("SELECT id, randomnumber from WORLD", ar -> { if (ar.succeeded()) { PgResult result = ar.result(); ctx.assertEquals(10000, result.size()); } else { ctx.assertEquals("closed", ar.cause().getMessage()); } async.countDown(); }); } } @Test public void testQueryWithParams(TestContext ctx) { int num = 1000; Async async = ctx.async(num); PgPool pool = createPool(options, 4); for (int i = 0;i < num;i++) { pool.preparedQuery("SELECT id, randomnumber from WORLD where id=$1", Tuple.of(i + 1), ar -> { if (ar.succeeded()) { PgResult result = ar.result(); ctx.assertEquals(1, result.size()); } else { ar.cause().printStackTrace(); ctx.assertEquals("closed", ar.cause().getMessage()); } async.countDown(); }); } } @Test public void testUpdate(TestContext ctx) { int num = 1000; Async async = ctx.async(num); PgPool pool = createPool(options, 4); for (int i = 0;i < num;i++) { pool.query("UPDATE Fortune SET message = 'Whatever' WHERE id = 9", ar -> { if (ar.succeeded()) { PgResult result = ar.result(); ctx.assertEquals(1, result.rowCount()); } else { ctx.assertEquals("closed", ar.cause().getMessage()); } async.countDown(); }); } } @Test public void testUpdateWithParams(TestContext ctx) { int num = 1000; Async async = ctx.async(num); PgPool pool = createPool(options, 4); for (int i = 0;i < num;i++) { pool.preparedQuery("UPDATE Fortune SET message = 'Whatever' WHERE id = $1", Tuple.of(9), ar -> { if (ar.succeeded()) { PgResult result = ar.result(); ctx.assertEquals(1, result.rowCount()); } else { ctx.assertEquals("closed", ar.cause().getMessage()); } async.countDown(); }); } } @Test public void testReconnect(TestContext ctx) { Async async = ctx.async(); ProxyServer proxy = ProxyServer.create(vertx, options.getPort(), options.getHost()); AtomicReference proxyConn = new AtomicReference<>(); proxy.proxyHandler(conn -> { proxyConn.set(conn); conn.connect(); }); proxy.listen(8080, "localhost", ctx.asyncAssertSuccess(v1 -> { PgPool pool = createPool(new PgConnectOptions(options).setPort(8080).setHost("localhost"), 1); pool.getConnection(ctx.asyncAssertSuccess(conn1 -> { proxyConn.get().close(); conn1.closeHandler(v2 -> { conn1.query("never-read", ctx.asyncAssertFailure(err -> { pool.getConnection(ctx.asyncAssertSuccess(conn2 -> { conn2.query("SELECT id, randomnumber from WORLD", ctx.asyncAssertSuccess(v3 -> { async.complete(); })); })); })); }); })); })); } @Test public void testCancelRequest(TestContext ctx) { Async async = ctx.async(); PgPool pool = createPool(options, 4); pool.getConnection(ctx.asyncAssertSuccess(conn -> { conn.query("SELECT pg_sleep(10)", ctx.asyncAssertFailure(error -> { ctx.assertEquals("canceling statement due to user request", error.getMessage()); conn.close(); async.complete(); })); conn.cancelRequest(ctx.asyncAssertSuccess()); })); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/PgPooledConnectionTest.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import org.junit.Test; /** * @author Julien Viet */ public class PgPooledConnectionTest extends PgConnectionTestBase { private PgPool pool; public PgPooledConnectionTest() { connector = handler -> { if (pool == null) { pool = PgClient.pool(vertx, new PgPoolOptions(options).setMaxSize(1)); } pool.getConnection(handler); }; } @Override public void teardown(TestContext ctx) { if (pool != null) { pool.close(); } super.teardown(ctx); } @Test public void testThatPoolReconnect(TestContext ctx) { } @Test public void testTransactionRollbackUnfinishedOnRecycle(TestContext ctx) { Async done = ctx.async(2); connector.accept(ctx.asyncAssertSuccess(conn1 -> { deleteFromTestTable(ctx, conn1, () -> { conn1.begin(); conn1.query("INSERT INTO Test (id, val) VALUES (5, 'some-value')", ctx.asyncAssertSuccess()); conn1.query("SELECT txid_current()", ctx.asyncAssertSuccess(result -> { Long txid1 = result.iterator().next().getLong(0); conn1.close(); // It will be the same connection connector.accept(ctx.asyncAssertSuccess(conn2 -> { conn2.query("SELECT id FROM Test WHERE id=5", ctx.asyncAssertSuccess(result2 -> { ctx.assertEquals(0, result2.size()); done.countDown(); })); conn2.query("SELECT txid_current()", ctx.asyncAssertSuccess(result2 -> { Long txid2 = result.iterator().next().getLong(0); ctx.assertEquals(txid1, txid2); done.countDown(); })); })); })); }); })); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/PgTestBase.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import de.flapdoodle.embed.process.config.IRuntimeConfig; import de.flapdoodle.embed.process.config.io.ProcessOutput; import de.flapdoodle.embed.process.runtime.ICommandLinePostProcessor; import de.flapdoodle.embed.process.store.IArtifactStore; import io.vertx.ext.unit.TestContext; import org.junit.AfterClass; import org.junit.BeforeClass; import ru.yandex.qatools.embed.postgresql.EmbeddedPostgres; import ru.yandex.qatools.embed.postgresql.distribution.Version; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.PosixFilePermission; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertTrue; import static ru.yandex.qatools.embed.postgresql.distribution.Version.V10_6; import static ru.yandex.qatools.embed.postgresql.distribution.Version.V11_1; import static ru.yandex.qatools.embed.postgresql.distribution.Version.V9_6_11; /** * @author Julien Viet */ public abstract class PgTestBase { private static final String connectionUri = System.getProperty("connection.uri"); private static final String tlsConnectionUri = System.getProperty("tls.connection.uri"); private static EmbeddedPostgres postgres; protected static PgConnectOptions options; @BeforeClass public static void before() throws Exception { options = startPg(); } @AfterClass public static void after() throws Exception { stopPg(); } public synchronized static PgConnectOptions startPg() throws Exception { return startPg(false, false); } public synchronized static PgConnectOptions startPg(boolean domainSockets, boolean ssl) throws Exception { if (domainSockets && ssl) { throw new IllegalArgumentException("ssl should be disabled when testing with Unix domain socket"); } if (ssl) { if (tlsConnectionUri != null && !tlsConnectionUri.isEmpty()) { return PgConnectOptions.fromUri(tlsConnectionUri); } } if (connectionUri != null && !connectionUri.isEmpty()) { return PgConnectOptions.fromUri(connectionUri); } if (postgres != null) { throw new IllegalStateException(); } IRuntimeConfig config; String a = System.getProperty("target.dir", "target"); File targetDir = new File(a); if (targetDir.exists() && targetDir.isDirectory()) { config = EmbeddedPostgres.cachedRuntimeConfig(targetDir.toPath()); } else { throw new AssertionError("Cannot access target dir"); } // SSL if (ssl) { config = useSSLRuntimeConfig(config); } // Domain sockets File sock; if (domainSockets) { sock = Files.createTempFile(targetDir.toPath(), "pg_", ".sock").toFile(); assertTrue(sock.delete()); assertTrue(sock.mkdir()); Files.setPosixFilePermissions(sock.toPath(), new HashSet<>(Arrays.asList( PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE, PosixFilePermission.GROUP_EXECUTE, PosixFilePermission.GROUP_READ, PosixFilePermission.GROUP_WRITE ))); config = useDomainSocketRunTimeConfig(config, sock); } else { sock = null; } postgres = new EmbeddedPostgres(getPostgresVersion()); PgTestBase.postgres.start(config, "localhost", 8081, "postgres", "postgres", "postgres", Collections.emptyList()); File setupFile = getTestResource("create-postgres.sql"); PgTestBase.postgres.getProcess().get().importFromFile(setupFile); PgConnectOptions options = new PgConnectOptions(); options.setHost(domainSockets ? sock.getAbsolutePath() : "localhost"); options.setPort(8081); options.setUser("postgres"); options.setPassword("postgres"); options.setDatabase("postgres"); return options; } public synchronized static void stopPg() throws Exception { if (postgres != null) { try { postgres.stop(); } finally { postgres = null; } } } private static File getTestResource(String name) throws Exception { InputStream in = new FileInputStream(new File("docker" + File.separator + "postgres" + File.separator + "resources" + File.separator + name)); Path path = Files.createTempFile("pg-client", ".tmp"); Files.copy(in, path, StandardCopyOption.REPLACE_EXISTING); File file = path.toFile(); file.deleteOnExit(); return file; } static void deleteFromTestTable(TestContext ctx, PgClient client, Runnable completionHandler) { client.query( "DELETE FROM Test", ctx.asyncAssertSuccess(result -> completionHandler.run())); } static void insertIntoTestTable(TestContext ctx, PgClient client, int amount, Runnable completionHandler) { AtomicInteger count = new AtomicInteger(); for (int i = 0;i < 10;i++) { client.query("INSERT INTO Test (id, val) VALUES (" + i + ", 'Whatever-" + i + "')", ctx.asyncAssertSuccess(r1 -> { ctx.assertEquals(1, r1.rowCount()); if (count.incrementAndGet() == amount) { completionHandler.run(); } })); } } // ssl=on just enables the possibility of using SSL which does not force clients to use SSL private static IRuntimeConfig useSSLRuntimeConfig(IRuntimeConfig config) throws Exception { File sslKey = getTestResource("server.key"); Files.setPosixFilePermissions(sslKey.toPath(), Collections.singleton(PosixFilePermission.OWNER_READ)); File sslCrt = getTestResource("server.crt"); return new RunTimeConfigBase(config) { @Override public ICommandLinePostProcessor getCommandLinePostProcessor() { ICommandLinePostProcessor commandLinePostProcessor = config.getCommandLinePostProcessor(); return (distribution, args) -> { List result = commandLinePostProcessor.process(distribution, args); if (result.get(0).endsWith("postgres")) { result = new ArrayList<>(result); result.add("--ssl=on"); result.add("--ssl_cert_file=" + sslCrt.getAbsolutePath()); result.add("--ssl_key_file=" + sslKey.getAbsolutePath()); } return result; }; } }; } private static IRuntimeConfig useDomainSocketRunTimeConfig(IRuntimeConfig config, File sock) throws Exception { return new RunTimeConfigBase(config) { @Override public ICommandLinePostProcessor getCommandLinePostProcessor() { ICommandLinePostProcessor commandLinePostProcessor = config.getCommandLinePostProcessor(); return (distribution, args) -> { List result = commandLinePostProcessor.process(distribution, args); if (result.get(0).endsWith("postgres")) { result = new ArrayList<>(result); result.add("--unix_socket_directories=" + sock.getAbsolutePath()); } return result; }; } }; } private static abstract class RunTimeConfigBase implements IRuntimeConfig { private final IRuntimeConfig config; private RunTimeConfigBase(IRuntimeConfig config) { this.config = config; } @Override public ProcessOutput getProcessOutput() { return config.getProcessOutput(); } @Override public IArtifactStore getArtifactStore() { return config.getArtifactStore(); } @Override public boolean isDaemonProcess() { return config.isDaemonProcess(); } } private static final Map supportedPgVersions = new HashMap<>(); static { supportedPgVersions.put("9.6", V9_6_11); supportedPgVersions.put("10.6", V10_6); supportedPgVersions.put("11.1", V11_1); } private static Version getPostgresVersion() { String specifiedVersion = System.getProperty("embedded.postgres.version"); Version version; if (specifiedVersion == null || specifiedVersion.isEmpty()) { // if version is not specified then V10 will be used by default version = V10_6; } else { version = supportedPgVersions.get(specifiedVersion); } if (version == null) { throw new IllegalArgumentException("embedded postgres only supports the following versions: " + supportedPgVersions.keySet().toString() + "instead of " + specifiedVersion); } return version; } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/PgTransactionTest.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import org.junit.Test; public class PgTransactionTest extends PgClientTestBase { private PgPool pool; public PgTransactionTest() { connector = handler -> { if (pool == null) { pool = PgClient.pool(vertx, new PgPoolOptions(options).setMaxSize(1)); } pool.begin(handler); }; } @Test public void testReleaseConnectionOnCommit(TestContext ctx) { Async async = ctx.async(); connector.accept(ctx.asyncAssertSuccess(conn -> { conn.query("UPDATE Fortune SET message = 'Whatever' WHERE id = 9", ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.rowCount()); conn.commit(ctx.asyncAssertSuccess(v1 -> { // Try acquire a connection pool.getConnection(ctx.asyncAssertSuccess(v2 -> { async.complete(); })); })); })); })); } @Test public void testReleaseConnectionOnRollback(TestContext ctx) { Async async = ctx.async(); connector.accept(ctx.asyncAssertSuccess(conn -> { conn.query("UPDATE Fortune SET message = 'Whatever' WHERE id = 9", ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.rowCount()); conn.rollback(ctx.asyncAssertSuccess(v1 -> { // Try acquire a connection pool.getConnection(ctx.asyncAssertSuccess(v2 -> { async.complete(); })); })); })); })); } @Test public void testReleaseConnectionOnSetRollback(TestContext ctx) { Async async = ctx.async(); connector.accept(ctx.asyncAssertSuccess(conn -> { conn.query("SELECT whatever from DOES_NOT_EXIST", ctx.asyncAssertFailure(result -> { // Try acquire a connection pool.getConnection(ctx.asyncAssertSuccess(v2 -> { async.complete(); })); })); })); } @Test public void testCommitWithPreparedQuery(TestContext ctx) { Async async = ctx.async(); connector.accept(ctx.asyncAssertSuccess(conn -> { conn.preparedQuery("INSERT INTO Fortune (id, message) VALUES ($1, $2);", Tuple.of(13, "test message1"), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.rowCount()); conn.commit(ctx.asyncAssertSuccess(v1 -> { pool.query("SELECT id, message from Fortune where id = 13", ctx.asyncAssertSuccess(rowSet -> { ctx.assertEquals(1, rowSet.rowCount()); Row row = rowSet.iterator().next(); ctx.assertEquals(13, row.getInteger("id")); ctx.assertEquals("test message1", row.getString("message")); async.complete(); })); })); })); })); } @Test public void testCommitWithQuery(TestContext ctx) { Async async = ctx.async(); connector.accept(ctx.asyncAssertSuccess(conn -> { conn.query("INSERT INTO Fortune (id, message) VALUES (14, 'test message2');", ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.rowCount()); conn.commit(ctx.asyncAssertSuccess(v1 -> { pool.query("SELECT id, message from Fortune where id = 14", ctx.asyncAssertSuccess(rowSet -> { ctx.assertEquals(1, rowSet.rowCount()); Row row = rowSet.iterator().next(); ctx.assertEquals(14, row.getInteger("id")); ctx.assertEquals("test message2", row.getString("message")); async.complete(); })); })); })); })); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/PreparedBatchTest.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.vertx.core.Vertx; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.List; /** * @author Emad Alblueshi */ @RunWith(VertxUnitRunner.class) public class PreparedBatchTest extends PgTestBase { Vertx vertx; @Before public void setup() { vertx = Vertx.vertx(); } @After public void teardown(TestContext ctx) { vertx.close(ctx.asyncAssertSuccess()); } @Test public void testEmptyBatch(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { List batch = new ArrayList<>(); conn.preparedBatch("INSERT INTO Test (id, val) VALUES ($1, $2)", batch, ctx.asyncAssertSuccess(result -> { async.complete(); })); })); } @Test public void testInsert(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { deleteFromTestTable(ctx, conn, () -> { List batch = new ArrayList<>(); batch.add(Tuple.of(79991, "batch one")); batch.add(Tuple.of(79992, "batch two")); batch.add(Tuple.of(79993, "batch three")); batch.add(Tuple.of(79994, "batch four")); conn.preparedBatch("INSERT INTO Test (id, val) VALUES ($1, $2)", batch, ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.rowCount()); conn.preparedQuery("SELECT * FROM Test WHERE id=$1", Tuple.of(79991), ctx.asyncAssertSuccess(ar1 -> { ctx.assertEquals(1, ar1.size()); Row one = ar1.iterator().next(); ctx.assertEquals(79991, one.getInteger("id")); ctx.assertEquals("batch one", one.getString("val")); conn.preparedQuery("SELECT * FROM Test WHERE id=$1", Tuple.of(79992), ctx.asyncAssertSuccess(ar2 -> { ctx.assertEquals(1, ar2.size()); Row two = ar2.iterator().next(); ctx.assertEquals(79992, two.getInteger("id")); ctx.assertEquals("batch two", two.getString("val")); conn.preparedQuery("SELECT * FROM Test WHERE id=$1", Tuple.of(79993), ctx.asyncAssertSuccess(ar3 -> { ctx.assertEquals(1, ar3.size()); Row three = ar3.iterator().next(); ctx.assertEquals(79993, three.getInteger("id")); ctx.assertEquals("batch three", three.getString("val")); conn.preparedQuery("SELECT * FROM Test WHERE id=$1", Tuple.of(79994), ctx.asyncAssertSuccess(ar4 -> { ctx.assertEquals(1, ar4.size()); Row four = ar4.iterator().next(); ctx.assertEquals(79994, four.getInteger("id")); ctx.assertEquals("batch four", four.getString("val")); async.complete(); })); })); })); })); })); }); })); } @Test public void testInsertWithFunction(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { deleteFromTestTable(ctx, conn, () -> { List batch = new ArrayList<>(); batch.add(Tuple.of(78881, "batch one")); batch.add(Tuple.of(78882, "batch two")); batch.add(Tuple.of(78883, "batch three")); batch.add(Tuple.of(78884, "batch four")); conn.preparedBatch("INSERT INTO Test (id, val) VALUES ($1, upper($2))", batch, ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.rowCount()); conn.preparedQuery("SELECT * FROM Test WHERE id=$1", Tuple.of(78881), ctx.asyncAssertSuccess(ar1 -> { ctx.assertEquals(1, ar1.size()); Row one = ar1.iterator().next(); ctx.assertEquals(78881, one.getInteger("id")); ctx.assertEquals("BATCH ONE", one.getString("val")); conn.preparedQuery("SELECT * FROM Test WHERE id=$1", Tuple.of(78882), ctx.asyncAssertSuccess(ar2 -> { ctx.assertEquals(1, ar2.size()); Row two = ar2.iterator().next(); ctx.assertEquals(78882, two.getInteger("id")); ctx.assertEquals("BATCH TWO", two.getString("val")); conn.preparedQuery("SELECT * FROM Test WHERE id=$1", Tuple.of(78883), ctx.asyncAssertSuccess(ar3 -> { ctx.assertEquals(1, ar3.size()); Row three = ar3.iterator().next(); ctx.assertEquals(78883, three.getInteger("id")); ctx.assertEquals("BATCH THREE", three.getString("val")); conn.preparedQuery("SELECT * FROM Test WHERE id=$1", Tuple.of(78884), ctx.asyncAssertSuccess(ar4 -> { ctx.assertEquals(1, ar4.size()); Row four = ar4.iterator().next(); ctx.assertEquals(78884, four.getInteger("id")); ctx.assertEquals("BATCH FOUR", four.getString("val")); async.complete(); })); })); })); })); })); }); })); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/PreparedStatementCachedTest.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import org.junit.Test; public class PreparedStatementCachedTest extends PreparedStatementTestBase { @Override protected PgConnectOptions options() { return new PgConnectOptions(options).setCachePreparedStatements(true); } @Test public void testConcurrent(TestContext ctx) { PgClient.connect(vertx, options(), ctx.asyncAssertSuccess(conn -> { Async[] asyncs = new Async[10]; for (int i = 0;i < 10;i++) { asyncs[i] = ctx.async(); } for (int i = 0;i < 10;i++) { Async async = asyncs[i]; conn.prepare("SELECT * FROM Fortune WHERE id=$1", ctx.asyncAssertSuccess(ps -> { ps.execute(Tuple.of(1), ctx.asyncAssertSuccess(results -> { ctx.assertEquals(1, results.size()); Tuple row = results.iterator().next(); ctx.assertEquals(1, row.getInteger(0)); ctx.assertEquals("fortune: No such file or directory", row.getString(1)); async.complete(); })); })); } })); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/PreparedStatementTest.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; public class PreparedStatementTest extends PreparedStatementTestBase { @Override protected PgConnectOptions options() { return new PgConnectOptions(options).setCachePreparedStatements(false); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/PreparedStatementTestBase.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.reactiverse.pgclient.impl.codec.util.Util; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.streams.ReadStream; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author Julien Viet */ @RunWith(VertxUnitRunner.class) public abstract class PreparedStatementTestBase extends PgTestBase { Vertx vertx; protected abstract PgConnectOptions options(); @Before public void setup() { vertx = Vertx.vertx(); } @After public void teardown(TestContext ctx) { vertx.close(ctx.asyncAssertSuccess()); } @Test public void testQuery1Param(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options(), ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT * FROM Fortune WHERE id=$1", ctx.asyncAssertSuccess(ps -> { ps.execute(Tuple.of(1), ctx.asyncAssertSuccess(results -> { ctx.assertEquals(1, results.size()); Tuple row = results.iterator().next(); ctx.assertEquals(1, row.getInteger(0)); ctx.assertEquals("fortune: No such file or directory", row.getString(1)); ps.close(ctx.asyncAssertSuccess(ar -> { async.complete(); })); })); })); })); } @Test public void testQuery(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options(), ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT * FROM Fortune WHERE id=$1 OR id=$2 OR id=$3 OR id=$4 OR id=$5 OR id=$6", ctx.asyncAssertSuccess(ps -> { ps.execute(Tuple.of(1, 8, 4, 11, 2, 9), ctx.asyncAssertSuccess(results -> { ctx.assertEquals(6, results.size()); ps.close(ctx.asyncAssertSuccess(result -> { async.complete(); })); })); })); })); } @Test public void testCollectorQuery(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options(), ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT * FROM Fortune WHERE id=$1 OR id=$2 OR id=$3 OR id=$4 OR id=$5 OR id=$6", ctx.asyncAssertSuccess(ps -> { ps.execute(Tuple.of(1, 8, 4, 11, 2, 9), Collectors.toList(), ctx.asyncAssertSuccess(results -> { ctx.assertEquals(6, results.size()); List list = results.value(); ctx.assertEquals(list.size(), 6); ctx.assertEquals(6L, list.stream().distinct().count()); ps.close(ctx.asyncAssertSuccess(result -> { async.complete(); })); })); })); })); } /* @Test public void testQueryStream(TestContext ctx) { Async async = ctx.async(); PgConnection.connect(vertx, options(), (ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT * FROM Fortune WHERE id=$1 OR id=$2 OR id=$3 OR id=$4 OR id=$5 OR id=$6", ctx.asyncAssertSuccess(ps -> { PgQuery createStream = ps.query(1, 8, 4, 11, 2, 9); LinkedList results = new LinkedList<>(); createStream.exceptionHandler(ctx::fail); createStream.endHandler(v -> { ctx.assertEquals(6, results.size()); ps.close(ctx.asyncAssertSuccess(result -> { async.complete(); })); }); createStream.handler(rs -> results.addAll(rs.getResults())); })); })); } */ @Test public void testQueryParseError(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options(), ctx.asyncAssertSuccess(conn -> { conn.prepare("invalid", ctx.asyncAssertFailure(err -> { PgException pgErr = (PgException) err; ctx.assertEquals(ErrorCodes.syntax_error, pgErr.getCode()); async.complete(); })); })); } private static final String validationErrorSql = "SELECT * FROM Fortune WHERE id=$1"; private static final Tuple validationErrorTuple = Tuple.of("invalid-id"); private void testValidationError(TestContext ctx, BiConsumer> test) { Async async = ctx.async(); PgClient.connect(vertx, options(), ctx.asyncAssertSuccess(conn -> { test.accept(conn, failure -> { ctx.assertEquals(Util.buildInvalidArgsError(Stream.of("invalid-id"), Stream.of(Number.class)), failure.getMessage()); async.complete(); }); conn.preparedQuery("SELECT * FROM Fortune WHERE id=$1", Tuple.of("invalid-id"), ctx.asyncAssertFailure(failure -> { })); })); } @Test public void testPrepareExecuteValidationError(TestContext ctx) { testValidationError(ctx, (conn, cont) -> { conn.prepare("SELECT * FROM Fortune WHERE id=$1", ctx.asyncAssertSuccess(ps -> { ps.execute(Tuple.of("invalid-id"), ctx.asyncAssertFailure(cont)); })); }); } @Test public void testPrepareCursorValidationError(TestContext ctx) { testValidationError(ctx, (conn, cont) -> { conn.prepare("SELECT * FROM Fortune WHERE id=$1", ctx.asyncAssertSuccess(ps -> { try { ps.cursor(Tuple.of("invalid-id")); } catch (Exception e) { cont.handle(e); } })); }); } @Test public void testPrepareBatchValidationError(TestContext ctx) { testValidationError(ctx, (conn, cont) -> { conn.prepare("SELECT * FROM Fortune WHERE id=$1", ctx.asyncAssertSuccess(ps -> { ps.batch(Collections.singletonList(Tuple.of("invalid-id")), ctx.asyncAssertFailure(cont)); })); }); } @Test public void testPreparedQueryValidationError(TestContext ctx) { testValidationError(ctx, (conn, cont) -> { conn.preparedQuery("SELECT * FROM Fortune WHERE id=$1", Tuple.of("invalid-id"), ctx.asyncAssertFailure(cont)); }); } @Test public void testPreparedBatchValidationError(TestContext ctx) { testValidationError(ctx, (conn, cont) -> { conn.preparedBatch("SELECT * FROM Fortune WHERE id=$1", Collections.singletonList(Tuple.of("invalid-id")), ctx.asyncAssertFailure(cont)); }); } @Test public void testNullValueIsAlwaysValid(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn .preparedQuery("SELECT 1 WHERE $1::INT4 IS NULL", Tuple.tuple().addInteger(null), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); async.complete(); })); })); } // Need to test partial query close or abortion ? @Test public void testQueryCursor(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options(), ctx.asyncAssertSuccess(conn -> { conn.query("BEGIN", ctx.asyncAssertSuccess(begin -> { conn.prepare("SELECT * FROM Fortune WHERE id=$1 OR id=$2 OR id=$3 OR id=$4 OR id=$5 OR id=$6", ctx.asyncAssertSuccess(ps -> { PgCursor query = ps.cursor(Tuple.of(1, 8, 4, 11, 2, 9)); query.read(4, ctx.asyncAssertSuccess(result -> { ctx.assertNotNull(result.columnsNames()); ctx.assertEquals(4, result.size()); ctx.assertTrue(query.hasMore()); query.read(4, ctx.asyncAssertSuccess(result2 -> { ctx.assertNotNull(result.columnsNames()); ctx.assertEquals(4, result.size()); ctx.assertFalse(query.hasMore()); async.complete(); })); })); })); })); })); } @Test public void testQueryCloseCursor(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options(), ctx.asyncAssertSuccess(conn -> { conn.query("BEGIN", ctx.asyncAssertSuccess(begin -> { conn.prepare("SELECT * FROM Fortune WHERE id=$1 OR id=$2 OR id=$3 OR id=$4 OR id=$5 OR id=$6", ctx.asyncAssertSuccess(ps -> { PgCursor query = ps.cursor(Tuple.of(1, 8, 4, 11, 2, 9)); query.read(4, ctx.asyncAssertSuccess(results -> { ctx.assertEquals(4, results.size()); query.close(ctx.asyncAssertSuccess(v1 -> { ps.close(ctx.asyncAssertSuccess(v2 -> { async.complete(); })); })); })); })); })); })); } @Test public void testQueryStreamCloseCursor(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options(), ctx.asyncAssertSuccess(conn -> { conn.query("BEGIN", ctx.asyncAssertSuccess(begin -> { conn.prepare("SELECT * FROM Fortune WHERE id=$1 OR id=$2 OR id=$3 OR id=$4 OR id=$5 OR id=$6", ctx.asyncAssertSuccess(ps -> { PgCursor stream = ps.cursor(Tuple.of(1, 8, 4, 11, 2, 9)); stream.read(4, ctx.asyncAssertSuccess(result -> { ctx.assertEquals(4, result.size()); stream.close(ctx.asyncAssertSuccess(v1 -> { ps.close(ctx.asyncAssertSuccess(v2 -> { async.complete(); })); })); })); })); })); })); } @Test public void testStreamQuery(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options(), ctx.asyncAssertSuccess(conn -> { conn.query("BEGIN", ctx.asyncAssertSuccess(begin -> { conn.prepare("SELECT * FROM Fortune", ctx.asyncAssertSuccess(ps -> { PgStream stream = ps.createStream(4, Tuple.tuple()); List rows = new ArrayList<>(); AtomicInteger ended = new AtomicInteger(); stream.endHandler(v -> { ctx.assertEquals(0, ended.getAndIncrement()); ctx.assertEquals(12, rows.size()); async.complete(); }); stream.handler(tuple -> { ctx.assertEquals(0, ended.get()); rows.add(tuple); }); })); })); })); } @Test public void testStreamQueryPauseInBatch(TestContext ctx) { testStreamQueryPauseInBatch(ctx, Runnable::run); } @Test public void testStreamQueryPauseInBatchFromAnotherThread(TestContext ctx) { testStreamQueryPauseInBatch(ctx, t -> new Thread(t).start()); } private void testStreamQueryPauseInBatch(TestContext ctx, Executor executor) { Async async = ctx.async(); PgClient.connect(vertx, options(), ctx.asyncAssertSuccess(conn -> { conn.query("BEGIN", ctx.asyncAssertSuccess(begin -> { conn.prepare("SELECT * FROM Fortune", ctx.asyncAssertSuccess(ps -> { PgStream stream = ps.createStream(4, Tuple.tuple()); List rows = Collections.synchronizedList(new ArrayList<>()); AtomicInteger ended = new AtomicInteger(); executor.execute(() -> { stream.endHandler(v -> { ctx.assertEquals(0, ended.getAndIncrement()); ctx.assertEquals(12, rows.size()); async.complete(); }); stream.handler(tuple -> { rows.add(tuple); if (rows.size() == 2) { stream.pause(); executor.execute(() -> { vertx.setTimer(100, v -> { executor.execute(stream::resume); }); }); } }); }); })); })); })); } @Test public void testStreamQueryError(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options(), ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT * FROM Fortune", ctx.asyncAssertSuccess(ps -> { PgStream stream = ps.createStream(4, Tuple.tuple()); stream.endHandler(v -> ctx.fail()); AtomicInteger rowCount = new AtomicInteger(); stream.exceptionHandler(err -> { ctx.assertEquals(4, rowCount.getAndIncrement()); async.complete(); }); stream.handler(tuple -> rowCount.incrementAndGet()); })); })); } @Test public void testCursorNoTx(TestContext ctx) { PgClient.connect(vertx, options(), ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT * FROM Fortune", ctx.asyncAssertSuccess(ps -> { PgCursor cursor = ps.cursor(Tuple.tuple()); cursor.read(1, ctx.asyncAssertSuccess(rowSet -> { cursor.read(1, ctx.asyncAssertFailure(err -> { PgException pgErr = (PgException) err; // This fails expectedly because the portal is closed ctx.assertEquals("34000", pgErr.getCode()); // invalid_cursor_name })); })); })); })); } /* @Test public void testStreamQueryCancel(TestContext ctx) { Async async = ctx.async(); PgConnection.connect(vertx, options(), (ctx.asyncAssertSuccess(conn -> { conn.query("BEGIN").execute(ctx.asyncAssertSuccess(begin -> { conn.prepare("SELECT * FROM Fortune", ctx.asyncAssertSuccess(ps -> { PgStream createStream = ps.createStream(Tuple.tuple()); AtomicInteger count = new AtomicInteger(); createStream.handler(tuple -> { ctx.assertEquals(0, count.getAndIncrement()); createStream.handler(null); }); })); })); })); } */ } ================================================ FILE: src/test/java/io/reactiverse/pgclient/ProxyServer.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.net.NetClient; import io.vertx.core.net.NetServer; import io.vertx.core.net.NetSocket; import java.util.function.Function; /** * A proxy server, useful for changing some server behavior * * @author Julien Viet */ class ProxyServer { static ProxyServer create(Vertx vertx, int pgPort, String pgHost) { return new ProxyServer(vertx, pgPort, pgHost); } static class Connection { private final NetSocket clientSocket; private final NetSocket serverSocket; private Function serverSocketFilter = Function.identity(); private Function clientSocketFilter = Function.identity(); public Connection(NetSocket clientSo, NetSocket serverSo) { this.clientSocket = clientSo; this.serverSocket = serverSo; } NetSocket clientSocket() { return clientSocket; } NetSocket serverSocket() { return serverSocket; } Connection serverSocketFilter(Function filter) { serverSocketFilter = filter; return this; } Connection clientSocketFilter(Function filter) { clientSocketFilter = filter; return this; } void connect() { clientSocket.handler(buff -> serverSocket.write(serverSocketFilter.apply(buff))); serverSocket.handler(buff -> clientSocket.write(clientSocketFilter.apply(buff))); clientSocket.closeHandler(v -> serverSocket.close()); serverSocket.closeHandler(v -> clientSocket.close()); serverSocket.resume(); clientSocket.resume(); } void close() { clientSocket.close(); serverSocket.close(); } } private final Vertx vertx; private final NetServer server; private final NetClient client; private final int pgPort; private final String pgHost; private Handler proxyHandler; private ProxyServer(Vertx vertx, int pgPort, String pgHost) { this.pgPort = pgPort; this.pgHost = pgHost; this.vertx = vertx; this.client = vertx.createNetClient(); this.server = vertx.createNetServer().connectHandler(this::handle); this.proxyHandler = Connection::connect; } public ProxyServer proxyHandler(Handler proxyHandler) { this.proxyHandler = proxyHandler; return this; } public void listen(int port, String host, Handler> completionHandler) { server.listen(port, host, ar -> completionHandler.handle(ar.mapEmpty())); } private void handle(NetSocket clientSocket) { clientSocket.pause(); client.connect(pgPort, pgHost, ar -> { if (ar.succeeded()) { NetSocket serverSocket = ar.result(); serverSocket.pause(); Connection conn = new Connection(clientSocket, serverSocket); proxyHandler.handle(conn); } else { clientSocket.close(); } }); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/PubSubTest.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.reactiverse.pgclient.pubsub.PgSubscriber; import io.reactiverse.pgclient.impl.pubsub.PgSubscriberImpl; import io.reactiverse.pgclient.pubsub.PgChannel; import io.vertx.core.Vertx; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Arrays; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; @RunWith(VertxUnitRunner.class) public class PubSubTest extends PgTestBase { Vertx vertx; PgSubscriber subscriber; @Before public void setup() { vertx = Vertx.vertx(); } @After public void teardown(TestContext ctx) { if (subscriber != null) { subscriber.close(); } vertx.close(ctx.asyncAssertSuccess()); } @Test public void testNotify(TestContext ctx) { testNotify(ctx, "the_channel"); } @Test public void testNotifyChannelRequiresQuotedID(TestContext ctx) { testNotify(ctx, "The.Channel"); } public void testNotify(TestContext ctx, String channelName) { String quotedChannelName = "\"" + channelName.replace("\"", "\"\"") + "\""; Async async = ctx.async(2); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.query("LISTEN " + quotedChannelName, ctx.asyncAssertSuccess(result1 -> { conn.notificationHandler(notification -> { ctx.assertEquals(channelName, notification.getChannel()); ctx.assertEquals("the message", notification.getPayload()); async.countDown(); }); conn.query("NOTIFY " + quotedChannelName + ", 'the message'", ctx.asyncAssertSuccess(result2 -> { async.countDown(); })); })); })); } @Test public void testConnect(TestContext ctx) { testConnect(ctx, "channel1", "channel2"); } @Test public void testConnectChannelRequiresQuotedID(TestContext ctx) { testConnect(ctx, "Channel.Test.1", "Channel.Test.2"); } private void testConnect(TestContext ctx, String channel1Name, String channel2Name) { String quotedChannel1Name = "\"" + channel1Name.replace("\"", "\"\"") + "\""; String quotedChannel2Name = "\"" + channel2Name.replace("\"", "\"\"") + "\""; subscriber = PgSubscriber.subscriber(vertx, options); Async notifiedLatch = ctx.async(); PgChannel sub1 = subscriber.channel(channel1Name); PgChannel sub2 = subscriber.channel(channel2Name); sub1.handler(notif -> { ctx.assertEquals("msg1", notif); notifiedLatch.countDown(); }); sub2.handler(notif -> { ctx.assertEquals("msg2", notif); notifiedLatch.countDown(); }); Async connectLatch = ctx.async(); subscriber.connect(ctx.asyncAssertSuccess(v -> connectLatch.complete())); connectLatch.awaitSuccess(10000); subscriber.actualConnection().query("NOTIFY " + quotedChannel1Name + ", 'msg1'", ctx.asyncAssertSuccess()); subscriber.actualConnection().query("NOTIFY " + quotedChannel2Name + ", 'msg2'", ctx.asyncAssertSuccess()); notifiedLatch.awaitSuccess(10000); } @Test public void testSubscribe(TestContext ctx) { testSubscribe(ctx, "the_channel"); } @Test public void testSubscribeChannelRequiresQuotedID(TestContext ctx) { testSubscribe(ctx, "The.Channel"); } @Test public void testSubscribeChannelContainsQuotes(TestContext ctx) { testSubscribe(ctx, "\"The\".\"Channel\""); } @Test public void testSubscribeChannelExceedsLengthLimit(TestContext ctx) { char[] channelNameChars = new char[PgSubscriberImpl.MAX_CHANNEL_NAME_LENGTH + 5]; Arrays.fill(channelNameChars, 0, PgSubscriberImpl.MAX_CHANNEL_NAME_LENGTH, 'a'); Arrays.fill(channelNameChars, PgSubscriberImpl.MAX_CHANNEL_NAME_LENGTH, channelNameChars.length, 'b'); String channelName = new String(channelNameChars); testSubscribe(ctx, channelName); } public void testSubscribe(TestContext ctx, String channelName) { String quotedChannelName = "\"" + channelName.replace("\"", "\"\"") + "\""; subscriber = PgSubscriber.subscriber(vertx, options); Async connectLatch = ctx.async(); subscriber.connect(ctx.asyncAssertSuccess(v -> connectLatch.complete())); connectLatch.awaitSuccess(10000); PgChannel channel = subscriber.channel(channelName); Async subscribedLatch = ctx.async(); ctx.assertEquals(channel, channel.subscribeHandler(v -> subscribedLatch.complete())); Async notifiedLatch = ctx.async(); channel.handler(notif -> { ctx.assertEquals("msg", notif); notifiedLatch.countDown(); }); subscribedLatch.awaitSuccess(10000); subscriber.actualConnection().query("NOTIFY " + quotedChannelName + ", 'msg'", ctx.asyncAssertSuccess()); notifiedLatch.awaitSuccess(10000); } @Test public void testSubscribeNotifyWithUnquotedId(TestContext ctx) { subscriber = PgSubscriber.subscriber(vertx, options); Async connectLatch = ctx.async(); subscriber.connect(ctx.asyncAssertSuccess(v -> connectLatch.complete())); connectLatch.awaitSuccess(10000); PgChannel channel = subscriber.channel("the_channel"); Async subscribedLatch = ctx.async(); ctx.assertEquals(channel, channel.subscribeHandler(v -> subscribedLatch.complete())); Async notifiedLatch = ctx.async(); channel.handler(notif -> { ctx.assertEquals("msg", notif); notifiedLatch.countDown(); }); subscribedLatch.awaitSuccess(10000); subscriber.actualConnection().query("NOTIFY The_Channel, 'msg'", ctx.asyncAssertSuccess()); notifiedLatch.awaitSuccess(10000); } @Test public void testUnsubscribe(TestContext ctx) { testUnsubscribe(ctx, "the_channel"); } @Test public void testUnsubscribeChannelRequiresQuotedID(TestContext ctx) { testUnsubscribe(ctx, "The.Channel"); } public void testUnsubscribe(TestContext ctx, String channelName) { subscriber = PgSubscriber.subscriber(vertx, options); Async connectLatch = ctx.async(); subscriber.connect(ctx.asyncAssertSuccess(v -> connectLatch.complete())); connectLatch.awaitSuccess(10000); PgChannel sub = subscriber.channel("the_channel"); Async endLatch = ctx.async(); sub.endHandler(v -> endLatch.complete()); Async subscribedLatch = ctx.async(); sub.subscribeHandler(v -> subscribedLatch.complete()); sub.handler(notif -> { }); subscribedLatch.awaitSuccess(10000); sub.handler(null); endLatch.awaitSuccess(10000); } @Test public void testReconnectImmediately(TestContext ctx) { testReconnect(ctx, 0, "the_channel"); } @Test public void testReconnectImmediatelyChannelRequiresQuotedID(TestContext ctx) { testReconnect(ctx, 0, "The.Channel"); } @Test public void testReconnectWithDelay(TestContext ctx) { testReconnect(ctx, 100, "the_channel"); } @Test public void testReconnectWithDelayChannelRequiresQuotedID(TestContext ctx) { testReconnect(ctx, 100, "The.Channel"); } public void testReconnect(TestContext ctx, long delay, String channelName) { PgConnectOptions options = new PgConnectOptions(PgTestBase.options); ProxyServer proxy = ProxyServer.create(vertx, options.getPort(), options.getHost()); AtomicReference connRef = new AtomicReference<>(); proxy.proxyHandler(conn -> { connRef.set(conn); conn.connect(); }); Async listenLatch = ctx.async(); proxy.listen(8080, "localhost", ctx.asyncAssertSuccess(v -> { options.setPort(8080).setHost("localhost"); listenLatch.complete(); })); listenLatch.awaitSuccess(10000); subscriber = PgSubscriber.subscriber(vertx, options); PgChannel sub = subscriber.channel(channelName); Async connect1Latch = ctx.async(); Async connect2Latch = ctx.async(); Async connect3Latch = ctx.async(); AtomicInteger times = new AtomicInteger(); sub.subscribeHandler(v -> { switch (times.getAndIncrement()) { case 0: connect1Latch.complete(); break; case 1: connect2Latch.complete(); break; case 2: connect3Latch.complete(); break; } }); subscriber.connect(ar -> { }); sub.handler(notif -> { }); connect1Latch.awaitSuccess(10000); AtomicInteger count = new AtomicInteger(); subscriber.reconnectPolicy(retries -> { ctx.assertEquals(0, retries); ctx.assertFalse(subscriber.closed()); if (count.getAndIncrement() < 2) { return delay; } else { return -1L; } }); Async closeLatch = ctx.async(); subscriber.closeHandler(v -> closeLatch.complete()); connRef.get().close(); connect2Latch.awaitSuccess(10000); connRef.get().close(); connect3Latch.awaitSuccess(10000); connRef.get().close(); closeLatch.awaitSuccess(10000); ctx.assertEquals(3, count.get()); ctx.assertTrue(subscriber.closed()); } @Test public void testClose(TestContext ctx) { testClose(ctx, "the_channel"); } @Test public void testCloseChannelRequiresQuotedID(TestContext ctx) { testClose(ctx, "The.Channel"); } public void testClose(TestContext ctx, String channelName) { PgSubscriber subscriber = PgSubscriber.subscriber(vertx, options); PgChannel sub = subscriber.channel(channelName); Async endLatch = ctx.async(); sub.endHandler(v -> endLatch.complete()); sub.handler(notif -> { }); Async connectLatch = ctx.async(); subscriber.connect(ctx.asyncAssertSuccess(v -> connectLatch.complete())); connectLatch.awaitSuccess(10000); Async closeLatch = ctx.async(); subscriber.closeHandler(v -> closeLatch.complete()); subscriber.close(); endLatch.awaitSuccess(10000); closeLatch.awaitSuccess(10000); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/RowTest.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.vertx.core.Vertx; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Arrays; import java.util.List; import java.util.function.Function; @RunWith(VertxUnitRunner.class) public class RowTest extends PgTestBase { Vertx vertx; @Before public void setup() { vertx = Vertx.vertx(); } @After public void teardown(TestContext ctx) { vertx.close(ctx.asyncAssertSuccess()); } @Test public void testGetNonExistingRows(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.query("SELECT 1 \"foo\"", ctx.asyncAssertSuccess(result -> { Row row = result.iterator().next(); List> functions = Arrays.asList( row::getValue, row::getString, row::getBuffer, row::getDouble, row::getShort, row::getInteger, row::getLong, row::getBigDecimal, row::getNumeric, row::getFloat, row::getLocalDate, row::getLocalTime, row::getOffsetDateTime, row::getLocalDateTime, row::getOffsetTime, row::getTemporal, row::getUUID, row::getPoint, row::getLine, row::getLineSegment, row::getBox, row::getPath, row::getPolygon, row::getCircle, row::getInterval, row::getBooleanArray, row::getShortArray, row::getIntegerArray, row::getLongArray, row::getFloatArray, row::getDoubleArray, row::getStringArray, row::getLocalDateArray, row::getLocalTimeArray, row::getOffsetTimeArray, row::getLocalDateTimeArray, row::getOffsetDateTimeArray, row::getBufferArray, row::getUUIDArray, row::getPointArray, row::getLineArray, row::getLineSegmentArray, row::getBoxArray, row::getPathArray, row::getPolygonArray, row::getCircleArray, row::getIntervalArray ); functions.forEach(f -> { ctx.assertEquals(null, f.apply("bar")); try { f.apply(null); ctx.fail("Was expecting an NPE"); } catch (NullPointerException ignore) { } }); async.complete(); })); })); } @Test public void testGetColumnNameRows(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.query("SELECT 2 \"foo\"", ctx.asyncAssertSuccess(result -> { Row row = result.iterator().next(); ctx.assertEquals("foo",row.getColumnName(0)); async.complete(); })); })); } @Test public void testNotEqualGetColumnNameRows(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.query("SELECT 2 \"foo\"", ctx.asyncAssertSuccess(result -> { Row row = result.iterator().next(); ctx.assertNotEquals("bar",row.getColumnName(0)); async.complete(); })); })); } @Test public void testNegativeGetColumnNameRows(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.query("SELECT 2 \"foo\"", ctx.asyncAssertSuccess(result -> { Row row = result.iterator().next(); ctx.assertNull(row.getColumnName(-1)); async.complete(); })); })); } @Test public void testPreventLengthMaxIndexOutOfBoundGetColumnNameRows(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.query("SELECT 2 \"foo\"", ctx.asyncAssertSuccess(result -> { Row row = result.iterator().next(); ctx.assertNull(row.getColumnName(1)); async.complete(); })); })); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/RxTest.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.reactiverse.reactivex.pgclient.PgStream; import io.reactiverse.reactivex.pgclient.Row; import io.reactiverse.reactivex.pgclient.Tuple; import io.reactiverse.reactivex.pgclient.PgPool; import io.reactiverse.reactivex.pgclient.PgClient; import io.reactivex.Flowable; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import io.vertx.reactivex.core.Vertx; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import java.util.Collections; import java.util.HashSet; import java.util.Set; @RunWith(VertxUnitRunner.class) public class RxTest extends PgTestBase { Vertx vertx; PgConnectOptions options; PgPool pool; @Before public void setup() { vertx = Vertx.vertx(); options = new PgConnectOptions(PgTestBase.options); pool = PgClient.pool(vertx, new PgPoolOptions(options).setMaxSize(1)); } @After public void teardown(TestContext ctx) { vertx.close(ctx.asyncAssertSuccess()); } private Flowable createFlowable(String sql) { return pool.rxBegin() .flatMapPublisher(tx -> tx.rxPrepare(sql) .flatMapPublisher(preparedQuery -> { // Fetch 50 rows at a time PgStream stream = preparedQuery.createStream(50, Tuple.tuple()); return stream.toFlowable(); }) .doAfterTerminate(tx::commit)); } @Test public void testFlowableCommit(TestContext ctx) { Async async = ctx.async(); Flowable flowable = createFlowable("SELECT id, randomnumber from WORLD"); flowable.subscribe(new Subscriber() { private Subscription sub; private Set ids = new HashSet<>(); { // Expected ids for (int i = 1;i <= 10000;i++) { ids.add(i); } } @Override public void onSubscribe(Subscription subscription) { sub = subscription; subscription.request(1); } @Override public void onNext(Row row) { ids.remove(row.getInteger("id")); sub.request(1); } @Override public void onError(Throwable err) { ctx.fail(err); } @Override public void onComplete() { ctx.assertEquals(Collections.emptySet(), ids); // Check the pool is back in the pool by the commit pool.rxGetConnection().subscribe(conn -> { conn.close(); async.complete(); }, ctx::fail); } }); } @Test public void testFlowableError(TestContext ctx) { Async async = ctx.async(); Flowable flowable = createFlowable("invalid SQL"); flowable.subscribe(row -> { ctx.fail("Should not get rows"); }, error -> { // Check the pool is back in the pool after implicit transaction rollback pool.rxGetConnection().subscribe(conn -> { conn.close(); async.complete(); }, ctx::fail); }); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/StringLongSequenceTest.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.reactiverse.pgclient.impl.StringLongSequence; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.junit.Assert; import org.junit.Test; import java.nio.charset.StandardCharsets; public class StringLongSequenceTest { @Test public void testSequence() { StringLongSequence seq = new StringLongSequence(); assertEquals("0000000", seq.next()); assertEquals("0000001", seq.next()); assertEquals("0000002", seq.next()); assertEquals("0000003", seq.next()); assertEquals("0000004", seq.next()); assertEquals("0000005", seq.next()); assertEquals("0000006", seq.next()); assertEquals("0000007", seq.next()); assertEquals("0000008", seq.next()); assertEquals("0000009", seq.next()); assertEquals("000000A", seq.next()); assertEquals("000000B", seq.next()); assertEquals("000000C", seq.next()); assertEquals("000000D", seq.next()); assertEquals("000000E", seq.next()); assertEquals("000000F", seq.next()); assertEquals("0000010", seq.next()); } @Test public void testEndingZero() { StringLongSequence seq = new StringLongSequence(); for (int i = 0;i < 10000;i++) { Assert.assertEquals(0, seq.next() & 0xFF); } } private static void assertEquals(String s, long l) { ByteBuf buf = Unpooled.buffer(); buf.writeLong(l); String actual = buf.getCharSequence(0, 7, StandardCharsets.UTF_8).toString(); Assert.assertEquals(s, actual); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/TLSTest.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.vertx.core.Vertx; import io.vertx.core.VertxException; import io.vertx.core.net.PemTrustOptions; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.*; import org.junit.runner.RunWith; @RunWith(VertxUnitRunner.class) public class TLSTest { private static PgConnectOptions options; private Vertx vertx; @BeforeClass public static void beforeClass() throws Exception { options = PgTestBase.startPg(false, true); } @AfterClass public static void afterClass() throws Exception { PgTestBase.stopPg(); } @Before public void setup() { vertx = Vertx.vertx(); } @After public void teardown(TestContext ctx) { vertx.close(ctx.asyncAssertSuccess()); } @Test public void testTLS(TestContext ctx) { Async async = ctx.async(); PgConnectOptions options = new PgConnectOptions(TLSTest.options) .setSslMode(SslMode.REQUIRE) .setPemTrustOptions(new PemTrustOptions().addCertPath("tls/server.crt")); PgClient.connect(vertx, new PgConnectOptions(options).setSslMode(SslMode.REQUIRE).setTrustAll(true), ctx.asyncAssertSuccess(conn -> { ctx.assertTrue(conn.isSSL()); conn.query("SELECT * FROM Fortune WHERE id=1", ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); Tuple row = result.iterator().next(); ctx.assertEquals(1, row.getInteger(0)); ctx.assertEquals("fortune: No such file or directory", row.getString(1)); async.complete(); })); })); } @Test public void testTLSTrustAll(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, new PgConnectOptions(options).setSslMode(SslMode.REQUIRE).setTrustAll(true), ctx.asyncAssertSuccess(conn -> { ctx.assertTrue(conn.isSSL()); async.complete(); })); } @Test public void testTLSInvalidCertificate(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, new PgConnectOptions(options).setSslMode(SslMode.REQUIRE), ctx.asyncAssertFailure(err -> { ctx.assertEquals(err.getClass(), VertxException.class); ctx.assertEquals(err.getMessage(), "SSL handshake failed"); async.complete(); })); } @Test public void testSslModeDisable(TestContext ctx) { Async async = ctx.async(); PgConnectOptions options = new PgConnectOptions(TLSTest.options) .setSslMode(SslMode.DISABLE); PgClient.connect(vertx, new PgConnectOptions(options), ctx.asyncAssertSuccess(conn -> { ctx.assertFalse(conn.isSSL()); async.complete(); })); } @Test public void testSslModeAllow(TestContext ctx) { Async async = ctx.async(); PgConnectOptions options = new PgConnectOptions(TLSTest.options) .setSslMode(SslMode.ALLOW); PgClient.connect(vertx, new PgConnectOptions(options), ctx.asyncAssertSuccess(conn -> { ctx.assertFalse(conn.isSSL()); async.complete(); })); } @Test public void testSslModePrefer(TestContext ctx) { Async async = ctx.async(); PgConnectOptions options = new PgConnectOptions(TLSTest.options) .setSslMode(SslMode.PREFER) .setTrustAll(true); PgClient.connect(vertx, new PgConnectOptions(options), ctx.asyncAssertSuccess(conn -> { ctx.assertTrue(conn.isSSL()); async.complete(); })); } @Test public void testSslModeVerifyCaConf(TestContext ctx) { PgConnectOptions options = new PgConnectOptions(TLSTest.options) .setSslMode(SslMode.VERIFY_CA) .setTrustAll(true); PgClient.connect(vertx, new PgConnectOptions(options), ctx.asyncAssertFailure(error -> { ctx.assertEquals("Trust options must be specified under verify-full or verify-ca sslmode", error.getMessage()); })); } @Test public void testSslModeVerifyFullConf(TestContext ctx) { PgConnectOptions options = new PgConnectOptions(TLSTest.options) .setSslMode(SslMode.VERIFY_FULL); PgClient.connect(vertx, new PgConnectOptions(options), ctx.asyncAssertFailure(error -> { ctx.assertEquals("Host verification algorithm must be specified under verify-full sslmode", error.getMessage()); })); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/TupleTest.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import org.junit.Assert; import org.junit.Test; import java.sql.Time; import java.sql.Timestamp; import java.time.Instant; import java.time.LocalTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.Calendar; import java.util.Date; import static org.junit.Assert.*; public class TupleTest { @Test public void testOf() { Tuple tuple = Tuple.of( ZonedDateTime.now(), Instant.now(), ZoneId.of("UTC"), new Date(), Calendar.getInstance(), ZoneOffset.UTC, Time.valueOf(LocalTime.MAX), Timestamp.from(Instant.EPOCH) ); assertEquals(8, tuple.size()); Assert.assertNull(tuple.getValue(0)); Assert.assertNull(tuple.getValue(1)); Assert.assertNull(tuple.getValue(2)); Assert.assertNull(tuple.getValue(3)); Assert.assertNull(tuple.getValue(4)); Assert.assertNull(tuple.getValue(5)); Assert.assertNull(tuple.getValue(6)); Assert.assertNull(tuple.getValue(7)); } @Test public void testNumbers() { Tuple tuple = Tuple.of((byte)127, (short)4000, 1_000_000, 1_000_000_000L, 4.5F, 4.5D); assertEquals(127, (short)tuple.getShort(0)); assertEquals(4000, (short)tuple.getShort(1)); assertEquals(4, (short)tuple.getShort(4)); assertEquals(4, (short)tuple.getShort(5)); assertEquals(127, (int)tuple.getInteger(0)); assertEquals(4000, (int)tuple.getInteger(1)); assertEquals(1_000_000, (int)tuple.getInteger(2)); assertEquals(1_000_000_000, (int)tuple.getInteger(3)); assertEquals(4, (int)tuple.getInteger(4)); assertEquals(4, (int)tuple.getInteger(5)); assertEquals(127, (long)tuple.getLong(0)); assertEquals(4000, (long)tuple.getLong(1)); assertEquals(1_000_000, (long)tuple.getLong(2)); assertEquals(1_000_000_000, (long)tuple.getLong(3)); assertEquals(4, (long)tuple.getLong(4)); assertEquals(4, (long)tuple.getLong(5)); assertEquals(127, tuple.getFloat(0), 0.0f); assertEquals(4000, tuple.getFloat(1), 0.0f); assertEquals(1_000_000, tuple.getFloat(2), 0.0f); assertEquals(1_000_000_000, tuple.getFloat(3), 0.0f); assertEquals(4.5, tuple.getFloat(4), 0.0f); assertEquals(4.5, tuple.getFloat(5), 0.0f); assertEquals(127, tuple.getDouble(0), 0.0D); assertEquals(4000, tuple.getDouble(1), 0.0D); assertEquals(1_000_000, tuple.getDouble(2), 0.0D); assertEquals(1_000_000_000, tuple.getDouble(3), 0.0D); assertEquals(4.5, tuple.getDouble(4), 0.0D); assertEquals(4.5, tuple.getDouble(5), 0.0D); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/UnixDomainSocketTest.java ================================================ /* * Copyright (C) 2018 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.vertx.core.Vertx; import io.vertx.core.VertxOptions; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.*; import org.junit.runner.RunWith; import static org.junit.Assert.assertFalse; import static org.junit.Assume.assumeTrue; @RunWith(VertxUnitRunner.class) public class UnixDomainSocketTest { private static final String unixSocketDirectory = System.getProperty("unix.socket.directory"); private static final String unixSocketPort = System.getProperty("unix.socket.port"); private static PgConnectOptions options; private PgPool client; @BeforeClass public static void beforeClass() throws Exception { Vertx vertx = Vertx.vertx(new VertxOptions().setPreferNativeTransport(true)); boolean nativeTransportEnabled = vertx.isNativeTransportEnabled(); vertx.close(); options = PgTestBase.startPg(nativeTransportEnabled, false); if (unixSocketDirectory != null && !unixSocketDirectory.isEmpty()) { options.setHost(unixSocketDirectory); } if (unixSocketPort != null && !unixSocketPort.isEmpty()) { options.setPort(Integer.parseInt(unixSocketPort)); } } @AfterClass public static void afterClass() throws Exception { PgTestBase.stopPg(); } @Before public void before() { } @After public void after() { if (client != null) { client.close(); } } @Test public void uriTest(TestContext context) { assumeTrue(options.isUsingDomainSocket()); String uri = "postgresql://postgres:postgres@/postgres?host=" + options.getHost() + "&port=" + options.getPort(); client = PgClient.pool(uri); client.getConnection(context.asyncAssertSuccess(pgConnection -> pgConnection.close())); } @Test public void simpleConnect(TestContext context) { assumeTrue(options.isUsingDomainSocket()); client = PgClient.pool(new PgPoolOptions(options)); client.getConnection(context.asyncAssertSuccess(pgConnection -> pgConnection.close())); } @Test public void connectWithVertxInstance(TestContext context) { assumeTrue(options.isUsingDomainSocket()); Vertx vertx = Vertx.vertx(new VertxOptions().setPreferNativeTransport(true)); try { client = PgClient.pool(vertx, new PgPoolOptions(options)); Async async = context.async(); client.getConnection(context.asyncAssertSuccess(pgConnection -> { async.complete(); pgConnection.close(); })); async.await(); } finally { vertx.close(); } } @Test public void testIgnoreSslMode(TestContext context) { assumeTrue(options.isUsingDomainSocket()); client = PgClient.pool(new PgPoolOptions(options).setSslMode(SslMode.REQUIRE)); client.getConnection(context.asyncAssertSuccess(pgConnection -> { assertFalse(pgConnection.isSSL()); pgConnection.close(); })); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/UtilTest.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.reactiverse.pgclient.impl.codec.util.UTF8StringEndDetector; import io.reactiverse.pgclient.impl.codec.util.Util; import io.vertx.core.buffer.Buffer; import org.junit.Test; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertEquals; public class UtilTest { @Test public void testWriteHexString() { assertWriteHexString("00", (byte) 0); assertWriteHexString("01", (byte) 1); assertWriteHexString("0a", (byte) 10); assertWriteHexString("10", (byte) 16); assertWriteHexString("ff", (byte) 255); assertWriteHexString("ff0a0a", (byte) 255, (byte)10, (byte)10); Buffer buff = Buffer.buffer(); for (int i = 0; i < 512;i++) { buff.appendByte((byte)('A' + i % 26)); } } private static void assertWriteHexString(String expected, byte... data) { ByteBuf buff = Unpooled.buffer(); Util.writeHexString(Buffer.buffer().appendBytes(data), buff); String hex = buff.toString(StandardCharsets.UTF_8); assertEquals(expected, hex); } @Test public void testUTF8StringEndDetector() throws Exception { assertSeparator("", -1); assertSeparator("\"", -1); assertSeparator("\"\"", 1); assertSeparator("\"a\"", 2); assertSeparator("\"€\"", 4); assertSeparator("\"\\\"\"", 3); } private void assertSeparator(String s, int expected) throws Exception { ByteBuf buf = Unpooled.buffer(); buf.writeCharSequence(s, StandardCharsets.UTF_8); UTF8StringEndDetector processor = new UTF8StringEndDetector(); int actual = buf.forEachByte(processor); assertEquals(expected, actual); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/BinaryDataTypesExtendedCodecTest.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.PgClient; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.Tuple; import io.vertx.core.buffer.Buffer; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import org.junit.Test; import java.util.Random; public class BinaryDataTypesExtendedCodecTest extends ExtendedQueryDataTypeCodecTestBase { @Test public void testBytea(TestContext ctx) { Random r = new Random(); int len = 2048; byte[] bytes = new byte[len]; r.nextBytes(bytes); Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT $1::BYTEA \"Bytea\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.of(Buffer.buffer(bytes)), ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Bytea") .returns(Tuple::getValue, Row::getValue, Buffer.buffer(bytes)) .returns(Tuple::getBuffer, Row::getBuffer, Buffer.buffer(bytes)) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testBufferArray(TestContext ctx) { Random r = new Random(); int len = 2048; byte[] bytes = new byte[len]; r.nextBytes(bytes); Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT ARRAY[$1::BYTEA] \"Bytea\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.of(Buffer.buffer(bytes)), ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Bytea") .returns(Tuple::getValue, Row::getValue, new Buffer[]{Buffer.buffer(bytes)}) .returns(Tuple::getBufferArray, Row::getBufferArray, new Buffer[]{Buffer.buffer(bytes)}) .forRow(result.iterator().next()); async.complete(); })); })); })); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/BinaryDataTypesSimpleCodecTest.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.Tuple; import io.vertx.core.buffer.Buffer; import io.vertx.ext.unit.TestContext; import org.junit.Test; public class BinaryDataTypesSimpleCodecTest extends SimpleQueryDataTypeCodecTestBase { @Test public void testByteaHexFormat1(TestContext ctx) { testDecodeGeneric(ctx, "12345678910", "BYTEA", "Buffer1", Tuple::getBuffer, Row::getBuffer, Buffer.buffer("12345678910")); } @Test public void testByteaHexFormat2(TestContext ctx) { testDecodeGeneric(ctx, "\u00DE\u00AD\u00BE\u00EF", "BYTEA", "Buffer2", Tuple::getBuffer, Row::getBuffer, Buffer.buffer("\u00DE\u00AD\u00BE\u00EF")); } @Test public void testByteaEscapeBackslash(TestContext ctx) { testDecodeGeneric(ctx, "\\\\\\134", "BYTEA", "Buffer3", Tuple::getBuffer, Row::getBuffer, Buffer.buffer(new byte[]{0x5C, 0x5C})); } @Test public void testByteaEscapeNonPrintableOctets(TestContext ctx) { testDecodeGeneric(ctx, "\\001\\007", "BYTEA", "Buffer4", Tuple::getBuffer, Row::getBuffer, Buffer.buffer(new byte[]{0x01, 0x07})); } @Test public void testByteaEscapePrintableOctets(TestContext ctx) { testDecodeGeneric(ctx, "123abc", "BYTEA", "Buffer5", Tuple::getBuffer, Row::getBuffer, Buffer.buffer(new byte[]{'1', '2', '3', 'a', 'b', 'c'})); } @Test public void testByteaEscapeSingleQuote(TestContext ctx) { testDecodeGeneric(ctx, "\'\'", "BYTEA", "Buffer6", Tuple::getBuffer, Row::getBuffer, Buffer.buffer(new byte[]{0x27})); } @Test public void testByteaEscapeZeroOctet(TestContext ctx) { testDecodeGeneric(ctx, "\\000", "BYTEA", "Buffer7", Tuple::getBuffer, Row::getBuffer, Buffer.buffer(new byte[]{0x00})); } @Test public void testByteaEscapeFormat(TestContext ctx) { testDecodeGeneric(ctx, "abc \\153\\154\\155 \\052\\251\\124", "BYTEA", "Buffer8", Tuple::getBuffer, Row::getBuffer, Buffer.buffer(new byte[]{'a', 'b', 'c', ' ', 'k', 'l', 'm', ' ', '*', (byte) 0xA9, 'T'})); } @Test public void testByteaEmptyString(TestContext ctx) { testDecodeGeneric(ctx, "", "BYTEA", "Buffer9", Tuple::getBuffer, Row::getBuffer, Buffer.buffer("")); } @Test public void testDecodeHexByteaArray(TestContext ctx) { testDecodeGenericArray(ctx, "ARRAY [decode('48454c4c4f', 'hex') :: BYTEA]", "BufferArray", Tuple::getBufferArray, Row::getBufferArray, Buffer.buffer("HELLO")); } @Test public void testDecodeEscapeByteaArray(TestContext ctx) { testDecodeGenericArray(ctx, "ARRAY [decode('abc \\153\\154\\155 \\052\\251\\124', 'escape') :: BYTEA]", "BufferArray2", Tuple::getBufferArray, Row::getBufferArray, Buffer.buffer(new byte[]{'a', 'b', 'c', ' ', 'k', 'l', 'm', ' ', '*', (byte) 0xA9, 'T'})); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/BooleanTypeExtendedCodecTest.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.PgClient; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.Tuple; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import org.junit.Test; public class BooleanTypeExtendedCodecTest extends ExtendedQueryDataTypeCodecTestBase { @Test public void testDecodeBoolean(TestContext ctx) { testGeneric(ctx, "SELECT $1::BOOLEAN \"Boolean\"", new Boolean[]{true}, Tuple::getBoolean); } @Test public void testEncodeBoolean(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"NumericDataType\" SET \"Boolean\" = $1 WHERE \"id\" = $2 RETURNING \"Boolean\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addBoolean(Boolean.FALSE) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Boolean") .returns(Tuple::getValue, Row::getValue, false) .returns(Tuple::getBoolean, Row::getBoolean, false) .forRow(row); async.complete(); })); })); })); } @Test public void testBooleanArray(TestContext ctx) { testGeneric(ctx, "SELECT c FROM (VALUES ($1 :: BOOL[])) AS t (c)", new Boolean[][]{new Boolean[]{true, null, false}}, Tuple::getBooleanArray); } @Test public void testDecodeBooleanArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Boolean\" FROM \"ArrayDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Boolean") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(new boolean[]{Boolean.TRUE})) .returns(Tuple::getBooleanArray, Row::getBooleanArray, ColumnChecker.toObjectArray(new boolean[]{Boolean.TRUE})) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeBooleanArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Boolean\" = $1 WHERE \"id\" = $2 RETURNING \"Boolean\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addBooleanArray(new Boolean[]{Boolean.FALSE, Boolean.TRUE}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Boolean") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(new boolean[]{Boolean.FALSE, Boolean.TRUE})) .returns(Tuple::getBooleanArray, Row::getBooleanArray, ColumnChecker.toObjectArray(new boolean[]{Boolean.FALSE, Boolean.TRUE})) .forRow(result.iterator().next()); async.complete(); })); })); })); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/BooleanTypeSimpleCodecTest.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.Tuple; import io.vertx.ext.unit.TestContext; import org.junit.Test; public class BooleanTypeSimpleCodecTest extends SimpleQueryDataTypeCodecTestBase { @Test public void testBoolean1(TestContext ctx) { testDecodeGeneric(ctx, "true", "BOOLEAN", "TrueValue", Tuple::getBoolean, Row::getBoolean, true); } @Test public void testBoolean2(TestContext ctx) { testDecodeGeneric(ctx, "false", "BOOLEAN", "FalseValue", Tuple::getBoolean, Row::getBoolean, false); } @Test public void testDecodeBOOLArray(TestContext ctx) { testDecodeGenericArray(ctx, "ARRAY ['TRUE' :: BOOLEAN,'FALSE' :: BOOLEAN]", "BooleanArray", Tuple::getBooleanArray, Row::getBooleanArray, true, false); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/CharacterTypesExtendedCodecTest.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.PgClient; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.Tuple; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import org.junit.Test; public class CharacterTypesExtendedCodecTest extends ExtendedQueryDataTypeCodecTestBase { @Test public void testDecodeName(TestContext ctx) { testGeneric(ctx, "SELECT $1::NAME \"Name\"", new String[]{"What is my name ?"}, Tuple::getString); } @Test public void testEncodeName(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"CharacterDataType\" SET \"Name\" = upper($1) WHERE \"id\" = $2 RETURNING \"Name\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addString("vert.x") .addInteger(2), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); String name = "VERT.X"; ColumnChecker.checkColumn(0, "Name") .returns(Tuple::getValue, Row::getValue, name) .returns(Tuple::getString, Row::getString, name) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeChar(TestContext ctx) { testGeneric(ctx, "SELECT $1::CHAR \"SingleChar\"", new String[]{"A"}, Tuple::getString); } @Test public void testEncodeChar(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"CharacterDataType\" SET \"SingleChar\" = upper($1) WHERE \"id\" = $2 RETURNING \"SingleChar\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addString("b") .addInteger(2), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); String singleChar = "B"; ColumnChecker.checkColumn(0, "SingleChar") .returns(Tuple::getValue, Row::getValue, singleChar) .returns(Tuple::getString, Row::getString, singleChar) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeFixedChar(TestContext ctx) { testGeneric(ctx, "SELECT $1::CHAR(3) \"FixedChar\"", new String[]{"YES"}, Tuple::getString); } @Test public void testEncodeFixedChar(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"CharacterDataType\" SET \"FixedChar\" = upper($1) WHERE \"id\" = $2 RETURNING \"FixedChar\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addString("no") .addInteger(2), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); String name = "NO "; ColumnChecker.checkColumn(0, "FixedChar") .returns(Tuple::getValue, Row::getValue, name) .returns(Tuple::getString, Row::getString, name) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeText(TestContext ctx) { testGeneric(ctx, "SELECT $1::TEXT \"Text\"", new String[]{"Hello World"}, Tuple::getString); } @Test public void testEncodeText(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"CharacterDataType\" SET \"Text\" = upper($1) WHERE \"id\" = $2 RETURNING \"Text\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addString("Hello World") .addInteger(2), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); String name = "HELLO WORLD"; ColumnChecker.checkColumn(0, "Text") .returns(Tuple::getValue, Row::getValue, name) .returns(Tuple::getString, Row::getString, name) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeVarCharacter(TestContext ctx) { testGeneric(ctx, "SELECT $1::VARCHAR \"VarCharacter\"", new String[]{"Great!"}, Tuple::getString); } @Test public void testEncodeVarCharacter(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"CharacterDataType\" SET \"VarCharacter\" = upper($1) WHERE \"id\" = $2 RETURNING \"VarCharacter\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addString("Great!") .addInteger(2), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); String name = "GREAT!"; ColumnChecker.checkColumn(0, "VarCharacter") .returns(Tuple::getValue, Row::getValue, name) .returns(Tuple::getString, Row::getString, name) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeLargeVarchar(TestContext ctx) { int len = 2048; StringBuilder builder = new StringBuilder(); for (int i = 0; i < len; i++) { builder.append((char) ('A' + (i % 26))); } String value = builder.toString(); Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT $1::VARCHAR(" + len + ")", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.of(value), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(value, result.iterator().next().getString(0)); async.complete(); })); })); })); } @Test public void testDecodeStringArray(TestContext ctx) { testGeneric(ctx, "SELECT $1::TEXT[]\"Text\"", new String[][]{new String[]{"Knock, knock.Who’s there?very long pause….Java."}}, Tuple::getStringArray); } @Test public void testEncodeStringArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Text\" = $1 WHERE \"id\" = $2 RETURNING \"Text\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addStringArray(new String[]{"Knock, knock.Who’s there?"}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Text") .returns(Tuple::getValue, Row::getValue, new String[]{"Knock, knock.Who’s there?"}) .returns(Tuple::getStringArray, Row::getStringArray, new String[]{"Knock, knock.Who’s there?"}) .forRow(result.iterator().next()); async.complete(); })); })); })); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/CharacterTypesSimpleCodecTest.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.Tuple; import io.vertx.ext.unit.TestContext; import org.junit.Test; public class CharacterTypesSimpleCodecTest extends SimpleQueryDataTypeCodecTestBase { @Test public void testName(TestContext ctx) { testDecodeGeneric(ctx, "VERT.X VERT.X VERT.X VERT.X VERT.X VERT.X VERT.X VERT.X VERT.X & VERT.X", "NAME", "Name", Tuple::getString, Row::getString, "VERT.X VERT.X VERT.X VERT.X VERT.X VERT.X VERT.X VERT.X VERT.X "); } @Test public void testBlankPaddedChar(TestContext ctx) { testDecodeGeneric(ctx, "pgClient", "CHAR(15)", "Char", Tuple::getString, Row::getString, "pgClient "); } @Test public void testSingleBlankPaddedChar(TestContext ctx) { testDecodeGeneric(ctx, "V", "CHAR", "Char", Tuple::getString, Row::getString, "V"); } @Test public void testSingleChar(TestContext ctx) { testDecodeGeneric(ctx, "X", "CHAR", "Character", Tuple::getString, Row::getString, "X"); } @Test public void testVarChar(TestContext ctx) { testDecodeGeneric(ctx, "pgClient", "VARCHAR(15)", "Driver", Tuple::getString, Row::getString, "pgClient"); } @Test public void testText(TestContext ctx) { testDecodeGeneric(ctx, "Vert.x PostgreSQL Client", "TEXT", "Text", Tuple::getString, Row::getString, "Vert.x PostgreSQL Client"); } @Test public void testDecodeCHARArray(TestContext ctx) { testDecodeGenericArray(ctx, "ARRAY['01234567' :: CHAR(8)]", "CharArray", Tuple::getStringArray, Row::getStringArray, "01234567"); } @Test public void testDecodeTEXTArray(TestContext ctx) { testDecodeGenericArray(ctx, "ARRAY ['Knock, knock.Who’s there?very long pause….Java.' :: TEXT]", "TextArray", Tuple::getStringArray, Row::getStringArray, "Knock, knock.Who’s there?very long pause….Java."); } @Test public void testDecodeVARCHARArray(TestContext ctx) { testDecodeGenericArray(ctx, "ARRAY ['Knock, knock.Who’s there?very long pause….Java.' :: VARCHAR]", "VarcharArray", Tuple::getStringArray, Row::getStringArray, "Knock, knock.Who’s there?very long pause….Java."); } @Test public void testDecodeNAMEArray(TestContext ctx) { testDecodeGenericArray(ctx, "ARRAY ['Knock, knock.Who’s there?very long pause….Java.' :: NAME]", "NameArray", Tuple::getStringArray, Row::getStringArray, "Knock, knock.Who’s there?very long pause….Java."); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/ColumnChecker.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.Tuple; import java.io.Serializable; import java.lang.invoke.SerializedLambda; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Consumer; import static org.junit.Assert.*; public class ColumnChecker { private static List> tupleMethods = new ArrayList<>(); private static List> rowMethods = new ArrayList<>(); static { tupleMethods.add(Tuple::getValue); rowMethods.add(Row::getValue); tupleMethods.add(Tuple::getShort); rowMethods.add(Row::getShort); tupleMethods.add(Tuple::getInteger); rowMethods.add(Row::getInteger); tupleMethods.add(Tuple::getLong); rowMethods.add(Row::getLong); tupleMethods.add(Tuple::getFloat); rowMethods.add(Row::getFloat); tupleMethods.add(Tuple::getDouble); rowMethods.add(Row::getDouble); tupleMethods.add(Tuple::getBigDecimal); rowMethods.add(Row::getBigDecimal); tupleMethods.add(Tuple::getNumeric); rowMethods.add(Row::getNumeric); tupleMethods.add(Tuple::getPoint); rowMethods.add(Row::getPoint); tupleMethods.add(Tuple::getString); rowMethods.add(Row::getString); tupleMethods.add(Tuple::getBoolean); rowMethods.add(Row::getBoolean); tupleMethods.add(Tuple::getBuffer); rowMethods.add(Row::getBuffer); tupleMethods.add(Tuple::getBuffer); rowMethods.add(Row::getBuffer); tupleMethods.add(Tuple::getTemporal); rowMethods.add(Row::getTemporal); tupleMethods.add(Tuple::getLocalDate); rowMethods.add(Row::getLocalDate); tupleMethods.add(Tuple::getLocalTime); rowMethods.add(Row::getLocalTime); tupleMethods.add(Tuple::getOffsetTime); rowMethods.add(Row::getOffsetTime); tupleMethods.add(Tuple::getLocalDateTime); rowMethods.add(Row::getLocalDateTime); tupleMethods.add(Tuple::getOffsetDateTime); rowMethods.add(Row::getOffsetDateTime); tupleMethods.add(Tuple::getBooleanArray); rowMethods.add(Row::getBooleanArray); tupleMethods.add(Tuple::getShortArray); rowMethods.add(Row::getShortArray); tupleMethods.add(Tuple::getIntegerArray); rowMethods.add(Row::getIntegerArray); tupleMethods.add(Tuple::getLongArray); rowMethods.add(Row::getLongArray); tupleMethods.add(Tuple::getFloatArray); rowMethods.add(Row::getFloatArray); tupleMethods.add(Tuple::getDoubleArray); rowMethods.add(Row::getDoubleArray); tupleMethods.add(Tuple::getStringArray); rowMethods.add(Row::getStringArray); tupleMethods.add(Tuple::getLocalDateArray); rowMethods.add(Row::getLocalDateArray); tupleMethods.add(Tuple::getLocalTimeArray); rowMethods.add(Row::getLocalTimeArray); tupleMethods.add(Tuple::getOffsetTimeArray); rowMethods.add(Row::getOffsetTimeArray); tupleMethods.add(Tuple::getLocalDateTimeArray); rowMethods.add(Row::getLocalDateTimeArray); tupleMethods.add(Tuple::getBufferArray); rowMethods.add(Row::getBufferArray); tupleMethods.add(Tuple::getUUIDArray); rowMethods.add(Row::getUUIDArray); tupleMethods.add(Tuple::getPointArray); rowMethods.add(Row::getPointArray); tupleMethods.add(Tuple::getLine); rowMethods.add(Row::getLine); tupleMethods.add(Tuple::getLineArray); rowMethods.add(Row::getLineArray); tupleMethods.add(Tuple::getLineSegment); rowMethods.add(Row::getLineSegment); tupleMethods.add(Tuple::getLineSegmentArray); rowMethods.add(Row::getLineSegmentArray); tupleMethods.add(Tuple::getBox); rowMethods.add(Row::getBox); tupleMethods.add(Tuple::getBoxArray); rowMethods.add(Row::getBoxArray); tupleMethods.add(Tuple::getPath); rowMethods.add(Row::getPath); tupleMethods.add(Tuple::getPathArray); rowMethods.add(Row::getPathArray); tupleMethods.add(Tuple::getPolygon); rowMethods.add(Row::getPolygon); tupleMethods.add(Tuple::getPolygonArray); rowMethods.add(Row::getPolygonArray); tupleMethods.add(Tuple::getCircle); rowMethods.add(Row::getCircle); tupleMethods.add(Tuple::getCircleArray); rowMethods.add(Row::getCircleArray); } public static ColumnChecker checkColumn(int index, String name) { return new ColumnChecker(index, name); } private final List blackList = new ArrayList<>(); private final List> expects = new ArrayList<>(); private final int index; private final String name; private ColumnChecker(int index, String name) { this.index = index; this.name = name; } public ColumnChecker returns(SerializableBiFunction byIndexGetter, SerializableBiFunction byNameGetter, R expected) { Method byIndexMeth = byIndexGetter.method(); blackList.add(byIndexMeth); Method byNameMeth = byNameGetter.method(); blackList.add(byNameMeth); expects.add(row -> { Object actual = byIndexGetter.apply(row, index); assertEquals("Expected that " + byIndexMeth + " returns " + expected + " instead of " + actual, expected, actual); actual = byNameGetter.apply(row, name); assertEquals("Expected that " + byNameMeth + " returns " + expected + " instead of " + actual, expected, actual); }); return this; } public ColumnChecker returns(SerializableBiFunction byIndexGetter, SerializableBiFunction byNameGetter, Object[] expected) { Method byIndexMeth = byIndexGetter.method(); blackList.add(byIndexMeth); Method byNameMeth = byNameGetter.method(); blackList.add(byNameMeth); expects.add(row -> { Object[] actual = toObjectArray(byIndexGetter.apply(row, index)); assertArrayEquals("Expected that " + byIndexMeth + " returns " + Arrays.toString(expected) + " instead of " + Arrays.toString(actual), expected, actual); actual = toObjectArray(byNameGetter.apply(row, name)); assertArrayEquals("Expected that " + byNameMeth + " returns " + Arrays.toString(expected) + " instead of " + Arrays.toString(actual), expected, actual); }); return this; } public ColumnChecker returns(SerializableBiFunction byIndexGetter, SerializableBiFunction byNameGetter, double expected, double delta) { blackList.add(byIndexGetter.method()); blackList.add(byNameGetter.method()); expects.add(row -> { Object actual = byIndexGetter.apply(row, index); assertEquals("Expected that " + byIndexGetter.method() + " returns " + expected + " instead of " + actual, expected, (double)actual, delta); actual = byNameGetter.apply(row, name); assertEquals("Expected that " + byNameGetter.method() + " returns " + expected + " instead of " + actual, expected, (double)actual, delta); }); return this; } public ColumnChecker returns(SerializableBiFunction byIndexGetter, SerializableBiFunction byNameGetter, float expected, float delta) { blackList.add(byIndexGetter.method()); blackList.add(byNameGetter.method()); expects.add(row -> { Object actual = byIndexGetter.apply(row, index); assertEquals("Expected that " + byIndexGetter.method() + " returns " + expected + " instead of " + actual, expected, (float)actual, delta); actual = byNameGetter.apply(row, name); assertEquals("Expected that " + byNameGetter.method() + " returns " + expected + " instead of " + actual, expected, (float)actual, delta); }); return this; } public ColumnChecker fails(SerializableBiFunction byIndexGetter, SerializableBiFunction byNameGetter) { blackList.add(byIndexGetter.method()); blackList.add(byNameGetter.method()); expects.add(row -> { try { byIndexGetter.apply(row, index); fail("Expected that " + byIndexGetter.method() + " would throw an exception"); } catch (Exception ignore) { } try { byNameGetter.apply(row, name); fail("Expected that " + byNameGetter.method() + " would throw an exception"); } catch (Exception ignore) { } }); return this; } public void forRow(Row row) { for (SerializableBiFunction m : tupleMethods) { if (!blackList.contains(m.method())) { Object v = m.apply(row, index); try { assertNull("Was expecting null for " + m.method() + " instead of " + v, v); } catch (Throwable e) { e.printStackTrace(); throw e; } } } for (SerializableBiFunction m : rowMethods) { if (!blackList.contains(m.method())) { Object v = m.apply(row, name); assertNull(v); } } for (Consumer e : expects) { e.accept(row); } } interface MethodReferenceReflection { //inspired by: http://benjiweber.co.uk/blog/2015/08/17/lambda-parameter-names-with-reflection/ default SerializedLambda serialized() { try { Method replaceMethod = getClass().getDeclaredMethod("writeReplace"); replaceMethod.setAccessible(true); return (SerializedLambda) replaceMethod.invoke(this); } catch (Exception e) { throw new RuntimeException(e); } } default Class getContainingClass() { try { String className = serialized().getImplClass().replaceAll("/", "."); return Class.forName(className); } catch (Exception e) { throw new RuntimeException(e); } } default Method method() { SerializedLambda lambda = serialized(); Class containingClass = getContainingClass(); return Arrays.stream(containingClass.getDeclaredMethods()) .filter(method -> Objects.equals(method.getName(), lambda.getImplMethodName())) .findFirst() .orElseThrow(MethodReferenceReflection.UnableToGuessMethodException::new); } class UnableToGuessMethodException extends RuntimeException {} } public interface SerializableBiFunction extends BiFunction, Serializable, MethodReferenceReflection {} public static Object[] toObjectArray(Object source) { if (source instanceof Object[]) { return (Object[]) source; } if (source == null) { return new Object[0]; } if (!source.getClass().isArray()) { throw new IllegalArgumentException("Source is not an array: " + source); } int length = Array.getLength(source); if (length == 0) { return new Object[0]; } Class wrapperType = Array.get(source, 0).getClass(); Object[] newArray = (Object[]) Array.newInstance(wrapperType, length); for (int i = 0; i < length; i++) { newArray[i] = Array.get(source, i); } return newArray; } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/CustomTypesExtendedCodecTest.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.PgClient; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.Tuple; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import org.junit.Test; public class CustomTypesExtendedCodecTest extends ExtendedQueryDataTypeCodecTestBase { @Test public void testEncodeCustomType(TestContext ctx) { Async async = ctx.async(); String actual = "('Othercity',\" 'Second Ave'\",f)"; PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"CustomDataType\" SET \"address\" = $1 WHERE \"id\" = $2 RETURNING \"address\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addString("('Othercity', 'Second Ave', false)") .addInteger(2) , ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "address") .returns(Tuple::getValue, Row::getValue, actual) .returns(Tuple::getString, Row::getString, actual) .forRow(row); async.complete(); })); })); })); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/CustomTypesSimpleCodecTest.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.PgClient; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.Tuple; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import org.junit.Test; public class CustomTypesSimpleCodecTest extends SimpleQueryDataTypeCodecTestBase { @Test public void testCustomType(TestContext ctx) { Async async = ctx.async(); String expected = "Anytown"; PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn .query("SELECT (address).city FROM \"CustomDataType\"", ctx.asyncAssertSuccess(result -> { ctx.assertEquals(2, result.size()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "city") .returns(Tuple::getValue, Row::getValue, expected) .returns(Tuple::getString, Row::getString, expected) .forRow(row); async.complete(); })); })); } @Test public void testDecodeCustomTypeArray(TestContext ctx) { String [] addresses = new String [] {"(Anytown,\"Main St\",t)", "(Anytown,\"First St\",f)"}; testDecodeXXXArray(ctx, "CustomType", "ArrayDataType", Tuple::getStringArray, Row::getStringArray, addresses); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/DataTypeTestBase.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.PgConnectOptions; import io.reactiverse.pgclient.PgTestBase; import io.vertx.core.Vertx; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.After; import org.junit.Before; import org.junit.runner.RunWith; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.OffsetDateTime; import java.time.OffsetTime; import java.time.format.DateTimeFormatter; import java.util.UUID; /** * @author Emad Alblueshi */ @RunWith(VertxUnitRunner.class) public abstract class DataTypeTestBase extends PgTestBase { protected Vertx vertx; protected abstract PgConnectOptions options(); protected static final UUID uuid = UUID.fromString("6f790482-b5bd-438b-a8b7-4a0bed747011"); protected static final LocalDateTime ldt = LocalDateTime.parse("2017-05-14T19:35:58.237666"); protected static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss.SSSSS"); protected static final LocalTime lt = LocalTime.parse("17:55:04.90512", dtf); protected static final OffsetTime dt = OffsetTime.parse("17:55:04.90512+03:00"); protected static final OffsetDateTime odt = OffsetDateTime.parse("2017-05-15T02:59:59.237666Z"); protected static final Interval[] intervals = new Interval[] { Interval.of().years(10).months(3).days(332).hours(20).minutes(20).seconds(20).microseconds(999991), Interval.of().minutes(20).seconds(20).microseconds(123456), Interval.of().years(-2).months(-6) }; @Before public void setup() { vertx = Vertx.vertx(); } @After public void teardown(TestContext ctx) { vertx.close(ctx.asyncAssertSuccess()); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/DateTimeTypesExtendedCodecTest.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.PgClient; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.Tuple; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import org.junit.Test; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.OffsetDateTime; import java.time.OffsetTime; import java.time.format.DateTimeFormatter; public class DateTimeTypesExtendedCodecTest extends ExtendedQueryDataTypeCodecTestBase { @Test public void testDecodeDateBeforePgEpoch(TestContext ctx) { testDecodeDataTimeGeneric(ctx, "DATE", "Date", Tuple::getLocalDate, Row::getLocalDate, LocalDate.parse("1981-05-30")); } @Test public void testEncodeDateBeforePgEpoch(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"TemporalDataType\" SET \"Date\" = $1 WHERE \"id\" = $2 RETURNING \"Date\"", ctx.asyncAssertSuccess(p -> { LocalDate ld = LocalDate.parse("1981-06-30"); p.execute(Tuple.tuple() .addLocalDate(ld) .addInteger(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Date") .returns(Tuple::getValue, Row::getValue, ld) .returns(Tuple::getLocalDate, Row::getLocalDate, ld) .returns(Tuple::getTemporal, Row::getTemporal, ld) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeDateAfterPgEpoch(TestContext ctx) { testDecodeDataTimeGeneric(ctx, "DATE", "Date", Tuple::getLocalDate, Row::getLocalDate, LocalDate.parse("2017-05-30")); } @Test public void testEncodeDateAfterPgEpoch(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"TemporalDataType\" SET \"Date\" = $1 WHERE \"id\" = $2 RETURNING \"Date\"", ctx.asyncAssertSuccess(p -> { LocalDate ld = LocalDate.parse("2018-05-30"); p.execute(Tuple.tuple() .addLocalDate(ld) .addInteger(4) , ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Date") .returns(Tuple::getValue, Row::getValue, ld) .returns(Tuple::getLocalDate, Row::getLocalDate, ld) .returns(Tuple::getTemporal, Row::getTemporal, ld) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeTime(TestContext ctx) { testDecodeDataTimeGeneric(ctx, "TIME WITHOUT TIME ZONE", "Time", Tuple::getLocalTime, Row::getLocalTime, LocalTime.parse("17:55:04.905120")); } @Test public void testEncodeTime(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"TemporalDataType\" SET \"Time\" = $1 WHERE \"id\" = $2 RETURNING \"Time\"", ctx.asyncAssertSuccess(p -> { LocalTime lt = LocalTime.parse("22:55:04.905120"); p.execute(Tuple.tuple() .addLocalTime(lt) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Time") .returns(Tuple::getValue, Row::getValue, lt) .returns(Tuple::getLocalTime, Row::getLocalTime, lt) .returns(Tuple::getTemporal, Row::getTemporal, lt) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeTimeTz(TestContext ctx) { testDecodeDataTimeGeneric(ctx, "TIME WITH TIME ZONE", "TimeTz", Tuple::getOffsetTime, Row::getOffsetTime, OffsetTime.parse("17:55:04.905120+03:07")); } @Test public void testEncodeTimeTz(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"TemporalDataType\" SET \"TimeTz\" = $1 WHERE \"id\" = $2 RETURNING \"TimeTz\"", ctx.asyncAssertSuccess(p -> { OffsetTime ot = OffsetTime.parse("20:55:04.905120+03:07"); p.execute(Tuple.tuple() .addOffsetTime(ot) .addInteger(2), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "TimeTz") .returns(Tuple::getValue, Row::getValue, ot) .returns(Tuple::getOffsetTime, Row::getOffsetTime, ot) .returns(Tuple::getTemporal, Row::getTemporal, ot) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeTimestampBeforePgEpoch(TestContext ctx) { testDecodeDataTimeGeneric(ctx, "TIMESTAMP WITHOUT TIME ZONE", "Timestamp", Tuple::getLocalDateTime, Row::getLocalDateTime, LocalDateTime.parse("1800-01-01T23:57:53.237666")); } @Test public void testEncodeTimestampBeforePgEpoch(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"TemporalDataType\" SET \"Timestamp\" = $1 WHERE \"id\" = $2 RETURNING \"Timestamp\"", ctx.asyncAssertSuccess(p -> { LocalDateTime ldt = LocalDateTime.parse("1900-02-01T23:57:53.237666"); p.execute(Tuple.tuple() .addLocalDateTime(ldt) .addInteger(4), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Timestamp") .returns(Tuple::getValue, Row::getValue, ldt) .returns(Tuple::getLocalDateTime, Row::getLocalDateTime, ldt) .returns(Tuple::getTemporal, Row::getTemporal, ldt) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeTimestampAfterPgEpoch(TestContext ctx) { testDecodeDataTimeGeneric(ctx, "TIMESTAMP WITHOUT TIME ZONE", "Timestamp", Tuple::getLocalDateTime, Row::getLocalDateTime, ldt); } @Test public void testEncodeTimestampAfterPgEpoch(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"TemporalDataType\" SET \"Timestamp\" =$1 WHERE \"id\" = $2 RETURNING \"Timestamp\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addLocalDateTime(LocalDateTime.parse("2017-05-14T19:35:58.237666")) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); LocalDateTime ldt = LocalDateTime.parse("2017-05-14T19:35:58.237666"); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Timestamp") .returns(Tuple::getValue, Row::getValue, ldt) .returns(Tuple::getLocalDateTime, Row::getLocalDateTime, ldt) .returns(Tuple::getTemporal, Row::getTemporal, ldt) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeTimestampTzBeforePgEpoch(TestContext ctx) { testDecodeDataTimeGeneric(ctx, "TIMESTAMP WITH TIME ZONE", "TimestampTz", Tuple::getOffsetDateTime, Row::getOffsetDateTime, OffsetDateTime.parse("1800-01-02T02:59:59.237666Z")); } @Test public void testEncodeTimestampTzBeforePgEpoch(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.query("SET TIME ZONE 'UTC'", ctx.asyncAssertSuccess(v -> { conn.prepare("UPDATE \"TemporalDataType\" SET \"TimestampTz\" =$1 WHERE \"id\" = $2 RETURNING \"TimestampTz\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addOffsetDateTime(OffsetDateTime.parse("1800-02-01T23:59:59.237666-03:00")) .addInteger(3) , ctx.asyncAssertSuccess(result -> { OffsetDateTime odt = OffsetDateTime.parse("1800-02-02T02:59:59.237666Z"); ctx.assertEquals(1, result.rowCount()); ctx.assertEquals(1, result.size()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "TimestampTz") .returns(Tuple::getValue, Row::getValue, odt) .returns(Tuple::getOffsetDateTime, Row::getOffsetDateTime, odt) .returns(Tuple::getTemporal, Row::getTemporal, odt) .forRow(row); async.complete(); })); })); })); })); } @Test public void testDecodeTimestampTzAfterPgEpoch(TestContext ctx) { testDecodeDataTimeGeneric(ctx, "TIMESTAMP WITH TIME ZONE", "TimestampTz", Tuple::getOffsetDateTime, Row::getOffsetDateTime, OffsetDateTime.parse("2017-05-15T02:59:59.237666Z")); } @Test public void testEncodeTimestampTzAfterPgEpoch(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.query("SET TIME ZONE 'UTC'", ctx.asyncAssertSuccess(v -> { conn.prepare("UPDATE \"TemporalDataType\" SET \"TimestampTz\" = $1 WHERE \"id\" = $2 RETURNING \"TimestampTz\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addOffsetDateTime(OffsetDateTime.parse("2017-06-14T23:59:59.237666-03:00")) .addInteger(1) , ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); OffsetDateTime odt = OffsetDateTime.parse("2017-06-15T02:59:59.237666Z"); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "TimestampTz") .returns(Tuple::getValue, Row::getValue, odt) .returns(Tuple::getOffsetDateTime, Row::getOffsetDateTime, odt) .returns(Tuple::getTemporal, Row::getTemporal, odt) .forRow(row); async.complete(); })); })); })); })); } @Test public void testDecodeInterval(TestContext ctx) { Interval interval = Interval.of() .years(10) .months(3) .days(332) .hours(20) .minutes(20) .seconds(20) .microseconds(999999); Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT $1 :: INTERVAL \"Interval\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addInterval(interval), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Interval") .returns(Tuple::getValue, Row::getValue, interval) .returns(Tuple::getInterval, Row::getInterval, interval) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeInterval(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"TemporalDataType\" SET \"Interval\" = $1 WHERE \"id\" = $2 RETURNING \"Interval\"", ctx.asyncAssertSuccess(p -> { // 2000 years 1 months 403 days 59 hours 35 minutes 13.999998 seconds Interval expected = Interval.of() .years(2000) .months(1) .days(403) .hours(59) .minutes(35) .seconds(13) .microseconds(999998); p.execute(Tuple.tuple() .addInterval(expected) .addInteger(2), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Interval") .returns(Tuple::getValue, Row::getValue, expected) .returns(Tuple::getInterval, Row::getInterval, expected) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeLocalDateArray(TestContext ctx) { testGeneric(ctx, "SELECT $1 :: DATE [] \"LocalDate\"", new LocalDate[][]{new LocalDate[]{LocalDate.parse("1998-05-11"), LocalDate.parse("1998-05-11")}}, Row::getLocalDateArray); } @Test public void testEncodeLocalDateArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"LocalDate\" = $1 WHERE \"id\" = $2 RETURNING \"LocalDate\"", ctx.asyncAssertSuccess(p -> { final LocalDate dt = LocalDate.parse("1998-05-12"); p.execute(Tuple.tuple() .addLocalDateArray(new LocalDate[]{dt}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "LocalDate") .returns(Tuple::getValue, Row::getValue, new LocalDate[]{dt}) .returns(Tuple::getLocalDateArray, Row::getLocalDateArray, new LocalDate[]{dt}) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testDecodeLocalTimeArray(TestContext ctx) { testGeneric(ctx, "SELECT $1 :: TIME WITHOUT TIME ZONE [] \"LocalTime\"", new LocalTime[][]{new LocalTime[]{lt}}, Row::getLocalTimeArray); } @Test public void testEncodeLocalTimeArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"LocalTime\" = $1 WHERE \"id\" = $2 RETURNING \"LocalTime\"", ctx.asyncAssertSuccess(p -> { final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss.SSSSS"); final LocalTime dt = LocalTime.parse("17:55:04.90512", dtf); p.execute(Tuple.tuple() .addLocalTimeArray(new LocalTime[]{dt}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "LocalTime") .returns(Tuple::getValue, Row::getValue, new LocalTime[]{dt}) .returns(Tuple::getLocalTimeArray, Row::getLocalTimeArray, new LocalTime[]{dt}) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testDecodeOffsetTimeArray(TestContext ctx) { testGeneric(ctx, "SELECT $1 :: TIME WITH TIME ZONE [] \"OffsetTime\"", new OffsetTime[][]{new OffsetTime[]{dt}}, Row::getOffsetTimeArray); } @Test public void testEncodeOffsetTimeArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"OffsetTime\" = $1 WHERE \"id\" = $2 RETURNING \"OffsetTime\"", ctx.asyncAssertSuccess(p -> { final OffsetTime dt = OffsetTime.parse("17:56:04.90512+03:07"); p.execute(Tuple.tuple() .addOffsetTimeArray(new OffsetTime[]{dt}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "OffsetTime") .returns(Tuple::getValue, Row::getValue, new OffsetTime[]{dt}) .returns(Tuple::getOffsetTimeArray, Row::getOffsetTimeArray, new OffsetTime[]{dt}) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testDecodeLocalDateTimeArray(TestContext ctx) { testGeneric(ctx, "SELECT $1 :: TIMESTAMP WITHOUT TIME ZONE [] \"LocalDateTime\"", new LocalDateTime[][]{new LocalDateTime[]{LocalDateTime.parse("2017-05-14T19:35:58.237666")}}, Row::getLocalDateTimeArray); } @Test public void testEncodeLocalDateTimeArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"LocalDateTime\" = $1 WHERE \"id\" = $2 RETURNING \"LocalDateTime\"", ctx.asyncAssertSuccess(p -> { final LocalDateTime dt = LocalDateTime.parse("2017-05-14T19:35:58.237666"); p.execute(Tuple.tuple() .addLocalDateTimeArray(new LocalDateTime[]{dt}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "LocalDateTime") .returns(Tuple::getValue, Row::getValue, new LocalDateTime[]{dt}) .returns(Tuple::getLocalDateTimeArray, Row::getLocalDateTimeArray, new LocalDateTime[]{dt}) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testDecodeOffsetDateTimeArray(TestContext ctx) { testGeneric(ctx, "SELECT $1 :: TIMESTAMP WITH TIME ZONE [] \"OffsetDateTime\"", new OffsetDateTime[][]{new OffsetDateTime[]{odt}}, Row::getOffsetDateTimeArray); } @Test public void testEncodeOffsetDateTimeArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"OffsetDateTime\" = $1 WHERE \"id\" = $2 RETURNING \"OffsetDateTime\"", ctx.asyncAssertSuccess(p -> { final OffsetDateTime dt = OffsetDateTime.parse("2017-05-14T19:35:58.237666Z"); p.execute(Tuple.tuple() .addOffsetDateTimeArray(new OffsetDateTime[]{dt}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "OffsetDateTime") .returns(Tuple::getValue, Row::getValue, new OffsetDateTime[]{dt}) .returns(Tuple::getOffsetDateTimeArray, Row::getOffsetDateTimeArray, new OffsetDateTime[]{dt}) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testDecodeIntervalArray(TestContext ctx) { testGeneric(ctx, "SELECT $1 :: INTERVAL [] \"Interval\"", new Interval[][]{intervals}, Row::getIntervalArray); } @Test public void testEncodeIntervalArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Interval\" = $1 WHERE \"id\" = $2 RETURNING \"Interval\"", ctx.asyncAssertSuccess(p -> { Interval[] intervals = new Interval[]{ Interval.of().years(10).months(3).days(332).hours(20).minutes(20).seconds(20).microseconds(999991), Interval.of().minutes(20).seconds(20).microseconds(123456), Interval.of().years(-2).months(-6), Interval.of() }; p.execute(Tuple.tuple() .addIntervalArray(intervals) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Interval") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(intervals)) .returns(Tuple::getIntervalArray, Row::getIntervalArray, ColumnChecker.toObjectArray(intervals)) .forRow(result.iterator().next()); async.complete(); })); })); })); } private void testDecodeDataTimeGeneric(TestContext ctx, String dataType, String columnName, ColumnChecker.SerializableBiFunction byIndexGetter, ColumnChecker.SerializableBiFunction byNameGetter, T expected) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT $1 :: " + dataType + " \"" + columnName + "\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addValue(expected), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, columnName) .returns(Tuple::getValue, Row::getValue, expected) .returns(byIndexGetter, byNameGetter, expected) .returns(Tuple::getTemporal, Row::getTemporal, expected) .forRow(row); async.complete(); })); })); })); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/DateTimeTypesSimpleCodecTest.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.PgClient; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.Tuple; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import org.junit.Test; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.OffsetDateTime; import java.time.OffsetTime; public class DateTimeTypesSimpleCodecTest extends SimpleQueryDataTypeCodecTestBase { @Test public void testDate(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn .query("SELECT '1981-05-30'::DATE \"LocalDate\"", ctx.asyncAssertSuccess(result -> { LocalDate ld = LocalDate.parse("1981-05-30"); ctx.assertEquals(1, result.size()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "LocalDate") .returns(Tuple::getValue, Row::getValue, ld) .returns(Tuple::getLocalDate, Row::getLocalDate, ld) .returns(Tuple::getTemporal, Row::getTemporal, ld) .forRow(row); async.complete(); })); })); } @Test public void testTime(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn .query("SELECT '17:55:04.905120'::TIME \"LocalTime\"", ctx.asyncAssertSuccess(result -> { LocalTime lt = LocalTime.parse("17:55:04.905120"); ctx.assertEquals(1, result.size()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "LocalTime") .returns(Tuple::getValue, Row::getValue, lt) .returns(Tuple::getLocalTime, Row::getLocalTime, lt) .returns(Tuple::getTemporal, Row::getTemporal, lt) .forRow(row); async.complete(); })); })); } @Test public void testTimeTz(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn .query("SELECT '17:55:04.90512+03:07'::TIMETZ \"OffsetTime\"", ctx.asyncAssertSuccess(result -> { OffsetTime ot = OffsetTime.parse("17:55:04.905120+03:07"); ctx.assertEquals(1, result.size()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "OffsetTime") .returns(Tuple::getOffsetTime, Row::getOffsetTime, ot) .returns(Tuple::getTemporal, Row::getTemporal, ot) .returns(Tuple::getValue, Row::getValue, ot) .forRow(row); async.complete(); })); })); } @Test public void testTimestamp(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn .query("SELECT '2017-05-14 19:35:58.237666'::TIMESTAMP \"LocalDateTime\"", ctx.asyncAssertSuccess(result -> { LocalDateTime ldt = LocalDateTime.parse("2017-05-14T19:35:58.237666"); ctx.assertEquals(1, result.size()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "LocalDateTime") .returns(Tuple::getValue, Row::getValue, ldt) .returns(Tuple::getLocalDateTime, Row::getLocalDateTime, ldt) .returns(Tuple::getTemporal, Row::getTemporal, ldt) .forRow(row); async.complete(); })); })); } @Test public void testTimestampTz(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.query("SET TIME ZONE 'UTC'", ctx.asyncAssertSuccess(v -> { conn.query("SELECT '2017-05-14 22:35:58.237666-03'::TIMESTAMPTZ \"OffsetDateTime\"", ctx.asyncAssertSuccess(result -> { OffsetDateTime odt = OffsetDateTime.parse("2017-05-15T01:35:58.237666Z"); ctx.assertEquals(1, result.size()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "OffsetDateTime") .returns(Tuple::getValue, Row::getValue, odt) .returns(Tuple::getOffsetDateTime, Row::getOffsetDateTime, odt) .returns(Tuple::getTemporal, Row::getTemporal, odt) .forRow(row); async.complete(); })); })); })); } @Test public void testInterval(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.query("SELECT '10 years 3 months 332 days 20 hours 20 minutes 20.999991 seconds'::INTERVAL \"Interval\"", ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); Row row = result.iterator().next(); Interval interval = Interval.of() .years(10) .months(3) .days(332) .hours(20) .minutes(20) .seconds(20) .microseconds(999991); ColumnChecker.checkColumn(0, "Interval") .returns(Tuple::getValue, Row::getValue, interval) .returns(Tuple::getInterval, Row::getInterval, interval) .forRow(row); async.complete(); })); })); } @Test public void testDecodeDATEArray(TestContext ctx) { testDecodeGenericArray(ctx, "ARRAY ['1998-05-11' :: DATE, '1998-05-11' :: DATE]", "LocalDate", Tuple::getLocalDateArray, Row::getLocalDateArray, LocalDate.parse("1998-05-11"), LocalDate.parse("1998-05-11")); } @Test public void testDecodeTIMEArray(TestContext ctx) { testDecodeGenericArray(ctx, "ARRAY ['17:55:04.90512' :: TIME WITHOUT TIME ZONE]", "LocalTime", Tuple::getLocalTimeArray, Row::getLocalTimeArray, lt); } @Test public void testDecodeTIMETZArray(TestContext ctx) { testDecodeGenericArray(ctx, "ARRAY ['17:55:04.90512+03' :: TIME WITH TIME ZONE]", "OffsetTime", Tuple::getOffsetTimeArray, Row::getOffsetTimeArray, dt); } @Test public void testDecodeTIMESTAMPArray(TestContext ctx) { testDecodeGenericArray(ctx, "ARRAY ['2017-05-14 19:35:58.237666' :: TIMESTAMP WITHOUT TIME ZONE]", "LocalDateTime", Tuple::getLocalDateTimeArray, Row::getLocalDateTimeArray, ldt); } @Test public void testDecodeTIMESTAMPTZArray(TestContext ctx) { testDecodeGenericArray(ctx, "ARRAY ['2017-05-14 23:59:59.237666-03' :: TIMESTAMP WITH TIME ZONE]", "OffsetDateTime", Tuple::getOffsetDateTimeArray, Row::getOffsetDateTimeArray, odt); } @Test public void testDecodeINTERVALArray(TestContext ctx) { testDecodeGenericArray(ctx, "ARRAY ['10 years 3 months 332 days 20 hours 20 minutes 20.999991 seconds'::INTERVAL, '20 minutes 20.123456 seconds'::INTERVAL, '30 months ago'::INTERVAL]", "Interval", Tuple::getIntervalArray, Row::getIntervalArray, intervals); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/EnumeratedTypesExtendedCodecTest.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.PgClient; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.Tuple; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import org.junit.Test; public class EnumeratedTypesExtendedCodecTest extends ExtendedQueryDataTypeCodecTestBase { @Test public void testDecodeEnum(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"currentMood\" FROM \"EnumDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "currentMood") .returns(Tuple::getValue, Row::getValue, "ok") .returns(Tuple::getString, Row::getString, "ok") .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeEnum(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"EnumDataType\" SET \"currentMood\" = $1 WHERE \"id\" = $2 RETURNING \"currentMood\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addString("happy") .addInteger(2) , ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "currentMood") .returns(Tuple::getValue, Row::getValue, "happy") .returns(Tuple::getString, Row::getString, "happy") .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeEnumArray(TestContext ctx) { final String[] expected = new String[]{"ok", "unhappy", "happy"}; Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Enum\" FROM \"ArrayDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Enum") .returns(Tuple::getValue, Row::getValue, expected) .returns(Tuple::getStringArray, Row::getStringArray, expected) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeEnumArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Enum\" = $1 WHERE \"id\" = $2 RETURNING \"Enum\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addStringArray(new String[]{"unhappy"}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Enum") .returns(Tuple::getValue, Row::getValue, new String[]{"unhappy"}) .returns(Tuple::getStringArray, Row::getStringArray, new String[]{"unhappy"}) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeEnumArrayMultipleValues(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Enum\" = $1 WHERE \"id\" = $2 RETURNING \"Enum\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addStringArray(new String[]{"unhappy", "ok"}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Enum") .returns(Tuple::getValue, Row::getValue, new String[]{"unhappy", "ok"}) .returns(Tuple::getStringArray, Row::getStringArray, new String[]{"unhappy", "ok"}) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeEnumArrayEmptyValues(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Enum\" = $1 WHERE \"id\" = $2 RETURNING \"Enum\", \"Boolean\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addStringArray(new String[]{}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Enum") .returns(Tuple::getValue, Row::getValue, new String[]{}) .returns(Tuple::getStringArray, Row::getStringArray, new String[]{}) .forRow(result.iterator().next()); ColumnChecker.checkColumn(1, "Boolean") .returns(Tuple::getValue, Row::getValue, new Boolean[]{true}) .returns(Tuple::getBooleanArray, Row::getBooleanArray, new Boolean[]{true}) .forRow(result.iterator().next()); async.complete(); })); })); })); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/EnumeratedTypesSimpleCodecTest.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.PgClient; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.Tuple; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import org.junit.Test; public class EnumeratedTypesSimpleCodecTest extends SimpleQueryDataTypeCodecTestBase { @Test public void testEnum(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn .query("SELECT \"currentMood\" FROM \"EnumDataType\" WHERE \"id\" = 5", ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "currentMood") .returns(Tuple::getValue, Row::getValue, "ok") .returns(Tuple::getString, Row::getString, "ok") .forRow(row); async.complete(); })); })); } @Test public void testDecodeENUMArray(TestContext ctx) { String [] moods = new String [] {"ok", "unhappy", "happy"}; testDecodeXXXArray(ctx, "Enum", "ArrayDataType", Tuple::getStringArray, Row::getStringArray, moods); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/ExtendedQueryDataTypeCodecTestBase.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.PgClient; import io.reactiverse.pgclient.PgConnectOptions; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.Tuple; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.function.BiFunction; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author Emad Alblueshi */ public abstract class ExtendedQueryDataTypeCodecTestBase extends DataTypeTestBase { private static void compare(TestContext ctx, T expected, T actual) { if (expected != null && expected.getClass().isArray()) { ctx.assertNotNull(actual); ctx.assertTrue(actual.getClass().isArray()); List expectedList = Arrays.asList((Object[]) expected); List actualList = Arrays.asList((Object[]) actual); ctx.assertEquals(expectedList, actualList); } else { ctx.assertEquals(expected, actual); } } @Override protected PgConnectOptions options() { return new PgConnectOptions(options).setCachePreparedStatements(false); } protected void testGeneric(TestContext ctx, String sql, T[] expected, BiFunction getter) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { List batch = Stream.of(expected).map(Tuple::of).collect(Collectors.toList()); conn.preparedBatch(sql, batch, ctx.asyncAssertSuccess(result -> { for (T n : expected) { ctx.assertEquals(result.size(), 1); Iterator it = result.iterator(); Row row = it.next(); compare(ctx, n, getter.apply(row, 0)); compare(ctx, n, row.getValue(0)); result = result.next(); } ctx.assertNull(result); async.complete(); })); })); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/GeometricTypesExtendedCodecTest.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.PgClient; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.Tuple; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import org.junit.Test; import java.util.Arrays; public class GeometricTypesExtendedCodecTest extends ExtendedQueryDataTypeCodecTestBase { @Test public void testDecodePoint(TestContext ctx) { testGeneric(ctx, "SELECT $1 :: POINT \"Point\"", new Point[]{new Point(1.0, 2.0)}, Row::getPoint); } @Test public void testDecodeLine(TestContext ctx) { testGeneric(ctx, "SELECT $1 :: LINE \"Line\"", new Line[]{new Line(1.0, 2.0, 3.0)}, Row::getLine); } @Test public void testDecodeLineSegment(TestContext ctx) { testGeneric(ctx, "SELECT $1 :: LSEG \"Lseg\"", new LineSegment[]{new LineSegment(new Point(1.0, 1.0), new Point(2.0, 2.0))}, Row::getLineSegment); } @Test public void testDecodeBox(TestContext ctx) { testGeneric(ctx, "SELECT $1 :: BOX \"Box\"", new Box[]{new Box(new Point(2.0, 2.0), new Point(1.0, 1.0))}, Row::getBox); } @Test public void testDecodeClosedPath(TestContext ctx) { testGeneric(ctx, "SELECT $1 :: PATH \"ClosedPath\"", new Path[]{new Path(false, Arrays.asList(new Point(1.0, 1.0), new Point(2.0, 1.0), new Point(2.0, 2.0), new Point(2.0, 1.0)))}, Row::getPath); } @Test public void testDecodeOpenPath(TestContext ctx) { testGeneric(ctx, "SELECT $1 :: PATH \"OpenPath\"", new Path[]{new Path(true, Arrays.asList(new Point(1.0, 1.0), new Point(2.0, 1.0), new Point(2.0, 2.0), new Point(2.0, 1.0)))}, Row::getPath); } @Test public void testDecodePolygon(TestContext ctx) { testGeneric(ctx, "SELECT $1 :: POLYGON \"Polygon\"", new Polygon[]{new Polygon(Arrays.asList(new Point(1.0, 1.0), new Point(2.0, 2.0), new Point(3.0, 1.0)))}, Row::getPolygon); } @Test public void testDecodeCircle(TestContext ctx) { testGeneric(ctx, "SELECT $1 :: CIRCLE \"Circle\"", new Circle[]{new Circle(new Point(1.0, 1.0), 1.0)}, Row::getCircle); } @Test public void testDecodePointArray(TestContext ctx) { Point[] points = {new Point(1.0, 1.0), new Point(2.0, 2.0)}; testGeneric(ctx, "SELECT $1 :: POINT[] \"PointArray\"", new Point[][]{points}, Row::getPointArray); } @Test public void testDecodeLineArray(TestContext ctx) { Line[] lines = {new Line(1.0, 2.0, 3.0), new Line(2.0, 3.0, 4.0)}; testGeneric(ctx, "SELECT $1 :: LINE[] \"LineArray\"", new Line[][]{lines}, Row::getLineArray); } @Test public void testDecodeLineSegmentArray(TestContext ctx) { LineSegment[] lineSegments = {new LineSegment(new Point(1.0, 1.0), new Point(2.0, 2.0)), new LineSegment(new Point(2.0, 2.0), new Point(3.0, 3.0))}; testGeneric(ctx, "SELECT $1 :: LSEG[] \"LsegArray\"", new LineSegment[][]{lineSegments}, Row::getLineSegmentArray); } @Test public void testDecodeBoxArray(TestContext ctx) { Box[] boxes = {new Box(new Point(2.0, 2.0), new Point(1.0, 1.0)), new Box(new Point(3.0, 3.0), new Point(2.0, 2.0))}; testGeneric(ctx, "SELECT $1 :: BOX[] \"BoxArray\"", new Box[][]{boxes}, Row::getBoxArray); } @Test public void testDecodeClosedPathArray(TestContext ctx) { Path[] closedPaths = {new Path(false, Arrays.asList(new Point(1.0, 1.0), new Point(2.0, 1.0), new Point(2.0, 2.0), new Point(2.0, 1.0))), new Path(false, Arrays.asList(new Point(2.0, 2.0), new Point(3.0, 2.0), new Point(3.0, 3.0), new Point(3.0, 2.0)))}; testGeneric(ctx, "SELECT $1 :: PATH[] \"ClosedPathArray\"", new Path[][]{closedPaths}, Row::getPathArray); } @Test public void testDecodeOpenPathArray(TestContext ctx) { Path[] openPaths = {new Path(true, Arrays.asList(new Point(1.0, 1.0), new Point(2.0, 1.0), new Point(2.0, 2.0), new Point(2.0, 1.0))), new Path(true, Arrays.asList(new Point(2.0, 2.0), new Point(3.0, 2.0), new Point(3.0, 3.0), new Point(3.0, 2.0)))}; testGeneric(ctx, "SELECT $1 :: PATH[] \"OpenPathArray\"", new Path[][]{openPaths}, Row::getPathArray); } @Test public void testDecodePolygonArray(TestContext ctx) { Polygon[] polygons = {new Polygon(Arrays.asList(new Point(1.0, 1.0), new Point(2.0, 2.0), new Point(3.0, 1.0))), new Polygon(Arrays.asList(new Point(0.0, 0.0), new Point(0.0, 1.0), new Point(1.0, 2.0), new Point(2.0, 1.0), new Point(2.0, 0.0)))}; testGeneric(ctx, "SELECT $1 :: POLYGON[] \"PolygonArray\"", new Polygon[][]{polygons}, Row::getPolygonArray); } @Test public void testDecodeCircleArray(TestContext ctx) { Circle[] circles = {new Circle(new Point(1.0, 1.0), 1.0), new Circle(new Point(0.0, 0.0), 2.0)}; testGeneric(ctx, "SELECT $1 :: CIRCLE[] \"CircleArray\"", new Circle[][]{circles}, Row::getCircleArray); } @Test public void testEncodeGeometric(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"" + "GeometricDataType" + "\" SET " + "\"Point\" = $1, " + "\"Line\" = $2, " + "\"Lseg\" = $3, " + "\"Box\" = $4, " + "\"ClosedPath\" = $5, " + "\"OpenPath\" = $6, " + "\"Polygon\" = $7, " + "\"Circle\" = $8 " + "WHERE \"id\" = $9 RETURNING \"Point\", \"Line\", \"Lseg\", \"Box\", \"ClosedPath\", \"OpenPath\", \"Polygon\", \"Circle\"", ctx.asyncAssertSuccess(p -> { Point point = new Point(2.0, 3.0); Line line = new Line(2.0, 3.0, 4.0); LineSegment lineSegment = new LineSegment(new Point(2.0, 2.0), new Point(3.0, 3.0)); Box box = new Box(new Point(3.0, 3.0), new Point(2.0, 2.0)); Path OpenPath = new Path(true, Arrays.asList(new Point(1.0, 1.0), new Point(2.0, 1.0), new Point(2.0, 2.0), new Point(2.0, 1.0))); Path closedPath = new Path(false, Arrays.asList(new Point(1.0, 1.0), new Point(2.0, 1.0), new Point(2.0, 2.0), new Point(2.0, 1.0))); Polygon polygon = new Polygon(Arrays.asList(new Point(2.0, 2.0), new Point(3.0, 3.0), new Point(4.0, 2.0))); Circle circle = new Circle(new Point(1.0, 1.0), 3.0); int id = 2; p.execute(Tuple.tuple() .addPoint(point) .addLine(line) .addLineSegment(lineSegment) .addBox(box) .addPath(OpenPath) .addPath(closedPath) .addPolygon(polygon) .addCircle(circle) .addInteger(id), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Point") .returns(Tuple::getValue, Row::getValue, point) .returns(Tuple::getPoint, Row::getPoint, point) .forRow(row); ColumnChecker.checkColumn(1, "Line") .returns(Tuple::getValue, Row::getValue, line) .returns(Tuple::getLine, Row::getLine, line) .forRow(row); ColumnChecker.checkColumn(2, "Lseg") .returns(Tuple::getValue, Row::getValue, lineSegment) .returns(Tuple::getLineSegment, Row::getLineSegment, lineSegment) .forRow(row); ColumnChecker.checkColumn(3, "Box") .returns(Tuple::getValue, Row::getValue, box) .returns(Tuple::getBox, Row::getBox, box) .forRow(row); ColumnChecker.checkColumn(4, "ClosedPath") .returns(Tuple::getValue, Row::getValue, OpenPath) .returns(Tuple::getPath, Row::getPath, OpenPath) .forRow(row); ColumnChecker.checkColumn(5, "OpenPath") .returns(Tuple::getValue, Row::getValue, closedPath) .returns(Tuple::getPath, Row::getPath, closedPath) .forRow(row); ColumnChecker.checkColumn(6, "Polygon") .returns(Tuple::getValue, Row::getValue, polygon) .returns(Tuple::getPolygon, Row::getPolygon, polygon) .forRow(row); ColumnChecker.checkColumn(7, "Circle") .returns(Tuple::getValue, Row::getValue, circle) .returns(Tuple::getCircle, Row::getCircle, circle) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeGeometricArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"" + "ArrayDataType" + "\" SET " + "\"Point\" = $1, " + "\"Line\" = $2, " + "\"Lseg\" = $3, " + "\"Box\" = $4, " + "\"ClosedPath\" = $5, " + "\"OpenPath\" = $6, " + "\"Polygon\" = $7, " + "\"Circle\" = $8 " + "WHERE \"id\" = $9 RETURNING \"Point\", \"Line\", \"Lseg\", \"Box\", \"ClosedPath\", \"OpenPath\", \"Polygon\", \"Circle\"", ctx.asyncAssertSuccess(p -> { Point[] points = {new Point(2.0, 2.0), new Point(1.0, 1.0)}; Line[] lines = {new Line(3.0, 2.0, 1.0), new Line(2.0, 3.0, 4.0)}; LineSegment[] lineSegments = {new LineSegment(new Point(1.0, 1.0), new Point(-3.0, -2.0)), new LineSegment(new Point(2.0, 2.0), new Point(3.0, 3.0))}; Box[] boxes = {new Box(new Point(2.0, 2.0), new Point(1.0, 1.0)), new Box(new Point(4.0, 4.0), new Point(2.0, 2.0))}; Path[] openPaths = {new Path(true, Arrays.asList(new Point(1.0, 1.0), new Point(2.0, 1.0), new Point(2.0, 2.0), new Point(2.0, 1.0))), new Path(false, Arrays.asList(new Point(2.0, 2.0), new Point(3.0, 2.0), new Point(3.0, 3.0), new Point(3.0, 2.0)))}; Path[] closedPaths = {new Path(false, Arrays.asList(new Point(1.0, 1.0), new Point(2.0, 1.0), new Point(2.0, 2.0), new Point(2.0, 1.0))), new Path(false, Arrays.asList(new Point(2.0, 2.0), new Point(3.0, 2.0), new Point(3.0, 3.0), new Point(3.0, 2.0)))}; Polygon[] polygons = {new Polygon(Arrays.asList(new Point(0.0, 0.0), new Point(2.0, 2.0), new Point(3.0, 1.0))), new Polygon(Arrays.asList(new Point(0.0, 0.0), new Point(0.0, 1.0), new Point(1.0, 2.0), new Point(2.0, 1.0), new Point(2.0, 0.0)))}; Circle[] circles = {new Circle(new Point(1.0, 1.0), 3.0), new Circle(new Point(2.0, 2.0), 2.0)}; int id = 2; p.execute(Tuple.tuple() .addPointArray(points) .addLineArray(lines) .addLineSegmentArray(lineSegments) .addBoxArray(boxes) .addPathArray(openPaths) .addPathArray(closedPaths) .addPolygonArray(polygons) .addCircleArray(circles) .addInteger(id), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Point") .returns(Tuple::getValue, Row::getValue, points) .returns(Tuple::getPointArray, Row::getPointArray, points) .forRow(row); ColumnChecker.checkColumn(1, "Line") .returns(Tuple::getValue, Row::getValue, lines) .returns(Tuple::getLineArray, Row::getLineArray, lines) .forRow(row); ColumnChecker.checkColumn(2, "Lseg") .returns(Tuple::getValue, Row::getValue, lineSegments) .returns(Tuple::getLineSegmentArray, Row::getLineSegmentArray, lineSegments) .forRow(row); ColumnChecker.checkColumn(3, "Box") .returns(Tuple::getValue, Row::getValue, boxes) .returns(Tuple::getBoxArray, Row::getBoxArray, boxes) .forRow(row); ColumnChecker.checkColumn(4, "ClosedPath") .returns(Tuple::getValue, Row::getValue, openPaths) .returns(Tuple::getPathArray, Row::getPathArray, openPaths) .forRow(row); ColumnChecker.checkColumn(5, "OpenPath") .returns(Tuple::getValue, Row::getValue, closedPaths) .returns(Tuple::getPathArray, Row::getPathArray, closedPaths) .forRow(row); ColumnChecker.checkColumn(6, "Polygon") .returns(Tuple::getValue, Row::getValue, polygons) .returns(Tuple::getPolygonArray, Row::getPolygonArray, polygons) .forRow(row); ColumnChecker.checkColumn(7, "Circle") .returns(Tuple::getValue, Row::getValue, circles) .returns(Tuple::getCircleArray, Row::getCircleArray, circles) .forRow(row); async.complete(); })); })); })); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/GeometricTypesSimpleCodecTest.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.Tuple; import io.vertx.ext.unit.TestContext; import org.junit.Test; import java.util.Arrays; public class GeometricTypesSimpleCodecTest extends SimpleQueryDataTypeCodecTestBase { @Test public void testPoint(TestContext ctx) { Point expected = new Point(1.0, 2.0); testDecodeGeneric(ctx, "(1.0,2.0)", "POINT", "Point", Tuple::getPoint, Row::getPoint, expected); } @Test public void testLine(TestContext ctx) { Line expected = new Line(1.0, 2.0, 3.0); testDecodeGeneric(ctx, "{1.0,2.0,3.0}", "LINE", "Line", Tuple::getLine, Row::getLine, expected); } @Test public void testLineSegment(TestContext ctx) { LineSegment expected = new LineSegment(new Point(1.0, 1.0), new Point(2.0, 2.0)); testDecodeGeneric(ctx, "((1.0,1.0),(2.0,2.0))", "LSEG", "Lseg", Tuple::getLineSegment, Row::getLineSegment, expected); } @Test public void testBox(TestContext ctx) { Box expected = new Box(new Point(2.0, 2.0), new Point(1.0, 1.0)); testDecodeGeneric(ctx, "((2.0,2.0),(1.0,1.0))", "BOX", "Box", Tuple::getBox, Row::getBox, expected); } @Test public void testClosedPath(TestContext ctx) { Path expected = new Path(false, Arrays.asList(new Point(1.0, 1.0), new Point(2.0, 1.0), new Point(2.0, 2.0), new Point(2.0, 1.0))); testDecodeGeneric(ctx, "((1.0,1.0),(2.0,1.0),(2.0,2.0),(2.0,1.0))", "PATH", "ClosedPath", Tuple::getPath, Row::getPath, expected); } @Test public void testOpenPath(TestContext ctx) { Path expected = new Path(true, Arrays.asList(new Point(1.0, 1.0), new Point(2.0, 1.0), new Point(2.0, 2.0), new Point(2.0, 1.0))); testDecodeGeneric(ctx, "[(1.0,1.0),(2.0,1.0),(2.0,2.0),(2.0,1.0)]", "PATH", "OpenPath", Tuple::getPath, Row::getPath, expected); } @Test public void testPolygon(TestContext ctx) { Polygon expected = new Polygon(Arrays.asList(new Point(1.0, 1.0), new Point(2.0, 2.0), new Point(3.0, 1.0))); testDecodeGeneric(ctx, "((1.0,1.0),(2.0,2.0),(3.0,1.0))", "POLYGON", "Polygon", Tuple::getPolygon, Row::getPolygon, expected); } @Test public void testCircle(TestContext ctx) { Circle expected = new Circle(new Point(1.0, 1.0), 1.0); testDecodeGeneric(ctx, "<(1.0,1.0),1.0>", "CIRCLE", "Circle", Tuple::getCircle, Row::getCircle, expected); } @Test public void testPointArray(TestContext ctx) { Point[] expected = {new Point(1.0, 1.0), new Point(2.0, 2.0)}; testDecodeGenericArray(ctx, "ARRAY ['(1.0,1.0)':: POINT, '(2.0,2.0)' :: POINT]", "Point", Tuple::getPointArray, Row::getPointArray, expected); } @Test public void testLineArray(TestContext ctx) { Line[] expected = {new Line(1.0, 2.0, 3.0), new Line(2.0, 3.0, 4.0)}; testDecodeGenericArray(ctx, "ARRAY ['{1.0,2.0,3.0}':: LINE, '{2.0,3.0,4.0}':: LINE]", "Line", Tuple::getLineArray, Row::getLineArray, expected); } @Test public void testLineSegmentArray(TestContext ctx) { LineSegment[] expected = {new LineSegment(new Point(1.0, 1.0), new Point(2.0, 2.0)), new LineSegment(new Point(2.0, 2.0), new Point(3.0, 3.0))}; testDecodeGenericArray(ctx, "ARRAY ['((1.0,1.0),(2.0,2.0))':: LSEG, '((2.0,2.0),(3.0,3.0))':: LSEG]", "Lseg", Tuple::getLineSegmentArray, Row::getLineSegmentArray, expected); } @Test public void testBoxArray(TestContext ctx) { Box[] expected = {new Box(new Point(2.0, 2.0), new Point(1.0, 1.0)), new Box(new Point(3.0, 3.0), new Point(2.0, 2.0))}; testDecodeGenericArray(ctx, "ARRAY ['((2.0,2.0),(1.0,1.0))':: BOX, '((3.0,3.0),(2.0,2.0))':: BOX]", "Box", Tuple::getBoxArray, Row::getBoxArray, expected); } @Test public void testClosedPathArray(TestContext ctx) { Path[] expected = {new Path(false, Arrays.asList(new Point(1.0, 1.0), new Point(2.0, 1.0), new Point(2.0, 2.0), new Point(2.0, 1.0))), new Path(false, Arrays.asList(new Point(2.0, 2.0), new Point(3.0, 2.0), new Point(3.0, 3.0), new Point(3.0, 2.0)))}; testDecodeGenericArray(ctx, "ARRAY ['((1.0,1.0),(2.0,1.0),(2.0,2.0),(2.0,1.0))':: PATH, '((2.0,2.0),(3.0,2.0),(3.0,3.0),(3.0,2.0))':: PATH]", "ClosedPath", Tuple::getPathArray, Row::getPathArray, expected); } @Test public void testOpenPathArray(TestContext ctx) { Path[] expected = {new Path(true, Arrays.asList(new Point(1.0, 1.0), new Point(2.0, 1.0), new Point(2.0, 2.0), new Point(2.0, 1.0))), new Path(true, Arrays.asList(new Point(2.0, 2.0), new Point(3.0, 2.0), new Point(3.0, 3.0), new Point(3.0, 2.0)))}; testDecodeGenericArray(ctx, "ARRAY ['[(1.0,1.0),(2.0,1.0),(2.0,2.0),(2.0,1.0)]':: PATH, '[(2.0,2.0),(3.0,2.0),(3.0,3.0),(3.0,2.0)]':: PATH]", "OpenPath", Tuple::getPathArray, Row::getPathArray, expected); } @Test public void testPolygonArray(TestContext ctx) { Polygon[] expected = {new Polygon(Arrays.asList(new Point(1.0, 1.0), new Point(2.0, 2.0), new Point(3.0, 1.0))), new Polygon(Arrays.asList(new Point(0.0, 0.0), new Point(0.0, 1.0), new Point(1.0, 2.0), new Point(2.0, 1.0), new Point(2.0, 0.0)))}; testDecodeGenericArray(ctx, "ARRAY ['((1.0,1.0),(2.0,2.0),(3.0,1.0))':: POLYGON, '((0.0,0.0),(0.0,1.0),(1.0,2.0),(2.0,1.0),(2.0,0.0))':: POLYGON]", "Polygon", Tuple::getPolygonArray, Row::getPolygonArray, expected); } @Test public void testCircleArray(TestContext ctx) { Circle[] expected = {new Circle(new Point(1.0, 1.0), 1.0), new Circle(new Point(0.0, 0.0), 2.0)}; testDecodeGenericArray(ctx, "ARRAY ['<(1.0,1.0),1.0>':: CIRCLE, '<(0.0,0.0),2.0>':: CIRCLE]", "Circle", Tuple::getCircleArray, Row::getCircleArray, expected); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/JsonTypesExtendedCodecTest.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.PgClient; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.Tuple; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import org.junit.Test; public class JsonTypesExtendedCodecTest extends ExtendedQueryDataTypeCodecTestBase { @Test public void testJSON(TestContext ctx) { testJson(ctx, "JSON"); } @Test public void testJSONB(TestContext ctx) { testJson(ctx, "JSONB"); } private void testJson(TestContext ctx, String jsonType) { testGeneric(ctx, "SELECT c FROM (VALUES ($1 :: " + jsonType + ")) AS t (c)", new Json[]{ Json.create(10), Json.create(true), Json.create("hello"), Json.create(new JsonObject().put("foo", "bar")), Json.create(new JsonArray().add(0).add(1).add(2)) }, Tuple::getJson); } @Test public void testJSONArray(TestContext ctx) { testJsonArray(ctx, "JSON"); } @Test public void testJSONBArray(TestContext ctx) { testJsonArray(ctx, "JSONB"); } private void testJsonArray(TestContext ctx, String jsonType) { testGeneric(ctx, "SELECT c FROM (VALUES ($1 :: " + jsonType + "[])) AS t (c)", new Json[][]{ new Json[]{Json.create(10), Json.create(true), Json.create("hello"), Json.create(new JsonObject().put("foo", "bar")), Json.create(new JsonArray().add(0).add(1).add(2))} }, Tuple::getJsonArray); } @Test public void testDecodeJson(TestContext ctx) { testDecodeJson(ctx, "JsonDataType"); } @Test public void testDecodeJsonb(TestContext ctx) { testDecodeJson(ctx, "JsonbDataType"); } private void testDecodeJson(TestContext ctx, String tableName) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"JsonObject\", \"JsonArray\", \"Number\", \"String\", \"BooleanTrue\", \"BooleanFalse\", \"Null\" FROM \"" + tableName + "\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addInteger(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); JsonObject object = new JsonObject("{\"str\":\"blah\", \"int\" : 1, \"float\" : 3.5, \"object\": {}, \"array\" : []}"); JsonArray array = new JsonArray("[1,true,null,9.5,\"Hi\"]"); ColumnChecker.checkColumn(0, "JsonObject") .returns(Tuple::getValue, Row::getValue, Json.create(object)) .returns(Tuple::getJson, Row::getJson, Json.create(object)) .forRow(row); ColumnChecker.checkColumn(1, "JsonArray") .returns(Tuple::getValue, Row::getValue, Json.create(array)) .returns(Tuple::getJson, Row::getJson, Json.create(array)) .forRow(row); ColumnChecker.checkColumn(2, "Number") .returns(Tuple::getValue, Row::getValue, Json.create(4)) .returns(Tuple::getJson, Row::getJson, Json.create(4)) .forRow(row); ColumnChecker.checkColumn(3, "String") .returns(Tuple::getValue, Row::getValue, Json.create("Hello World")) .returns(Tuple::getJson, Row::getJson, Json.create("Hello World")) .forRow(row); ColumnChecker.checkColumn(4, "BooleanTrue") .returns(Tuple::getValue, Row::getValue, Json.create(true)) .returns(Tuple::getJson, Row::getJson, Json.create(true)) .forRow(row); ColumnChecker.checkColumn(5, "BooleanFalse") .returns(Tuple::getValue, Row::getValue, Json.create(false)) .returns(Tuple::getJson, Row::getJson, Json.create(false)) .forRow(row); ColumnChecker.checkColumn(6, "Null") .returns(Tuple::getValue, Row::getValue, Json.create(null)) .returns(Tuple::getJson, Row::getJson, Json.create(null)) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeJson(TestContext ctx) { testEncodeJson(ctx, "JsonDataType"); } @Test public void testEncodeJsonb(TestContext ctx) { testEncodeJson(ctx, "JsonbDataType"); } private void testEncodeJson(TestContext ctx, String tableName) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"" + tableName + "\" SET " + "\"JsonObject\" = $1, " + "\"JsonArray\" = $2, " + "\"Number\" = $3, " + "\"String\" = $4, " + "\"BooleanTrue\" = $5, " + "\"BooleanFalse\" = $6, " + "\"Null\" = $7 " + "WHERE \"id\" = $8 RETURNING \"JsonObject\", \"JsonArray\", \"Number\", \"String\", \"BooleanTrue\", \"BooleanFalse\", \"Null\"", ctx.asyncAssertSuccess(p -> { JsonObject object = new JsonObject("{\"str\":\"blah\", \"int\" : 1, \"float\" : 3.5, \"object\": {}, \"array\" : []}"); JsonArray array = new JsonArray("[1,true,null,9.5,\"Hi\"]"); p.execute(Tuple.tuple() .addJson(Json.create(object)) .addJson(Json.create(array)) .addJson(Json.create(4)) .addJson(Json.create("Hello World")) .addJson(Json.create(true)) .addJson(Json.create(false)) .addJson(Json.create(null)) .addInteger(2), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "JsonObject") .returns(Tuple::getValue, Row::getValue, Json.create(object)) .returns(Tuple::getJson, Row::getJson, Json.create(object)) .forRow(row); ColumnChecker.checkColumn(1, "JsonArray") .returns(Tuple::getValue, Row::getValue, Json.create(array)) .returns(Tuple::getJson, Row::getJson, Json.create(array)) .forRow(row); ColumnChecker.checkColumn(2, "Number") .returns(Tuple::getValue, Row::getValue, Json.create(4)) .returns(Tuple::getJson, Row::getJson, Json.create(4)) .forRow(row); ColumnChecker.checkColumn(3, "String") .returns(Tuple::getValue, Row::getValue, Json.create("Hello World")) .returns(Tuple::getJson, Row::getJson, Json.create("Hello World")) .forRow(row); ColumnChecker.checkColumn(4, "BooleanTrue") .returns(Tuple::getValue, Row::getValue, Json.create(true)) .returns(Tuple::getJson, Row::getJson, Json.create(true)) .forRow(row); ColumnChecker.checkColumn(5, "BooleanFalse") .returns(Tuple::getValue, Row::getValue, Json.create(false)) .returns(Tuple::getJson, Row::getJson, Json.create(false)) .forRow(row); ColumnChecker.checkColumn(6, "Null") .returns(Tuple::getValue, Row::getValue, Json.create(null)) .returns(Tuple::getJson, Row::getJson, Json.create(null)) .forRow(row); async.complete(); })); })); })); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/JsonTypesSimpleCodecTest.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.PgClient; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.Tuple; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import org.junit.Test; public class JsonTypesSimpleCodecTest extends SimpleQueryDataTypeCodecTestBase { @Test public void testJSONB(TestContext ctx) { testJson(ctx, "JSONB"); } @Test public void testJSON(TestContext ctx) { testJson(ctx, "JSON"); } private void testJson(TestContext ctx, String type) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.query("SELECT " + "' {\"str\":\"blah\", \"int\" : 1, \"float\" : 3.5, \"object\": {}, \"array\" : [] }'::" + type + " \"JsonObject\"," + "' [1,true,null,9.5,\"Hi\" ] '::" + type + " \"JsonArray\"," + "' true '::" + type + " \"TrueValue\"," + "' false '::" + type + " \"FalseValue\"," + "' null '::" + type + " \"NullValue\"," + "' 7.502 '::" + type + " \"Number1\"," + "' 8 '::" + type + " \"Number2\"," + "'\" Really Awesome! \"'::" + type + " \"Text\"", ctx.asyncAssertSuccess(result -> { JsonObject object = new JsonObject("{\"str\":\"blah\", \"int\" : 1, \"float\" : 3.5, \"object\": {}, \"array\" : []}"); JsonArray array = new JsonArray("[1,true,null,9.5,\"Hi\"]"); ctx.assertEquals(1, result.size()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "JsonObject") .returns(Tuple::getValue, Row::getValue, Json.create(object)) .forRow(row); ColumnChecker.checkColumn(1, "JsonArray") .returns(Tuple::getValue, Row::getValue, Json.create(array)) .forRow(row); ColumnChecker.checkColumn(2, "TrueValue") .returns(Tuple::getValue, Row::getValue, Json.create(true)) .returns(Tuple::getJson, Row::getJson, Json.create(true)) .forRow(row); ColumnChecker.checkColumn(3, "FalseValue") .returns(Tuple::getValue, Row::getValue, Json.create(false)) .returns(Tuple::getJson, Row::getJson, Json.create(false)) .forRow(row); ColumnChecker.checkColumn(4, "NullValue") .returns(Tuple::getValue, Row::getValue, Json.create(null)) .forRow(row); ColumnChecker.checkColumn(5, "Number1") .returns(Tuple::getValue, Row::getValue, Json.create(7.502d)) .returns(Tuple::getJson, Row::getJson, Json.create(7.502d)) .forRow(row); ColumnChecker.checkColumn(6, "Number2") .returns(Tuple::getValue, Row::getValue, Json.create(8)) .returns(Tuple::getJson, Row::getJson, Json.create(8)) .forRow(row); ColumnChecker.checkColumn(7, "Text") .returns(Tuple::getValue, Row::getValue, Json.create(" Really Awesome! ")) .returns(Tuple::getJson, Row::getJson, Json.create(" Really Awesome! ")) .forRow(row); async.complete(); })); })); } private Object[] expected = {Json.create(new JsonObject("{\"str\":\"blah\",\"int\":1,\"float\":3.5,\"object\":{},\"array\":[]}")), Json.create(new JsonArray("[1,true,null,9.5,\"Hi\"]")), Json.create(4), Json.create("Hello World"), Json.create(true), Json.create(false), Json.create(null)}; @Test public void testDecodeJSONArray(TestContext ctx) { testDecodeGenericArray(ctx, "ARRAY [' {\"str\":\"blah\", \"int\" : 1, \"float\" : 3.5, \"object\": {}, \"array\" : [] }' :: JSON, '[1,true,null,9.5,\"Hi\"]' :: JSON, '4' :: JSON, '\"Hello World\"' :: JSON, 'true' :: JSON, 'false' :: JSON, 'null' :: JSON]", "JSON", Tuple::getJsonArray, Row::getJsonArray, expected); } @Test public void testDecodeJSONBArray(TestContext ctx) { testDecodeGenericArray(ctx, "ARRAY [' {\"str\":\"blah\", \"int\" : 1, \"float\" : 3.5, \"object\": {}, \"array\" : [] }' :: JSON, '[1,true,null,9.5,\"Hi\"]' :: JSON, '4' :: JSON, '\"Hello World\"' :: JSON, 'true' :: JSON, 'false' :: JSON, 'null' :: JSON]", "JSONB", Tuple::getJsonArray, Row::getJsonArray, expected); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/NullSimpleCodecTest.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.PgClient; import io.reactiverse.pgclient.Row; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import org.junit.Test; public class NullSimpleCodecTest extends SimpleQueryDataTypeCodecTestBase { @Test public void testNull(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn .query("SELECT null \"NullValue\"", ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "NullValue").forRow(row); async.complete(); })); })); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/NumericTypesExtendedCodecTest.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.PgClient; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.Tuple; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import org.junit.Test; import java.math.BigDecimal; public class NumericTypesExtendedCodecTest extends ExtendedQueryDataTypeCodecTestBase { @Test public void testDecodeInt2(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT $1 :: INT2 \"Short\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addShort((short) 32767), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Short") .returns(Tuple::getValue, Row::getValue, (short) 32767) .returns(Tuple::getShort, Row::getShort, Short.MAX_VALUE) .returns(Tuple::getInteger, Row::getInteger, 32767) .returns(Tuple::getLong, Row::getLong, 32767L) .returns(Tuple::getFloat, Row::getFloat, 32767f) .returns(Tuple::getDouble, Row::getDouble, 32767d) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal(32767)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.create(32767)) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeInt2(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"NumericDataType\" SET \"Short\" = $1 WHERE \"id\" = $2 RETURNING \"Short\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.of(Short.MIN_VALUE, 2), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Short") .returns(Tuple::getValue, Row::getValue, (short) -32768) .returns(Tuple::getShort, Row::getShort, Short.MIN_VALUE) .returns(Tuple::getInteger, Row::getInteger, -32768) .returns(Tuple::getLong, Row::getLong, -32768L) .returns(Tuple::getFloat, Row::getFloat, -32768f) .returns(Tuple::getDouble, Row::getDouble, -32768d) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal(-32768)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.create(-32768)) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeInt4(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT $1 :: INT4 \"Integer\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addInteger(Integer.MAX_VALUE), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Integer") .returns(Tuple::getValue, Row::getValue, Integer.MAX_VALUE) .returns(Tuple::getShort, Row::getShort, (short) -1) .returns(Tuple::getInteger, Row::getInteger, Integer.MAX_VALUE) .returns(Tuple::getLong, Row::getLong, 2147483647L) .returns(Tuple::getFloat, Row::getFloat, 2147483647f) .returns(Tuple::getDouble, Row::getDouble, 2147483647d) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal(2147483647)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.create(2147483647)) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeInt4(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"NumericDataType\" SET \"Integer\" = $1 WHERE \"id\" = $2 RETURNING \"Integer\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(Integer.MIN_VALUE) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Integer") .returns(Tuple::getValue, Row::getValue, Integer.MIN_VALUE) .returns(Tuple::getShort, Row::getShort, (short) 0) .returns(Tuple::getInteger, Row::getInteger, Integer.MIN_VALUE) .returns(Tuple::getLong, Row::getLong, -2147483648L) .returns(Tuple::getFloat, Row::getFloat, -2147483648f) .returns(Tuple::getDouble, Row::getDouble, -2147483648d) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal(-2147483648)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.create(-2147483648)) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeInt8(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT $1 :: INT8 \"Long\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addLong(Long.MAX_VALUE), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Long") .returns(Tuple::getValue, Row::getValue, Long.MAX_VALUE) .returns(Tuple::getShort, Row::getShort, (short) -1) .returns(Tuple::getInteger, Row::getInteger, -1) .returns(Tuple::getLong, Row::getLong, Long.MAX_VALUE) .returns(Tuple::getFloat, Row::getFloat, 9.223372E18f) .returns(Tuple::getDouble, Row::getDouble, 9.223372036854776E18d) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal(Long.MAX_VALUE)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.create(Long.MAX_VALUE)) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeInt8(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"NumericDataType\" SET \"Long\" = $1 WHERE \"id\" = $2 RETURNING \"Long\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addLong(Long.MIN_VALUE) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Long") .returns(Tuple::getValue, Row::getValue, Long.MIN_VALUE) .returns(Tuple::getShort, Row::getShort, (short) 0) .returns(Tuple::getInteger, Row::getInteger, 0) .returns(Tuple::getLong, Row::getLong, Long.MIN_VALUE) .returns(Tuple::getFloat, Row::getFloat, -9.223372E18f) .returns(Tuple::getDouble, Row::getDouble, -9.223372036854776E18d) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal(Long.MIN_VALUE)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.create(Long.MIN_VALUE)) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeFloat4(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT $1 :: FLOAT4\"Float\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addFloat(Float.MAX_VALUE), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Float") .returns(Tuple::getValue, Row::getValue, Float.MAX_VALUE) .returns(Tuple::getShort, Row::getShort, (short) -1) .returns(Tuple::getInteger, Row::getInteger, 2147483647) .returns(Tuple::getLong, Row::getLong, 9223372036854775807L) .returns(Tuple::getFloat, Row::getFloat, Float.MAX_VALUE) .returns(Tuple::getDouble, Row::getDouble, 3.4028234663852886E38d) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal("" + Float.MAX_VALUE)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.parse("" + Float.MAX_VALUE)) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeFloat4(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"NumericDataType\" SET \"Float\" = $1 WHERE \"id\" = $2 RETURNING \"Float\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addFloat(Float.MIN_VALUE) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Float") .returns(Tuple::getValue, Row::getValue, Float.MIN_VALUE) .returns(Tuple::getShort, Row::getShort, (short) 0) .returns(Tuple::getInteger, Row::getInteger, 0) .returns(Tuple::getLong, Row::getLong, 0L) .returns(Tuple::getFloat, Row::getFloat, Float.MIN_VALUE) .returns(Tuple::getDouble, Row::getDouble, 1.401298464324817E-45d) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal("" + Float.MIN_VALUE)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.parse("" + Float.MIN_VALUE)) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeFloat8(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT $1 :: FLOAT8\"Double\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addDouble(Double.MAX_VALUE), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Double") .returns(Tuple::getValue, Row::getValue, Double.MAX_VALUE) .returns(Tuple::getShort, Row::getShort, (short) -1) .returns(Tuple::getInteger, Row::getInteger, 2147483647) .returns(Tuple::getLong, Row::getLong, 9223372036854775807L) .returns(Tuple::getFloat, Row::getFloat, Float.POSITIVE_INFINITY) .returns(Tuple::getDouble, Row::getDouble, Double.MAX_VALUE) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal("" + Double.MAX_VALUE)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.parse("" + Double.MAX_VALUE)) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeFloat8(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"NumericDataType\" SET \"Double\" = $1 WHERE \"id\" = $2 RETURNING \"Double\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addDouble(Double.MIN_VALUE) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Double") .returns(Tuple::getValue, Row::getValue, Double.MIN_VALUE) .returns(Tuple::getShort, Row::getShort, (short) 0) .returns(Tuple::getInteger, Row::getInteger, 0) .returns(Tuple::getLong, Row::getLong, 0L) .returns(Tuple::getFloat, Row::getFloat, 0f) .returns(Tuple::getDouble, Row::getDouble, Double.MIN_VALUE) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal("" + Double.MIN_VALUE)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.parse("" + Double.MIN_VALUE)) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeSerial2(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"SmallSerial\" FROM \"NumericDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.of(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "SmallSerial") .returns(Tuple::getValue, Row::getValue, (short) 1) .returns(Tuple::getShort, Row::getShort, (short) 1) .returns(Tuple::getInteger, Row::getInteger, 1) .returns(Tuple::getLong, Row::getLong, 1L) .returns(Tuple::getFloat, Row::getFloat, 1f) .returns(Tuple::getDouble, Row::getDouble, 1d) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal(1)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.create(1)) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeSerial2(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"NumericDataType\" SET \"SmallSerial\" = $1 WHERE \"id\" = $2 RETURNING \"SmallSerial\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.of(Short.MIN_VALUE, 2), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "SmallSerial") .returns(Tuple::getValue, Row::getValue, (short) -32768) .returns(Tuple::getShort, Row::getShort, Short.MIN_VALUE) .returns(Tuple::getInteger, Row::getInteger, -32768) .returns(Tuple::getLong, Row::getLong, -32768L) .returns(Tuple::getFloat, Row::getFloat, -32768f) .returns(Tuple::getDouble, Row::getDouble, -32768d) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal(-32768)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.create(-32768)) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeSerial4(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Serial\" FROM \"NumericDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addInteger(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Serial") .returns(Tuple::getValue, Row::getValue, 1) .returns(Tuple::getShort, Row::getShort, (short) 1) .returns(Tuple::getInteger, Row::getInteger, 1) .returns(Tuple::getLong, Row::getLong, 1L) .returns(Tuple::getFloat, Row::getFloat, 1f) .returns(Tuple::getDouble, Row::getDouble, 1d) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal(1)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.create(1)) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeSerial4(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"NumericDataType\" SET \"Serial\" = $1 WHERE \"id\" = $2 RETURNING \"Serial\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(Integer.MIN_VALUE) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Serial") .returns(Tuple::getValue, Row::getValue, Integer.MIN_VALUE) .returns(Tuple::getShort, Row::getShort, (short) 0) .returns(Tuple::getInteger, Row::getInteger, Integer.MIN_VALUE) .returns(Tuple::getLong, Row::getLong, -2147483648L) .returns(Tuple::getFloat, Row::getFloat, -2147483648f) .returns(Tuple::getDouble, Row::getDouble, -2147483648d) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal(-2147483648)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.create(-2147483648)) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeSerial8(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"BigSerial\" FROM \"NumericDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addInteger(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "BigSerial") .returns(Tuple::getValue, Row::getValue, 1L) .returns(Tuple::getShort, Row::getShort, (short) 1) .returns(Tuple::getInteger, Row::getInteger, 1) .returns(Tuple::getLong, Row::getLong, 1L) .returns(Tuple::getFloat, Row::getFloat, 1f) .returns(Tuple::getDouble, Row::getDouble, 1d) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal(1)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.create(1)) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeSerial8(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"NumericDataType\" SET \"BigSerial\" = $1 WHERE \"id\" = $2 RETURNING \"BigSerial\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addLong(Long.MIN_VALUE) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "BigSerial") .returns(Tuple::getValue, Row::getValue, Long.MIN_VALUE) .returns(Tuple::getShort, Row::getShort, (short) 0) .returns(Tuple::getInteger, Row::getInteger, 0) .returns(Tuple::getLong, Row::getLong, Long.MIN_VALUE) .returns(Tuple::getFloat, Row::getFloat, -9.223372E18f) .returns(Tuple::getDouble, Row::getDouble, -9.223372036854776E18d) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal(Long.MIN_VALUE)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.create(Long.MIN_VALUE)) .forRow(row); async.complete(); })); })); })); } @Test public void testNumeric(TestContext ctx) { testGeneric(ctx, "SELECT c FROM (VALUES ($1 :: NUMERIC)) AS t (c)", new Numeric[]{ Numeric.create(10), Numeric.create(200030004), Numeric.create(-500), Numeric.NaN }, Tuple::getNumeric); } @Test public void testNumericArray(TestContext ctx) { testGeneric(ctx, "SELECT c FROM (VALUES ($1 :: NUMERIC[])) AS t (c)", new Numeric[][]{new Numeric[]{Numeric.create(10), Numeric.create(200030004), null, Numeric.create(-500), Numeric.NaN, null}}, Tuple::getNumericArray); } @Test public void testShortArray(TestContext ctx) { testGeneric(ctx, "SELECT c FROM (VALUES ($1 :: INT2[])) AS t (c)", new Short[][]{new Short[]{0, -10, null, Short.MAX_VALUE}}, Tuple::getShortArray); } @Test public void testIntegerArray(TestContext ctx) { testGeneric(ctx, "SELECT c FROM (VALUES ($1 :: INT4[])) AS t (c)", new Integer[][]{new Integer[]{0, -10, null, Integer.MAX_VALUE}}, Tuple::getIntegerArray); } @Test public void testLongArray(TestContext ctx) { testGeneric(ctx, "SELECT c FROM (VALUES ($1 :: INT8[])) AS t (c)", new Long[][]{new Long[]{0L, -10L, null, Long.MAX_VALUE}}, Tuple::getLongArray); } @Test public void testFloatArray(TestContext ctx) { testGeneric(ctx, "SELECT c FROM (VALUES ($1 :: FLOAT4[])) AS t (c)", new Float[][]{new Float[]{0f, -10f, Float.MAX_VALUE}}, Tuple::getFloatArray); } @Test public void testDecodeShortArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Short\" FROM \"ArrayDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Short") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(new short[]{1})) .returns(Tuple::getShortArray, Row::getShortArray, ColumnChecker.toObjectArray(new short[]{1})) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeShortArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Short\" = $1 WHERE \"id\" = $2 RETURNING \"Short\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addShortArray(new Short[]{2, 3, 4}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Short") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(new short[]{2, 3, 4})) .returns(Tuple::getShortArray, Row::getShortArray, ColumnChecker.toObjectArray(new short[]{2, 3, 4})) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testDecodeIntArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Integer\" FROM \"ArrayDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Integer") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(new int[]{2})) .returns(Tuple::getIntegerArray, Row::getIntegerArray, ColumnChecker.toObjectArray(new int[]{2})) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeIntArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Integer\" = $1 WHERE \"id\" = $2 RETURNING \"Integer\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addIntegerArray(new Integer[]{3, 4, 5, 6}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Integer") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(new int[]{3, 4, 5, 6})) .returns(Tuple::getIntegerArray, Row::getIntegerArray, ColumnChecker.toObjectArray(new int[]{3, 4, 5, 6})) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testDecodeLongArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Long\" FROM \"ArrayDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Long") .returns(Tuple::getValue, Row::getValue, new Long[]{3L}) .returns(Tuple::getLongArray, Row::getLongArray, new Long[]{3L}) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeLongArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Long\" = $1 WHERE \"id\" = $2 RETURNING \"Long\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addLongArray(new Long[]{4L, 5L, 6L, 7L, 8L}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Long") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(new long[]{4, 5, 6, 7, 8})) .returns(Tuple::getLongArray, Row::getLongArray, ColumnChecker.toObjectArray(new long[]{4, 5, 6, 7, 8})) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testDecodeFloatArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Float\" FROM \"ArrayDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Float") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(new float[]{4.1f})) .returns(Tuple::getFloatArray, Row::getFloatArray, ColumnChecker.toObjectArray(new float[]{4.1f})) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeFloatArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Float\" = $1 WHERE \"id\" = $2 RETURNING \"Float\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addFloatArray(new Float[]{5.2f, 5.3f, 5.4f}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Float") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(new float[]{5.2f, 5.3f, 5.4f})) .returns(Tuple::getFloatArray, Row::getFloatArray, ColumnChecker.toObjectArray(new float[]{5.2f, 5.3f, 5.4f})) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testDecodeDoubleArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Double\" FROM \"ArrayDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Double") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(new double[]{5.2})) .returns(Tuple::getDoubleArray, Row::getDoubleArray, ColumnChecker.toObjectArray(new double[]{5.2})) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeDoubleArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Double\" = $1 WHERE \"id\" = $2 RETURNING \"Double\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addDoubleArray(new Double[]{6.3}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Double") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(new double[]{6.3})) .returns(Tuple::getDoubleArray, Row::getDoubleArray, ColumnChecker.toObjectArray(new double[]{6.3})) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeEmptyArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Double\" = $1 WHERE \"id\" = $2 RETURNING \"Double\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addDoubleArray(new Double[]{}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Double") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(new double[]{})) .returns(Tuple::getDoubleArray, Row::getDoubleArray, ColumnChecker.toObjectArray(new double[]{})) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testDecodeNumericArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Numeric\" FROM \"ArrayDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { Numeric[] expected = { Numeric.create(0), Numeric.create(1), Numeric.create(2), Numeric.create(3) }; ColumnChecker.checkColumn(0, "Numeric") .returns(Tuple::getValue, Row::getValue, expected) .returns(Tuple::getNumericArray, Row::getNumericArray, expected) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeNumericArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Numeric\" = $1 WHERE \"id\" = $2 RETURNING \"Numeric\"", ctx.asyncAssertSuccess(p -> { Numeric[] expected = { Numeric.create(0), Numeric.create(10000), }; p.execute(Tuple.tuple() .addNumericArray(expected) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Numeric") .returns(Tuple::getValue, Row::getValue, expected) .returns(Tuple::getNumericArray, Row::getNumericArray, expected) .forRow(result.iterator().next()); async.complete(); })); })); })); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/NumericTypesSimpleCodecTest.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.PgClient; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.Tuple; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import org.junit.Test; import java.math.BigDecimal; public class NumericTypesSimpleCodecTest extends SimpleQueryDataTypeCodecTestBase { @Test public void testInt2(TestContext ctx) { testNumber(ctx, new Number[]{(short) 32767, (short) -1}, "INT2"); } @Test public void testInt4(TestContext ctx) { testNumber(ctx, new Number[]{2147483647, -1}, "INT4"); } @Test public void testInt8(TestContext ctx) { testNumber(ctx, new Number[]{9223372036854775807L, -1L}, "INT8"); } @Test public void testFloat4(TestContext ctx) { testNumber(ctx, new Number[]{3.4028235E38f, -1f}, "FLOAT4"); } @Test public void testFloat8(TestContext ctx) { testNumber(ctx, new Number[]{1.7976931348623157E308D, -1D}, "FLOAT8"); } @Test public void testSerial2(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn .query("SELECT \"SmallSerial\" FROM \"NumericDataType\" WHERE \"id\" = 1", ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "SmallSerial") .returns(Tuple::getValue, Row::getValue, (short) 1) .returns(Tuple::getShort, Row::getShort, (short) 1) .returns(Tuple::getInteger, Row::getInteger, 1) .returns(Tuple::getLong, Row::getLong, 1L) .returns(Tuple::getFloat, Row::getFloat, 1f) .returns(Tuple::getDouble, Row::getDouble, 1d) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal(1)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.create(1)) .forRow(row); async.complete(); })); })); } @Test public void testSerial4(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn .query("SELECT \"Serial\" FROM \"NumericDataType\" WHERE \"id\" = 1", ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Serial") .returns(Tuple::getValue, Row::getValue, 1) .returns(Tuple::getShort, Row::getShort, (short) 1) .returns(Tuple::getInteger, Row::getInteger, 1) .returns(Tuple::getLong, Row::getLong, 1L) .returns(Tuple::getFloat, Row::getFloat, 1f) .returns(Tuple::getDouble, Row::getDouble, 1d) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal(1)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.create(1)) .forRow(row); async.complete(); })); })); } @Test public void testSerial8(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn .query("SELECT \"BigSerial\" FROM \"NumericDataType\" WHERE \"id\" = 1", ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "BigSerial") .returns(Tuple::getValue, Row::getValue, 1L) .returns(Tuple::getShort, Row::getShort, (short) 1) .returns(Tuple::getInteger, Row::getInteger, 1) .returns(Tuple::getLong, Row::getLong, 1L) .returns(Tuple::getFloat, Row::getFloat, 1f) .returns(Tuple::getDouble, Row::getDouble, 1d) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal(1)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.create(1)) .forRow(row); async.complete(); })); })); } @Test public void testNumeric(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn .query("SELECT 919.999999999999999999999999999999999999::NUMERIC \"Numeric\", 'NaN'::NUMERIC \"NaN\"", ctx.asyncAssertSuccess(result -> { Numeric numeric = Numeric.parse("919.999999999999999999999999999999999999"); Numeric nan = Numeric.parse("NaN"); ctx.assertEquals(1, result.size()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Numeric") .returns(Tuple::getValue, Row::getValue, numeric) .returns(Tuple::getShort, Row::getShort, (short) 919) .returns(Tuple::getInteger, Row::getInteger, 919) .returns(Tuple::getLong, Row::getLong, 919L) .returns(Tuple::getFloat, Row::getFloat, 920f) .returns(Tuple::getDouble, Row::getDouble, 920.0) .returns(Tuple::getBigDecimal, Row::getBigDecimal, numeric.bigDecimalValue()) .returns(Tuple::getNumeric, Row::getNumeric, numeric) .forRow(row); ColumnChecker.checkColumn(1, "NaN") .returns(Tuple::getValue, Row::getValue, nan) .returns(Tuple::getShort, Row::getShort, (short) 0) .returns(Tuple::getInteger, Row::getInteger, 0) .returns(Tuple::getLong, Row::getLong, 0L) .returns(Tuple::getFloat, Row::getFloat, Float.NaN) .returns(Tuple::getDouble, Row::getDouble, Double.NaN) .fails(Tuple::getBigDecimal, Row::getBigDecimal) .returns(Tuple::getNumeric, Row::getNumeric, nan) .forRow(row); async.complete(); })); })); } private void testNumber(TestContext ctx, Number[] values, String type) { Async async = ctx.async(values.length); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { for (Number value : values) { conn .query("SELECT " + value + "::" + type + " \"col\"", ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "col") .returns(Tuple::getValue, Row::getValue, value) .returns(Tuple::getShort, Row::getShort, value.shortValue()) .returns(Tuple::getInteger, Row::getInteger, value.intValue()) .returns(Tuple::getLong, Row::getLong, value.longValue()) .returns(Tuple::getFloat, Row::getFloat, value.floatValue()) .returns(Tuple::getDouble, Row::getDouble, value.doubleValue()) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal("" + value)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.parse("" + value)) .forRow(row); async.countDown(); })); } })); } @Test public void testDecodeINT2Array(TestContext ctx) { testDecodeGenericArray(ctx, "ARRAY [1 :: INT2]", "Short", Tuple::getShortArray, Row::getShortArray, (short) 1); } @Test public void testDecodeINT4Array(TestContext ctx) { testDecodeGenericArray(ctx, "ARRAY [2 :: INT4]", "Integer", Tuple::getIntegerArray, Row::getIntegerArray, 2); } @Test public void testDecodeINT8Array(TestContext ctx) { testDecodeGenericArray(ctx, "ARRAY [3 :: INT8]", "Long", Tuple::getLongArray, Row::getLongArray, 3L); } @Test public void testDecodeFLOAT4Array(TestContext ctx) { testDecodeGenericArray(ctx, "ARRAY [4.1 :: FLOAT4]", "Float", Tuple::getFloatArray, Row::getFloatArray, 4.1f); } @Test public void testDecodeFLOAT8Array(TestContext ctx) { testDecodeGenericArray(ctx, "ARRAY [5.2 :: FLOAT8]", "Double", Tuple::getDoubleArray, Row::getDoubleArray, 5.2d); } @Test public void testDecodeEmptyArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { // The extra column makes sure that reading the array remains confined in the value since we are doing // parsing of the array value conn.query("SELECT '{}'::bigint[] \"array\", 1 \"Extra\"", ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "array") .returns(Tuple::getValue, Row::getValue, (Object[]) new Long[0]) .returns(Tuple::getLongArray, Row::getLongArray, (Object[]) new Long[0]) .forRow(result.iterator().next()); async.complete(); })); })); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/PreparedStatementParamCoercionTest.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.PgClient; import io.reactiverse.pgclient.PgConnectOptions; import io.reactiverse.pgclient.PgConnection; import io.reactiverse.pgclient.Tuple; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import org.junit.Test; import java.lang.reflect.Array; import java.math.BigInteger; public class PreparedStatementParamCoercionTest extends DataTypeTestBase { @Override protected PgConnectOptions options() { return options; } private static final Object[] VALUES_TO_COERCE = { (byte)5, (short)5, 5, 5L, 5f, 5d, BigInteger.valueOf(5), Numeric.create(5) }; private static final String[] SQL_TYPES_TO_COERCE_TO = { "SMALLINT", "INTEGER", "BIGINT", "DECIMAL", "NUMERIC", "REAL", "DOUBLE PRECISION" }; @Test public void testCoerceSingleParam(TestContext ctx) { Async async = ctx.async(VALUES_TO_COERCE.length * SQL_TYPES_TO_COERCE_TO.length); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { for (String sqlType : SQL_TYPES_TO_COERCE_TO) { for (Object value: VALUES_TO_COERCE) { assertCoerceParam(conn, ctx, "SELECT 1 \"result\" WHERE $1::" + sqlType + "=5", value, async::countDown); } } })); } @Test public void testCoerceArrayParam(TestContext ctx) { Async async = ctx.async(VALUES_TO_COERCE.length * SQL_TYPES_TO_COERCE_TO.length); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { for (String sqlType : SQL_TYPES_TO_COERCE_TO) { for (Object value: VALUES_TO_COERCE) { Object array = Array.newInstance(value.getClass(), 1); Array.set(array, 0, value); assertCoerceParam(conn, ctx, "SELECT 1 \"result\" WHERE ($1::" + sqlType + "[])=ARRAY[5::" + sqlType + "]", array, async::countDown); } } })); } private void assertCoerceParam(PgConnection conn, TestContext ctx, String query, Object value, Runnable cont) { conn .preparedQuery(query, Tuple.of(value), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.iterator().next().getInteger(0)); cont.run(); })); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/SimpleQueryDataTypeCodecTestBase.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.PgClient; import io.reactiverse.pgclient.PgConnectOptions; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.Tuple; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; /** * @author Emad Alblueshi */ public abstract class SimpleQueryDataTypeCodecTestBase extends DataTypeTestBase { @Override protected PgConnectOptions options() { return new PgConnectOptions(options).setCachePreparedStatements(false); } protected void testDecodeGeneric(TestContext ctx, String data, String dataType, String columnName, ColumnChecker.SerializableBiFunction byIndexGetter, ColumnChecker.SerializableBiFunction byNameGetter, T expected) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.query("SELECT '" + data + "' :: " + dataType + " \"" + columnName + "\"", ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, columnName) .returns(Tuple::getValue, Row::getValue, expected) .returns(byIndexGetter, byNameGetter, expected) .forRow(row); async.complete(); })); })); } protected void testDecodeGenericArray(TestContext ctx, String arrayData, String columnName, ColumnChecker.SerializableBiFunction byIndexGetter, ColumnChecker.SerializableBiFunction byNameGetter, Object... expected) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.query("SET TIME ZONE 'UTC'", ctx.asyncAssertSuccess(res -> { conn.query("SELECT " + arrayData + " \"" + columnName + "\"", ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, columnName) .returns(Tuple::getValue, Row::getValue, expected) .returns(byIndexGetter, byNameGetter, expected) .forRow(row); async.complete(); })); })); })); } protected void testDecodeXXXArray(TestContext ctx, String columnName, String tableName, ColumnChecker.SerializableBiFunction byIndexGetter, ColumnChecker.SerializableBiFunction byNameGetter, Object... expected) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.query("SET TIME ZONE 'UTC'", ctx.asyncAssertSuccess(res -> { conn.query("SELECT \"" + columnName + "\" FROM \"" + tableName + "\" WHERE \"id\" = 1", ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, columnName) .returns(Tuple::getValue, Row::getValue, expected) .returns(byIndexGetter, byNameGetter, expected) .forRow(result.iterator().next()); async.complete(); })); })); })); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/UUIDTypeExtendedCodecTest.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.PgClient; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.Tuple; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import org.junit.Test; import java.util.UUID; public class UUIDTypeExtendedCodecTest extends ExtendedQueryDataTypeCodecTestBase { @Test public void testDecodeUUID(TestContext ctx) { testGeneric(ctx, "SELECT $1::UUID \"uuid\"", new UUID[]{uuid}, Tuple::getUUID); } @Test public void testEncodeUUID(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"CharacterDataType\" SET \"uuid\" = $1 WHERE \"id\" = $2 RETURNING \"uuid\"", ctx.asyncAssertSuccess(p -> { UUID uuid = UUID.fromString("92b53cf1-2ad0-49f9-be9d-ca48966e43ee"); p.execute(Tuple.tuple() .addUUID(uuid) .addInteger(2), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "uuid") .returns(Tuple::getValue, Row::getValue, uuid) .returns(Tuple::getUUID, Row::getUUID, uuid) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeUUIDArray(TestContext ctx) { testGeneric(ctx, "SELECT $1::UUID[] \"UUID\"", new UUID[][]{new UUID[]{uuid}}, Tuple::getUUIDArray); } @Test public void testEncodeUUIDArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"UUID\" = $1 WHERE \"id\" = $2 RETURNING \"UUID\"", ctx.asyncAssertSuccess(p -> { final UUID uuid = UUID.fromString("6f790482-b5bd-438b-a8b7-4a0bed747011"); p.execute(Tuple.tuple() .addUUIDArray(new UUID[]{uuid}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "UUID") .returns(Tuple::getValue, Row::getValue, new UUID[]{uuid}) .returns(Tuple::getUUIDArray, Row::getUUIDArray, new UUID[]{uuid}) .forRow(result.iterator().next()); async.complete(); })); })); })); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/data/UUIDTypeSimpleCodecTest.java ================================================ package io.reactiverse.pgclient.data; import io.reactiverse.pgclient.Row; import io.reactiverse.pgclient.Tuple; import io.vertx.ext.unit.TestContext; import org.junit.Test; import java.util.UUID; public class UUIDTypeSimpleCodecTest extends SimpleQueryDataTypeCodecTestBase { @Test public void testUUID(TestContext ctx) { UUID expected = UUID.fromString("50867d3d-0098-4f61-bd31-9309ebf53475"); testDecodeGeneric(ctx, "50867d3d-0098-4f61-bd31-9309ebf53475", "UUID", "uuid", Tuple::getUUID, Row::getUUID, expected); } @Test public void testDecodeUUIDArray(TestContext ctx) { testDecodeGenericArray(ctx, "ARRAY ['6f790482-b5bd-438b-a8b7-4a0bed747011' :: UUID]", "UUID", Tuple::getUUIDArray, Row::getUUIDArray, uuid); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/impl/codec/util/MD5AuthenticationTest.java ================================================ package io.reactiverse.pgclient.impl.codec.util; import org.junit.Test; import java.nio.charset.StandardCharsets; import static org.junit.Assert.*; public class MD5AuthenticationTest { @Test public void encodeTest() { assertEquals( "md54cd35160716308e3e571bbba12bb7591", MD5Authentication.encode("scott", "tiger", "salt'n'pepper".getBytes(StandardCharsets.UTF_8))); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/it/EnvTest.java ================================================ /* * Copyright (C) 2018 Julien Viet * * Licensed 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 io.reactiverse.pgclient.it; import io.reactiverse.pgclient.PgConnectOptions; import io.reactiverse.pgclient.SslMode; import org.junit.Test; import static org.junit.Assert.assertEquals; public class EnvTest { @Test public void testFoo() { PgConnectOptions options = PgConnectOptions.fromEnv(); assertEquals("test_host", options.getHost()); assertEquals("test_database", options.getDatabase()); assertEquals("test_user", options.getUser()); assertEquals("test_password", options.getPassword()); assertEquals(SslMode.REQUIRE, options.getSslMode()); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/pool/ConnectionPoolTest.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.pool; import io.reactiverse.pgclient.impl.ConnectionPool; import io.vertx.core.Future; import org.junit.Test; import static org.junit.Assert.*; public class ConnectionPoolTest { @Test public void testSimple() { ConnectionQueue queue = new ConnectionQueue(); ConnectionPool pool = new ConnectionPool(queue, 1); SimpleHolder holder = new SimpleHolder(); pool.acquire(holder); assertEquals(1, queue.size()); assertFalse(holder.isComplete()); SimpleConnection conn = new SimpleConnection(); queue.connect(conn); assertTrue(holder.isConnected()); assertNotNull(conn.holder); assertNotSame(conn, holder.connection()); holder.init(); holder.close(); } @Test public void testRecycle() { ConnectionQueue queue = new ConnectionQueue(); ConnectionPool pool = new ConnectionPool(queue, 1); SimpleHolder holder1 = new SimpleHolder(); pool.acquire(holder1); SimpleConnection conn = new SimpleConnection(); queue.connect(conn); holder1.init(); SimpleHolder holder2 = new SimpleHolder(); pool.acquire(holder2); assertFalse(holder2.isComplete()); assertEquals(0, queue.size()); holder1.close(); assertEquals(0, conn.closed); assertEquals(0, holder1.closed()); assertTrue(holder2.isConnected()); assertEquals(0, queue.size()); } @Test public void testConnectionCreation() { ConnectionQueue queue = new ConnectionQueue(); ConnectionPool pool = new ConnectionPool(queue, 1); SimpleHolder holder1 = new SimpleHolder(); pool.acquire(holder1); SimpleHolder holder2 = new SimpleHolder(); pool.acquire(holder2); assertEquals(1, queue.size()); // Check that we won't create more connection than max size SimpleConnection conn = new SimpleConnection(); queue.connect(conn); assertTrue(holder1.isConnected()); assertEquals(0, queue.size()); } @Test public void testConnClose() { ConnectionQueue queue = new ConnectionQueue(); ConnectionPool pool = new ConnectionPool(queue, 1); SimpleHolder holder1 = new SimpleHolder(); pool.acquire(holder1); SimpleConnection conn = new SimpleConnection(); queue.connect(conn); holder1.init(); SimpleHolder holder2 = new SimpleHolder(); pool.acquire(holder2); assertFalse(holder2.isComplete()); assertEquals(0, queue.size()); conn.close(); assertEquals(1, holder1.closed()); assertEquals(1, queue.size()); assertFalse(holder2.isComplete()); } @Test public void testConnectionCloseInPool() { ConnectionQueue queue = new ConnectionQueue(); ConnectionPool pool = new ConnectionPool(queue, 1); SimpleHolder holder = new SimpleHolder(); pool.acquire(holder); SimpleConnection conn = new SimpleConnection(); queue.connect(conn); holder.init(); holder.close(); conn.close(); assertEquals(0, pool.available()); } @Test public void testDoubleConnectionClose() { ConnectionQueue queue = new ConnectionQueue(); ConnectionPool pool = new ConnectionPool(queue, 1); SimpleHolder holder = new SimpleHolder(); pool.acquire(holder); SimpleConnection conn = new SimpleConnection(); queue.connect(conn); holder.init(); conn.close(); try { conn.close(); fail(); } catch (IllegalStateException ignore) { } } @Test public void testDoubleConnectionRelease() { ConnectionQueue queue = new ConnectionQueue(); ConnectionPool pool = new ConnectionPool(queue, 1); SimpleHolder holder = new SimpleHolder(); pool.acquire(holder); SimpleConnection conn = new SimpleConnection(); queue.connect(conn); holder.init(); holder.close(); try { holder.close(); fail(); } catch (IllegalStateException ignore) { } } @Test public void testDoubleConnectionAcquire() { ConnectionQueue queue = new ConnectionQueue(); ConnectionPool pool = new ConnectionPool(queue, 1); SimpleHolder holder = new SimpleHolder(); pool.acquire(holder); SimpleConnection conn = new SimpleConnection(); queue.connect(conn); holder.init(); try { holder.init(); fail(); } catch (IllegalStateException ignore) { } } @Test public void testReleaseConnectionWhenWaiterQueueIsEmpty() { ConnectionQueue queue = new ConnectionQueue(); ConnectionPool pool = new ConnectionPool(queue, 2); // Acquire a connection from the pool for holder1 SimpleHolder holder1 = new SimpleHolder(); pool.acquire(holder1); SimpleConnection conn1 = new SimpleConnection(); queue.connect(conn1); holder1.init(); // Acquire a connection from the pool for holder2 SimpleHolder holder2 = new SimpleHolder(); pool.acquire(holder2); // Release the first connection so the second waiter gets the connection holder1.close(); // The connection should be put back in the pool assertEquals(1, pool.available()); // Satisfy the holder with connection it actually asked for SimpleConnection conn2 = new SimpleConnection(); queue.connect(conn2); holder2.init(); } @Test public void testReleaseClosedConnectionShouldNotAddBackTheConnectionToThePool() { ConnectionQueue queue = new ConnectionQueue(); ConnectionPool pool = new ConnectionPool(queue, 1); // Acquire a connection from the pool for holder1 SimpleHolder holder1 = new SimpleHolder(); pool.acquire(holder1); SimpleConnection conn1 = new SimpleConnection(); queue.connect(conn1); holder1.init(); // Close connection conn1.close(); holder1.close(); assertEquals(pool.available(), 0); } @Test public void testMaxQueueSize1() { ConnectionQueue queue = new ConnectionQueue(); ConnectionPool pool = new ConnectionPool(queue, 1, 0); SimpleHolder holder1 = new SimpleHolder(); pool.acquire(holder1); SimpleConnection conn = new SimpleConnection(); queue.connect(conn); holder1.init(); SimpleHolder holder2 = new SimpleHolder(); pool.acquire(holder2); assertTrue(holder2.isFailed()); } @Test public void testMaxQueueSize2() { SimpleHolder holder2 = new SimpleHolder(); SimpleConnection conn = new SimpleConnection(); ConnectionPool[] poolRef = new ConnectionPool[1]; ConnectionPool pool = new ConnectionPool(ar -> { poolRef[0].acquire(holder2); assertFalse(holder2.isComplete()); ar.handle(Future.succeededFuture(conn)); assertFalse(holder2.isComplete()); }, 1, 0); poolRef[0] = pool; SimpleHolder holder1 = new SimpleHolder(); pool.acquire(holder1); assertTrue(holder1.isComplete()); assertTrue(holder2.isFailed()); } @Test public void testConnectionFailure() { ConnectionQueue queue = new ConnectionQueue(); ConnectionPool pool = new ConnectionPool(queue, 1, 0); SimpleHolder holder1 = new SimpleHolder(); pool.acquire(holder1); Exception cause = new Exception(); queue.fail(cause); assertTrue(holder1.isFailed()); assertSame(cause, holder1.failure()); assertEquals(0, pool.available()); assertEquals(0, pool.size()); SimpleHolder holder2 = new SimpleHolder(); pool.acquire(holder2); SimpleConnection conn = new SimpleConnection(); queue.connect(conn); assertTrue(holder2.isConnected()); assertEquals(0, pool.available()); assertEquals(1, pool.size()); } @Test public void testAcquireOnlyConnectOnce() { ConnectionQueue queue = new ConnectionQueue(); ConnectionPool pool = new ConnectionPool(queue, 10, 0); SimpleHolder holder1 = new SimpleHolder(); pool.acquire(holder1); assertEquals(1, queue.size()); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/pool/ConnectionQueue.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.pool; import io.reactiverse.pgclient.impl.Connection; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import java.util.ArrayDeque; import java.util.function.Consumer; class ConnectionQueue extends ArrayDeque>> implements Consumer>> { @Override public void accept(Handler> event) { add(event); } void connect(SimpleConnection conn) { poll().handle(Future.succeededFuture(conn)); } void fail(Throwable cause) { poll().handle(Future.failedFuture(cause)); } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/pool/SimpleConnection.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.pool; import io.reactiverse.pgclient.impl.CommandBase; import io.reactiverse.pgclient.impl.Connection; class SimpleConnection implements Connection { Holder holder; int closed; @Override public void init(Holder holder) { this.holder = holder; } @Override public boolean isSsl() { return false; } @Override public void close(Holder holder) { closed++; } void close() { holder.handleClosed(); } @Override public void schedule(CommandBase cmd) { throw new UnsupportedOperationException(); } @Override public int getProcessId() { return -1; } @Override public int getSecretKey() { return -1; } } ================================================ FILE: src/test/java/io/reactiverse/pgclient/pool/SimpleHolder.java ================================================ /* * Copyright (C) 2017 Julien Viet * * Licensed 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 io.reactiverse.pgclient.pool; import io.reactiverse.pgclient.impl.Connection; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; class SimpleHolder implements Connection.Holder, Handler> { private Connection conn; private Throwable failure; private int closed; SimpleHolder() { } int closed() { return closed; } boolean isConnected() { return conn != null; } boolean isComplete() { return isConnected() || isFailed(); } boolean isFailed() { return failure != null; } Throwable failure() { return failure; } void init() { conn.init(this); } @Override public void handle(AsyncResult ar) { if (ar.succeeded()) { conn = ar.result(); } else { failure = ar.cause(); } } @Override public Connection connection() { return conn; } @Override public void handleClosed() { closed++; } @Override public void handleException(Throwable err) { } @Override public void handleNotification(int processId, String channel, String payload) { } void close() { conn.close(this); } }