Class: SQLiteSweep::Query::Remote

Inherits:
Base
  • Object
show all
Defined in:
lib/sqlitesweep/query/remote.rb

Overview

Executes batched SQL queries on remote hosts via SSH.

Instead of one SSH round-trip per database, this runs a single SSH command that queries multiple databases sequentially on the remote host. The remote command iterates over database paths, running sqlite3 -json on each one, and outputs tab-delimited lines:

/path/to/db1.sqlite3\t[{"count(*)":42}]
/path/to/db2.sqlite3\t[{"count(*)":17}]

The output is parsed back into individual Result objects, one per database.

Examples:

remote = Query::Remote.new(config, ssh_manager)
results = remote.execute_batch([uri1, uri2, uri3])
results.each { |r| puts "#{r.source}: #{r.rows}" }

Instance Method Summary collapse

Methods inherited from Base

#execute

Constructor Details

#initialize(config, ssh_manager) ⇒ Remote

Returns a new instance of Remote.



24
25
26
27
# File 'lib/sqlitesweep/query/remote.rb', line 24

def initialize(config, ssh_manager)
  super(config)
  @ssh_manager = ssh_manager
end

Instance Method Details

#execute_batch(uris) ⇒ Array<Result>

Queries multiple databases on the same remote host in a single SSH call.

Parameters:

  • uris (Array<DatabaseURI>)

    URIs for databases on the same host. All URIs must share the same host_key.

Returns:

  • (Array<Result>)

    One Result per successfully queried database.

Raises:

  • (QueryError)

    If the SSH command fails or JSON parsing fails.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/sqlitesweep/query/remote.rb', line 35

def execute_batch(uris)
  return [] if uris.empty?

  host_key = uris.first.host_key
  paths = uris.map(&:path)

  # Escape single quotes in the SQL for safe embedding in the shell command
  sql = @config.query.gsub("'", "'\\''")

  # Build a remote script that queries each database and outputs
  # tab-delimited results: <db_path>\t<json_result>
  remote_script = paths.map { |path|
    escaped_path = Shellwords.shellescape(path)
    "printf '%s\\t' #{escaped_path}; sqlite3 -json #{escaped_path} '#{sql}'; echo"
  }.join("; ")

  output = @ssh_manager.run(host_key, remote_script)
  parse_batch_output(output, uris)
end