Skip to content

tokuhirom/jdbc-querylog

Repository files navigation

JDBC QueryLog

Maven Central javadoc.io Circle CI

jdbc-querylog is a JDBC driver, which provides hook points to trace all queries.

SYNOPSIS

Use 'jdbc:querylog:' prefix for JDBC connection uri.

    QueryLogDriver.setExplain(true);
    try (Connection conn = DriverManager.getConnection("jdbc:querylog:h2:mem:test")) {
        try (PreparedStatement stmt = conn.prepareStatement("SELECT * FROM user WHERE id=?")) {
            stmt.setInt(1, 1);
            try (ResultSet resultSet = stmt.executeQuery()) {
            }
        }
        try (PreparedStatement stmt = conn.prepareStatement("SELECT * FROM user")) {
            try (ResultSet resultSet = stmt.executeQuery()) {
            }
        }
    }

Then, you got automatic EXPLAIN.

Query: SELECT * FROM user WHERE id=1
┌────────────────────────────────────────┐
│ PLAN                                   │
├────────────────────────────────────────┤
│ SELECT                                 │
│ USER.ID,                               │
│ USER.NAME                              │
│ FROM PUBLIC.USER                       │
│ /* PUBLIC.PRIMARY_KEY_2: ID = 1 */     │
│ WHERE ID = 1                           │
└────────────────────────────────────────┘

Query: SELECT * FROM user
┌─────────────────────────────────┐
│ PLAN                            │
├─────────────────────────────────┤
│ SELECT                          │
│ USER.ID,                        │
│ USER.NAME                       │
│ FROM PUBLIC.USER                │
│ /* PUBLIC.USER.tableScan */     │
└─────────────────────────────────┘

Use cases

  • Record all statements executed by JDBC driver
  • Detect heavy queries in development environment.
    • Send EXPLAIN statement
  • Logging queries and parameters.
  • Detect webapp controller, that sends too much SQL queries.

Usage

If your JDBC uri is this:

jdbc:mysql://localhost/test

Then, you need to rewrite the uri as following:

jdbc:querylog:mysql://localhost/test

That's all.

Options

QueryLogDriver.setExplain(true) : Default false

Enable automatic EXPLAIN statement generation.

(Note, this feature only supports mysql. patches welcome)

QueryLogDriver.setCompact(true) : Default true

Compact SQL query before query logging.

QueryLogDriver.setQueryHandler(Connection connection, String query)

    QueryLogDriver.setQueryHandler((connection, query) -> {
        System.err.println("Query: " + query);
    });

Added query handler. If you set this handler, querylog pass the query to the callback handler.

QueryLogDriver.setExplainHandler(ExplainHandler printExplain)

    QueryLogDriver.setExplainHandler((connection, query, header, rows) -> {
        System.err.println("Query: " + query);
        System.err.println("Header: " + Arrays.toString(header));
        System.err.println("Rows: " + rows.stream()
                .map(it -> Arrays.stream(it).collect(Collectors.joining(",")))
                .collect(Collectors.joining("\n")));
    });

Set explain handler. If you call QueryLogDriver.setExplain(true), querylog sends EXPLAIN statement to DB server, and pass the results to the callback listener.

jdbc-tracer

jdbc-querylog is based on jdbc-tracer. jdbc-tracer provides following two listener interfaces.

PreparedStatementListener

You can get following values for each executed queries:

  • connection
  • elapsed time
  • SQL statement
  • binded variables

ResultSetListener

You can get following values for each got rows:

  • isFirstRow
    • You may print column information on first row.
  • resultSet
    • you can get resultset information!
      • (MUST NOT call next() from the listener. it cause infinite loop)

Install

You can install this library from maven central.

SEE ALSO

This is a port of Perl5's DBIx::QueryLog.

http://search.cpan.org/perldoc?DBIx%3A%3AQueryLog

License

The MIT License (MIT)
Copyright © 2016 Tokuhiro Matsuno, http://64p.org/ <tokuhirom@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages