From 53e07ff4b5e9c11363a88337a9f45b88b8295361 Mon Sep 17 00:00:00 2001 From: Samer Abukhait Date: Thu, 17 Nov 2011 13:11:27 -0800 Subject: [PATCH] Add db2 keywords to autocomplete list, use rlwrap goodies Wrap db2 command mode in a repl --- .gitignore | 1 + README.md | 2 + Rakefile | 2 +- bin/ac | 540 ++++++++++++++++++++++++++++++++++++++++++++ bin/db2c | 24 +- db2c.gemspec | 34 +-- lib/db2c.rb | 6 + lib/db2c/command.rb | 52 +++++ lib/db2c/version.rb | 3 - man/db2c.1 | 30 +-- man/db2c.1.html | 32 +-- man/db2c.1.ronn | 30 +-- 12 files changed, 663 insertions(+), 93 deletions(-) create mode 100644 .gitignore create mode 100644 bin/ac create mode 100644 lib/db2c.rb create mode 100644 lib/db2c/command.rb delete mode 100644 lib/db2c/version.rb diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4921bd3 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +db2c*.gem diff --git a/README.md b/README.md index 32f95b1..286136f 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ Once you've made your great commits: Acknowledgement ------------ +Chris Jester-Young ([CKY][4]) found out the problem of using shell metacharacters when executing commands from Ruby. The initial script was inspired by [defunkt's repl][3], for a genenral purpose repl/wrapper, this is your friend. Meta @@ -42,3 +43,4 @@ Samer Abukhait , @s4mer [1]: http://help.github.com/forking/ [2]: https://github.com/on-site/db2c/issues [3]: https://github.com/defunkt/repl +[4]: https://github.com/cky diff --git a/Rakefile b/Rakefile index 342547f..5575071 100644 --- a/Rakefile +++ b/Rakefile @@ -1,5 +1,5 @@ $LOAD_PATH.unshift 'lib' -require "db2c/version" +require "db2c" def version Db2c::VERSION diff --git a/bin/ac b/bin/ac new file mode 100644 index 0000000..4d306dd --- /dev/null +++ b/bin/ac @@ -0,0 +1,540 @@ +absolute +access +action +activate +ada +add +after +alias +all +allocate +allow +alter +alterin +always +and +any +append +asc +ascii +assertion +assignment +associate +asutime +atomic +attributes +authorization +authid +automatic +avg +before +begin +between +bigint +binary +bind +bindadd +bit +bit_length +blob +blocked +both +bufferpool +cache +call +called +caller +capture +cardinality +cascade +cascaded +case +cast +catalog +catalog_name +change +char +char_length +character +character_length +check +checked +class_origin +client +clob +close +cluster +cobol +cobolle +collate +collation +collect +collid +column +column_name +command_function +comment +commit +committed +comparisons +concat +condition +condition_number +connect +connection +connection_name +conservative +constraint +constraint_catalog +constraint_name +constraint_schema +constraints +contains +continue +control +convert +copy +correlation +corr +corresponding +count +count_big +create +cross +cube +current +current_date +current_path +current_schema +current_server +current_sqlid +current_time +current_timestamp +current_timezone +current_user +cursor +cursors +cursor_name +cycle +date +data +database +datalink +day +days +dbadm +dbclob +dbinfo +db2dari +db2genrl +db2general +db2options +db2sql +deadlocks +deallocate +dec +decimal +declare +default +defaults +define +definition +degree +deferrable +deferred +delete +desc +describe +descriptor +deterministic +diagnostics +dimensions +disable +disallow +disconnect +dispatch +distinct +domain +do +double +drop +dropin +dynamic +dynamic_function +each +ebcdic +else +elseif +enable +end +end-exec +erase +escape +eur +event +exact +except +exception +exclude +excluding +exclusive +exec +execute +exists +exit +explain +extension +external +extract +false +federated +fenced +fetch +file +final +first +float +flush +following +for +force +foreign +fortran +found +from +fs +full +function +general +generated +get +global +goto +grant +graphic +group +grouping +handler +having +hold +hour +hours +identity +immediate +implicit_schema +include +including +increment +index +indicator +inherit +initially +initial_insts +initial_ios +inner +inout +input +insensitive +insert +instead +insts_per_argbyte +insts_per_invoc +int +integer +integrity +intersect +interval +into +ios_per_argbyte +ios_per_invoc +iso +iterate +isolation +java +jis +join +key +language +large +last +leading +leave +left +length +level +like +limit +link +linktype +load +local +locator +locators +lock +locks +locksize +logged +long +longvar +loop +lower +maintained +mapping +match +max +maxvalue +message_length +message_octet_length +message_text +method +microsecond +microseconds +minute +minutes +minvalue +mode +modifies +module +monitor +month +months +more +named +names +national +natural +nchar +new +new_table +next +nextval +nickname +nocache +nocycle +node +nomaxvalue +nominvalue +none +noorder +not +null +nullable +nulls +number +numeric +octet_length +object +off +old +old_table +ole +oledb +once +online +only +open +optimization +optimize +option +or +order +out +outer +output +over +overlaps +package +pad +partial +parallel +parameter +pascal +passthru +password +path +partition +partitioning +pctfree +percent_argbytes +permission +piecesize +pipe +plan +pli +position +preceding +precision +prepare +preserve +primary +prior +priqty +privileges +procedure +program +public +query +queryno +range +read +reads +real +recommend +recovery +ref +reference +references +referencing +refresh +registers +relative +release +rename +repeatable +repeat +rpg +rpgle +replace +replicated +reset +resignal +resolve +restart +restore +restrict +result +result_set_locator +returned_sqlstate +retain +return +returns +return_status +revoke +right +rollback +rollup +routine +row +row_count +rowid +rows +run +savepoint +sbcs +scale +schema +schema_name +scope +scratchpad +scroll +search +second +seconds +secqty +section +select +self +sequence +serializable +server +server_name +session +session_user +set +sets +share +signal +simple +size +smallint +snapshot +some +source +space +specific +sql +sqlcode +sqlerror +sqlexception +sqlwarning +sqlid +sqlstate +start +state +statement +statistics +stay +stogroup +storage +style +subclass_origin +substring +summary +switch +synonym +system +system_user +table +tables +table_name +tablespace +tablespaces +temporary +then +threadsafe +time +timestamp +timezone +timezone_hour +timezone_minute +to +trailing +transaction +transform +translate +translation +treat +trigger +trim +true +type +unbounded +uncommitted +under +undo +unicode +union +unique +unknown +unlink +until +update +upper +url +usa +use +usage +user +using +value +values +varchar +vargraphic +variant +varying +vcat +version +view +when +whenever +where +while +with +without +work +wrapper +write +year +years +yes +zone diff --git a/bin/db2c b/bin/db2c index 39e4f9b..de578f7 100644 --- a/bin/db2c +++ b/bin/db2c @@ -5,7 +5,7 @@ if !system("which db2 > /dev/null 2> /dev/null") exit end -if !system("which rlwrap > /dev/null 2> /dev/null") +if !ARGV.include?('--no-rlwrap') && !system("which rlwrap > /dev/null 2> /dev/null") puts "This program depends on rlwrap, install rlwrap" exit end @@ -32,4 +32,24 @@ if ARGV.include? '--man' exec "man #{cdir}/../man/db2c.1" end -exec "rlwrap -A -pblue -f #{cdir}/ac -H ~/.db2c_history db2 #{ARGV.join(' ')}" +unless ARGV.include? '--no-rlwrap' + exec "rlwrap -z pipeto -i -r -s 999999 -pBLUE -f #{cdir}/ac -H ~/.db2c_history db2c --no-rlwrap #{ARGV.join(' ')}" +end + +$LOAD_PATH.unshift 'lib' +require "db2c" + +Db2c::Command.debug = ARGV.any? { |arg| %w( -d --debug -debug debug ).include?(arg) } + +loop do + print Db2c::Command.prompt + + begin + command = Db2c::Command.new $stdin.gets + rescue Interrupt + exit + end + + exit if command.quit? + command.execute +end diff --git a/db2c.gemspec b/db2c.gemspec index 32dd3af..1cc0dbc 100644 --- a/db2c.gemspec +++ b/db2c.gemspec @@ -1,20 +1,20 @@ -$LOAD_PATH.unshift 'lib' -require "db2c/version" +# -*- encoding: utf-8 -*- +lib = File.expand_path('../lib/', __FILE__) +$:.unshift lib unless $:.include?(lib) -Gem::Specification.new do |s| - s.name = "db2c" - s.version = Db2c::VERSION - s.date = Time.now.strftime('%Y-%m-%d') - s.summary = "a db2 console with with history and autocomplete support" - s.description = "a db2 console with with history and autocomplete support" - s.homepage = "http://github.com/on-site/db2c" - s.email = "samer@on-siteNOSPAM.com" - s.authors = [ "Samer Abukhait" ] - s.has_rdoc = false - - s.files = %w( README.md Rakefile LICENSE ) - s.files += Dir.glob("bin/**/*") - s.files += Dir.glob("man/**/*") +require 'db2c' - s.executables = %w( db2c ) +Gem::Specification.new do |s| + s.name = "db2c" + s.version = Db2c::VERSION + s.platform = Gem::Platform::RUBY + s.date = Time.now.strftime('%Y-%m-%d') + s.summary = "a db2 console with with history and autocomplete support" + s.description = "This program wraps db2 command mode with a repl, and wraps that repl with rlwrap" + s.homepage = "http://github.com/on-site/db2c" + s.email = "samer@on-siteNOSPAM.com" + s.authors = ["Samer Abukhait"] + s.files = Dir.glob("{bin,lib,man}/**/*") + %w(LICENSE README.md Rakefile) + s.executables = ['db2c'] + s.require_path = 'lib' end diff --git a/lib/db2c.rb b/lib/db2c.rb new file mode 100644 index 0000000..5798115 --- /dev/null +++ b/lib/db2c.rb @@ -0,0 +1,6 @@ +module Db2c + DEFAULT_PROMPT = "db2c => " + VERSION = "0.0.2" +end + +require "db2c/command.rb" diff --git a/lib/db2c/command.rb b/lib/db2c/command.rb new file mode 100644 index 0000000..1b9952e --- /dev/null +++ b/lib/db2c/command.rb @@ -0,0 +1,52 @@ +module Db2c + class Command + + @@cdb = '' + @@debug = false + + def initialize input + if input + puts "initializing: #{input}" if @@debug + @input = input.chomp.strip + @input.gsub! /^db2 /i, '' + @input.gsub! /;$/, '' + @input.gsub! /^use /, 'connect to ' + @input.insert 0, "? sql" if @input =~ /^\-\d+$/ + @input.insert 0, "? " if @input =~ /^\d+$/ + @input.insert 0, "values " if @input =~ /^current.+$/i + end + end + + def to_s + @input + end + + def quit? + @input.nil? || @input =~ /^(exit|quit)$/ + end + + def valid? + @input && @input.length > 0 + end + + def execute + puts "executing: #{@input}" if @@debug + system 'db2', @input if valid? + if @input =~ /^connect to (.*)$/i + @@cdb = $1.downcase + end + end + + def self.debug=(value) + @@debug = value + end + + def self.prompt + "db2c".tap do |pr| + pr << "(#{@@cdb})" if @@cdb.length > 0 + pr << " => " + end + end + + end +end diff --git a/lib/db2c/version.rb b/lib/db2c/version.rb deleted file mode 100644 index 03152f0..0000000 --- a/lib/db2c/version.rb +++ /dev/null @@ -1,3 +0,0 @@ -module Db2c - VERSION = "0.0.1" -end diff --git a/man/db2c.1 b/man/db2c.1 index 2c8d0b5..a8319a6 100644 --- a/man/db2c.1 +++ b/man/db2c.1 @@ -18,31 +18,15 @@ DB2 console mode does not support readline and autocomplete, this is a wrapper f $ db2c db2 => connect to testdb +or: db2 => use testdb +db2 => current date +db2 => \-107 -Database Connection Information +Use the arrows for history, you can also use \-r to search the history -Database server = DB2/LINUXX8664 9\.7\.4 -SQL authorization ID = SAMER -Local database alias = TESTDB - -db2 => ? sql\-107 - - -SQL0107N The name "" is too long\. The maximum length is - ""\. - -\.\.\. - -db2 => values current date - -1 -\-\-\-\-\-\-\-\-\-\- -11/17/2011 - - 1 record(s) selected\. - - -Then use the arrows for history +You can pipe: +db2 => select * from large\.table | less +db2 => select * from large\.table | grep something . .fi . diff --git a/man/db2c.1.html b/man/db2c.1.html index 14d775d..668732e 100644 --- a/man/db2c.1.html +++ b/man/db2c.1.html @@ -86,31 +86,15 @@

EXAMPLES

$ db2c
 db2 => connect to testdb
+or: db2 => use testdb
+db2 => current date
+db2 => -107
 
-Database Connection Information
+Use the arrows for history, you can also use <CTRL>-r to search the history
 
-Database server        = DB2/LINUXX8664 9.7.4
-SQL authorization ID   = SAMER
-Local database alias   = TESTDB
-
-db2 => ? sql-107
-
-
-SQL0107N  The name "<name>" is too long. The maximum length is
-      "<length>".
-
-...
-
-db2 => values current date
-
-1         
-----------
-11/17/2011
-
-  1 record(s) selected.
-
-
-Then use the arrows for history
+You can pipe:
+db2 => select * from large.table | less
+db2 => select * from large.table | grep something
 

OPTIONS

@@ -127,7 +111,7 @@

BUGS

AUTHOR

-

Samer Abukhait samer@on-siteNOSPAM.com, @s4mer

+

Samer Abukhait samer@on-siteNOSPAM.com, @s4mer

SEE ALSO

diff --git a/man/db2c.1.ronn b/man/db2c.1.ronn index c36dc45..09b9c64 100644 --- a/man/db2c.1.ronn +++ b/man/db2c.1.ronn @@ -13,31 +13,15 @@ DB2 console mode does not support readline and autocomplete, this is a wrapper f $ db2c db2 => connect to testdb + or: db2 => use testdb + db2 => current date + db2 => -107 - Database Connection Information + Use the arrows for history, you can also use -r to search the history - Database server = DB2/LINUXX8664 9.7.4 - SQL authorization ID = SAMER - Local database alias = TESTDB - - db2 => ? sql-107 - - - SQL0107N The name "" is too long. The maximum length is - "". - - ... - - db2 => values current date - - 1 - ---------- - 11/17/2011 - - 1 record(s) selected. - - - Then use the arrows for history + You can pipe: + db2 => select * from large.table | less + db2 => select * from large.table | grep something ## OPTIONS