SQL::Shell(3)
π SQL::Shell π
ok bestie, welcome to SQL::Shell β a command interpreter for DBI shells, straight out of your friendly neighbourhood Perl docs. This is the part where I tell you everything, so grab a boba and let's go π§β¨
β¨ NAME β¨
SQL::Shell β command interpreter for DBI shells. that's it, that's the vibe. π
β¨ SYNOPSIS β¨
use SQL::Shell;
#Initialise and configure
my $sqlsh = new SQL::Shell(\%settings);
$sqlsh->set($setting, $new_value);
$value = $sqlsh->get($setting);
#Interpret commands
$sqlsh->execute_command($command);
$sqlsh->run_script($filename);
β¨ DESCRIPTION β¨
so SQL::Shell is a command-interpreter API for building shells and batch scripts. it's giving framework energy, not just a lil script. π
and here's the tea: a command-line interface with readline support β sqlsh.pl β is included as part of the CPAN distribution. also, go read SQL::Shell::Manual for a user guide. it's the companion piece, the main character's bestie, iykyk. π«Ά
SQL::Shell offers features similar to the mysql or sql*plus client programs but it's database independent. the default command syntax is arguably more user-friendly than dbish β no cap β because you don't need any go, do or slashes to fire SQL statements at the database. you just... type them. iconic behaviour honestly. π₯
Features include:
- issuing common SQL statements by simply typing them
- command history
- listing drivers, datasources, tables
- describing a table or the entire schema
- dumping and loading data to/from delimited text files
- character set conversion when loading data
- logging of queries, results or all commands to file
- a number of formats for display/logging data (sql, xml, delimited, boxed)
- executing a series of commands from a file
You can also install custom commands, rendering formats and command history mechanisms. All the commands run by the interpreter are available via the API so if you don't like the default command syntax you can replace the command regexes with your own. it's your shell now, you can customise the whole wardrobe. π
It's been developed and used in anger with Oracle and mysql but should work with any database with a DBD:: driver. any database. periodt. π
β¨ METHODS β¨
$sqlsh = new SQL::Shell(\%settings);β Constructs a new object and initialises it with a set of settings. See "SETTINGS" for a complete list. (we're building the whole personality here, bestie πΈ)$sqlsh->set($setting, $new_value)β Changes a setting once the object has been constructed. See "SETTINGS" for a complete list.$value = $sqlsh->get($setting)β Fetches a setting. See "SETTINGS" for a complete list. β¨
π Commands π
$sqlsh->execute_cmd($command)β Executes a command ($commandis a string).
Returns 1 if the command was successful. Returns 0 if the command was unsuccessful. so it's a lil pass/fail, very honest of it. π―
$sqlsh->run_script($filename)β Executes a sequence of commands in a file. Dies if there is a problem. π (fr, it dies, so keep an eye on it)$sqlsh->install_cmds(\%additional_commands)β%additional_commandsshould contain a mapping of regex to coderef. See "INSTALLING CUSTOM COMMANDS" for more information.$sqlsh->uninstall_cmds(\@commands)β@additional_commandsshould contain a list of regexes to remove. Ifuninstall_cmdsis called with no arguments, all commands will be uninstalled. bye bye commands π$sqlsh->set_param($param, $value)β Equivalent to theset <param> <value>command. In many cases this will affect the internal settings accessible through thesetandgetmethods.
πΈ Renderers πΈ
$sqlsh->install_renderers(\%additional_renderers)β%additional_renderersshould contain a mapping of renderer name to coderef. See "INSTALLING CUSTOM RENDERERS" for more information.$sqlsh->uninstall_renderers(\@renderers)β@renderersshould contain a list of renderer names to remove. Ifuninstall_renderersis called with no arguments, all renderers will be uninstalled.$sqlsh->render_rowset(\@headers, \@data, $table)β Calls the current renderer (writes toSTDOUT)$sqlsh->log_rowset(\@headers, \@data, $table)β Calls the current logger
π¦ Database connection π¦
$dsn = $sqlsh->connect($dsn, $user, $pass)β Connects to a DBI datasource. Equivalent to issuing theconnect $dsn $user $passcommand.$sqlsh->disconnect()β Disconnects if connected. Equivalent to issuing thedisconnectcommand.$bool = $sqlsh->is_connected()β Check if we're connected to the database. vibe check on the connection π$string = $sqlsh->dsn()β The datasource we're currently connected as βundefif not connected.
π History manipulation π
$arrayref = $sqlsh->load_history($filename)β Loads a sequence of commands from a file into the command history. Equivalent toload history from $filename.$sqlsh->clear_history()β Clears the command history. Equivalent toclear history. (the past? gone. we don't know her.)$sqlsh->save_history($filename, $size)β Saves the command history to a file in a format suitable forload_historyandrun_script. Equivalent tosave history to $filename, except the maximum number of items can be specified.$sizeis optional β if not specified defaults to theMaxHistorysetting.$sqlsh->show_history()β Displays the command history. Equivalent toshow history.
π Logging π
$sqlsh->enable_logging($level, $file)β Enables logging to a file.$levelshould beall,queriesorcommands. Equivalent tolog $level $file.$sqlsh->disable_logging()β Disables logging to a file. Equivalent tono log.
β Querying β
$sqlsh->show_drivers()β Outputs a list of database drivers. Equivalent toshow drivers.$sqlsh->show_datasources($driver)β Outputs a list of datasources for a driver. Equivalent toshow datasources $driver.$sqlsh->show_dbh($property)β Outputs a property of a database handle. Equivalent toshow \$dbh $property.$sqlsh->show_schema()β Equivalent toshow schema.$sqlsh->show_objects()β Displays a list of tables, schemas, catalogs or table-types depending on the object argument passed.$sqlsh->show_tablecounts()β Displays a list of tables with row counts. Equivalent toshow tablecounts.$sqlsh->show_settings()β Displays a list of internalsqlshsettings. Equivalent toshow settings. Not all internal settings are included here yet. (it's a work in progress bestie, be patient π«Ά)$sqlsh->describe($table)β Displays the columns in the table. Equivalent todescribe $table.$sqlsh->run_query($sql)β Displays the rowset returned by the query. Equivalent toexecute_cmdwith aselectorexplainstatement.
π₯ Modifying data π₯
$sqlsh->do_sql($sql)β Executes a SQL statement that modifies the database. Equivalent toexecute_cmdwith a DML or DDL statement.$sqlsh->begin_work()β Starts a transaction. Equivalent tobegin work.$sqlsh->commit()β Commits a transaction. Equivalent tocommit. slay, locked in π$sqlsh->rollback()β Rolls back a transaction. Equivalent torollback. not me undoing everything π$sqlsh->wipe_tables()β Blanks all the tables in the database. Will prompt for confirmation if theInteractivesetting is enabled. Equivalent towipe tables.
β οΈ okay sowipe_tablesBLANKS ALL THE TABLES IN THE DATABASE. that is a lot of power in one method name. the prompt only shows up if theInteractivesetting is enabled, so please, for the love of everything, know what you're doing here. π
π Loading and dumping data π
$sqlsh->dump_data($source, $filename, $delimiter)β Dumps data from a table or query into a delimited file.$sourceshould either be a table name or aselectquery. This is equivalent to thedump datacommand.$sqlsh->load_data($filename, $table, $delimiter, $uri_decode, $charset_from, $charset_to)β Loads data from a delimited file into a database table.$uri_decodeis a boolean value β if true the data will be URI-decoded before being inserted.$charset_fromand$charset_toare character set names understood byLocale::Recode. This is equivalent to theload datacommand.$sqlsh->show_charsets()β Lists the character sets supported by the recoding feature ofload data. Equivalent toshow charsets.
β¨ CUSTOMISING β¨
π§ INSTALLING CUSTOM COMMANDS π§
The coderef will be passed the $sqlsh object followed by each argument captured by the regex.
my %additional_commands = (
qr/^hello from (\.*)/ => sub {
my ($self, $name) = @_;
print "hi there $name\n";
});
To install this:
$sqlsh->install_cmds(\%additional_commands)
Then in sqlsh:
> hello from John
hi there John
see?? you literally taught it manners. we love a polite shell. π«Άβ¨
π INSTALLING CUSTOM RENDERERS π
Renderers are coderefs which are passed the following arguments:
$sqlsh - the SQL::Shell object
$fh - the filehandle to render to
$headers - an arrayref of column headings
$data - an arrayref of arrays containing the data (row major)
$table - the name of the table being rendered (not defined in all contexts)
Here's an example to render data in CSV format:
sub my_renderer {
my ($sqlsh, $fh, $headers, $data, $table) = @_;
my $delim = ",";
print $fh "#Dump of $table" if($table); #Assuming our CSV format support #-style comments
print $fh join($delim, @$headers)."\n";
foreach my $row (@$data)
{
print $fh join($delim, @$row)."\n";
}
}
To install this:
$sqlsh->install_renderers({'csv' => \&my_renderer});
Then in sqlsh:
> set display-mode csv
and boom, csv era begins. ππ
π¦ INSTALLING A CUSTOM HISTORY MECHANISM π¦
You can install a custom history recording mechanism by overriding the GetHistory, SetHistory and AddHistory callbacks which should take the following arguments and return values:
$arrayref = $GetHistorySub->()
$SetHistorySub->($arrayref)
$AddHistorySub->($string)
An example:
my $term = new Term::ReadLine "My Shell";
my $autohistory = $term->Features()->{autohistory};
my $sqlsh = new SQL::Shell({
'GetHistory' => sub {[$term->GetHistory()]});
'SetHistory' => sub {my $history = shift; $term->SetHistory(@$history)});
'AddHistory' => sub {my $cmd = shift; $term->addhistory($cmd) if !$autohistory});
});
look at that. custom history, custom everything. main character energy fr. π
β¨ SETTINGS β¨
okay so these first ones? they can only be set through the constructor or the set method, no cap:
GetHistoryβ Callback to fetch history. Default:sub {return \@history}SetHistoryβ Callback to set history. Default:sub {my $n = shift; @history = @$n}AddHistoryβ Callback to add cmd to history. Default:sub {push @history, shift()}MaxHistoryβ Maximum length of history to save. Default:$ENV{HISTSIZE} || $ENV{HISTFILESIZE} || 50Interactiveβ Should SQL::Shell ask questions? Default:0Verboseβ Should SQL::Shell print messages? Default:0NULLβ How to display null values. Default:NULL
the next batch is also affected by the set_param method or the set command:
Rendererβ Current renderer for screen. Default:\&_render_boxLoggerβ Current renderer for logfile. Default:\&_render_delimitedDelimiterβ Delimiter for delimited format. Default:\tWidthβ Width used for record display. Default:80LogLevelβ Log what?all|commands|queries. Default:undefEscapeStrategyβUriEscape|EscapeWhitespace|ShowWhitespace. Default:undefAutoCommitβ Commit each statement. Default:0LongTruncOkβ OK to truncateLONGdatatypes? Default:1LongReadLenβ Amount read fromLONGdatatypes. Default:512MultiLineβ Allows multiline sql statements. Default:0
π COMMANDS π
bestie, here's the whole command menu β every single one, fr fr:
show driversshow datasources <driver>connect <dsn> [<user> <pass>]β connect to DBI DSNdisconnectβ disconnect from the DBshow tablesβ display a list of tablesshow catalogsβ display a list of catalogsshow schemasβ display a list of schemasshow tabletypesβ display a list of tabletypesshow schemaβ display the entire schemashow settingsβ display some internal settingsdesc <table>β display schema of tableshow $dbh <attribute>β show a database handle object. some examples:show $dbh Nameshow $dbh LongReadLenshow $dbh mysql_serverinfo(mysql only)
set display-mode delimited|spaced|box|record|sql|xmlβ query display modeset log-mode delimited|spaced|box|record|sql|xmlβ set the query log modeset delimiter <delim>β set the column delimiter (default is tab)set escape show-whitespace|escape-whitespace|uri-escape|offshow-whitespaceis just for looking atescape-whitespaceis compatible withenter-whitespaceuri-escapeis compatible withuri-decode(loadcommand)
set enter-whitespace on|offβ allow\r\nand\tin SQL statementsset uri-encode on|offβ allow all non ascii characters to be escapedset auto-commit on|offβ commit after every statement (default is OFF)set longtruncok on|offβ SeeDBI/LongTruncOk(default is on)set longreadlen <int>β SeeDBI/LongReadLen(default is 512)set multiline on|offβ multiline statements ending in;(default is off)set tracing on|off|deepβ debug sqlsh usingLog::Trace(default is off)log (queries|commands|all) <filename>β start logging to<filename>no logβ stop loggingselect ...insert ...update ...create ...alter ...drop ...grant ...revoke ...begin_workcommitrollbacksend ...recv ...load <file> into <table> (delimited by foo) (uri-decode) (from bar to baz)- load delimited data from a file
- use
uri-decodeif file includes uri-encoded data from,tocan take character set to recode data e.g. fromCP1252toUTF-8
show charsetsβ display available character setsdump <table> into <file> (delimited by foo)β dump delimited datadump <sql> into <file> (delimited by foo)β dump delimited datadump all tables into <directory> (delimited by foo)β dump delimited datawipe tablesβ remove all data from DB (leaving tables empty)show historyβ display command historyclear historyβ erases the command historysave history to <file>β saves the command historyload history from <file>β loads the command historyexecute <file>β run a set of SQL or sqlsh commands from a file
β VERSION β
Version 1.18 β slay.
π AUTHOR π
John Alden with contributions by Simon Flack and Simon Stevenson <cpan _at_ bbc _dot_ co _dot_ uk>
Miguel Gualdron maintainer.
π COPYRIGHT π
okay legal bestie moment, here's the whole copyright + license, no cap:
SQL-Shell: Interactive shell for DBI Databases Copyright (C) 2006 BBC Copyright (C) 2019 Miguel Gualdron This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
See the file COPYING in this distribution, or https://www.gnu.org/licenses/gpl-2.0.html
and that's the whole vibe π
this page came from perl v5.42.0, dated 2025-12-05, and it's the SQL::Shell(3) manpage. go forth and query, bestie π¦β¨
π¦ where this page comes from
- fedora 43: perl-SQL-Shell 1.18-1.fc43 Β· GPL-2.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms