class Csvql::TableHandler
Public Class Methods
new(path, console)
click to toggle source
# File lib/csvql/csvql.rb, line 9 def initialize(path, console) @db_file = if path && path.strip.size > 0 path elsif console @tmp_file = Tempfile.new("csvql").path else ":memory:" end @db = SQLite3::Database.new(@db_file) end
Public Instance Methods
create_alias(table, view="tbl")
click to toggle source
# File lib/csvql/csvql.rb, line 27 def create_alias(table, view="tbl") return if table == view exec "DROP VIEW IF EXISTS #{view}" exec "CREATE VIEW #{view} AS SELECT * FROM #{table}" end
create_table(schema, table_name="tbl")
click to toggle source
# File lib/csvql/csvql.rb, line 20 def create_table(schema, table_name="tbl") @col_name = schema.split(",").map {|c| c.split.first.strip } @col_size = @col_name.size @table_name = table_name exec "CREATE TABLE IF NOT EXISTS #{@table_name} (#{schema})" end
drop_table(table_name="tbl")
click to toggle source
# File lib/csvql/csvql.rb, line 33 def drop_table(table_name="tbl") exec "DROP TABLE IF EXISTS #{table_name}" end
exec(sql)
click to toggle source
# File lib/csvql/csvql.rb, line 51 def exec(sql) @db.execute(sql) end
insert(cols, line)
click to toggle source
# File lib/csvql/csvql.rb, line 42 def insert(cols, line) if cols.size != @col_size puts "line #{line}: wrong number of fields in line (skipping)" return end @pre ||= prepare(cols) @pre.execute(cols) end
open_console()
click to toggle source
# File lib/csvql/csvql.rb, line 55 def open_console system("sqlite3", @db_file) File.delete(@tmp_file) if @tmp_file end
prepare(cols)
click to toggle source
# File lib/csvql/csvql.rb, line 37 def prepare(cols) sql = "INSERT INTO #{@table_name} (#{@col_name.join(",")}) VALUES (#{cols.map{"?"}.join(",")});" @pre = @db.prepare(sql) end