Skip to content

Instantly share code, notes, and snippets.

@thekid
Created July 25, 2014 18:06
Show Gist options
  • Select an option

  • Save thekid/67925df18d5015a85a10 to your computer and use it in GitHub Desktop.

Select an option

Save thekid/67925df18d5015a85a10 to your computer and use it in GitHub Desktop.
Query class
<?php
use lang\Throwable;
use util\profiling\Timer;
use rdbms\DriverManager;
use rdbms\ResultSet;
use io\streams\Streams;
use io\streams\TextWriter;
/**
* Performs an SQL query
*/
class Query extends \util\cmd\Command {
protected $connection= null;
protected $queries= [];
protected $ouput;
/**
* Set dsn (e.g. mysqlx://user:pass@host[:port])
*
* @param string dsn
*/
#[@arg(position= 0)]
public function setConnection($dsn) {
$this->connection= DriverManager::getConnection($dsn);
$this->connection->connect();
$this->err->writeLine('C: ', $this->connection);
}
/**
* Set SQL query
*
* @param string query
*/
#[@args(select= '[1..]')]
public function setQueries($queries) {
foreach ($queries as $query) {
if ('-' === $query) {
$this->queries[]= Streams::readAll($this->in->getStream());
} else if ('-' !== $query{0}) {
$this->queries[]= $query;
}
}
}
/**
* Set output (either "csv" or "dump")
*
* @param string format
*/
#[@arg]
public function setOutput($format= 'dump') {
if ('csv' === $format) {
$this->output= function($q) {
$headers= [];
foreach ($q->fields as $field) {
$headers[]= $field['name'];
}
$writer= new \text\csv\CsvMapWriter(new TextWriter($this->out->getStream()));
$writer->setHeaders($headers);
while ($r= $q->next()) {
$writer->write($r);
}
};
} else {
$this->output= function($q) {
$i= 0;
while ($r= $q->next()) {
$this->out->writeLine(++$i, ': ', $r);
}
};
}
}
/**
* Main runner method
*/
public function run() {
$t= new Timer();
foreach ($this->queries as $query) {
$this->err->writeLine('Q: ', $query);
$t->start();
try {
$q= $this->connection->query($query);
if ($q instanceof ResultSet) {
call_user_func($this->output, $q);
} else {
$this->out->writeLine(typeof($q), ': ', $q);
}
} catch (Throwable $e) {
$this->err->writeLine($e);
}
$t->stop();
$this->err->writeLinef('%.3f seconds', $t->elapsedTime());
}
}
/**
* Destructor. Closes communications.
*/
public function __destruct() {
$this->connection && $this->connection->close();
}
}
@thekid
Copy link
Author

thekid commented Jul 25, 2014

Usage:

$ xpcli Query 'driver://user:pass@host/DATABASE' 'select ...' --output=csv

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment