Skip to content

Instantly share code, notes, and snippets.

@thekid
Last active July 23, 2016 18:19
Show Gist options
  • Save thekid/ae35fc4555252938dcea43cf135b5adf to your computer and use it in GitHub Desktop.
Save thekid/ae35fc4555252938dcea43cf135b5adf to your computer and use it in GitHub Desktop.
ISQL
<?php namespace isql;
use rdbms\DriverManager;
use rdbms\SQLException;
use rdbms\SQLConnectException;
use rdbms\SQLConnectionClosedException;
use util\cmd\Console;
use util\profiling\Timer;
const PROMPT = "\e[31;1m\$u@\$h \e[36;1m\$d\e[0m [\e[32;1m%s\e[0m]\n\$";
$timer= new Timer();
$timer->start();
$conn= DriverManager::getConnection($argv[1]);
try {
$conn->connect();
} catch (SQLConnectException $e) {
Console::writeLine("\e[31m*** ", $e->compoundMessage(), "\e[0m");
return 1;
}
Console::writeLinef("\e[32m@%s - (%.2f sec)\e[0m", $conn->toString(), $timer->elapsedTime());
Console::writeLine('Type "exit" to end shell');
Console::writeLine();
$dsn= $conn->getDSN();
$prompt= strtr(PROMPT, ['$u' => $dsn->getUser(), '$h' => $dsn->getHost(), '$d' => $db= $dsn->getDatabase()]);
while (null !== ($sql= Console::readLine(sprintf($prompt, $conn->hashCode())))) {
$sql= trim($sql, '; ');
if ('' === $sql) {
continue;
} else if ('exit' === $sql) {
break;
} else if (1 === sscanf($sql, 'use %s', $use)) {
try {
$conn->selectdb($use);
$prompt= strtr(PROMPT, ['$u' => $dsn->getUser(), '$h' => $dsn->getHost(), '$d' => $db= $use]);
Console::writeLine();
} catch (SQLException $e) {
Console::writeLine("\e[31m*** ", $e->compoundMessage(), "\e[0m");
}
continue;
}
query: try {
$timer->start();
$q= $conn->query($sql);
if ($q->isSuccess()) {
Console::writeLinef('Query OK, %d rows affected (%.2f sec)', $q->affected(), $timer->elapsedTime());
} else {
$rows= 0;
while ($record= $q->next()) {
Console::writeLine($record);
$rows++;
}
Console::writeLinef('%d rows in set (%.2f sec)', $rows, $timer->elapsedTime());
}
$q->close();
Console::writeLine();
} catch (SQLConnectionClosedException $e) {
Console::writeLine("\e[31mConnection cosed ('", $e->getMessage(), "'), reconnecting...\e[0m");
$conn->close();
$conn->connect();
$conn->selectdb($db);
goto query;
} catch (SQLException $e) {
Console::writeLine("\e[31m*** ", $e->compoundMessage(), "\e[0m");
}
}
$conn->close();
Console::writeLine();
return 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment