Class: Knj::Db
Overview
A wrapper of several possible database-types.
Examples
db = Knj::Db.new(:type => “mysql”, :subtype => “mysql2”, :db => “mysql”, :user => “user”, :pass => “password”) mysql_table = db.tables name = mysql_table.name cols = mysql_table.columns
db = Knj::Db.new(:type => “sqlite3”, :path => “some_db.sqlite3”)
db.q(“SELECT * FROM users”) do |data|
print data[:name]
end
Defined Under Namespace
Classes: Dbtime, Dump, Idquery, Query_buffer, Revision, Sqlspecs
Instance Attribute Summary collapse
-
#conn ⇒ Object
readonly
Returns the value of attribute conn.
-
#conns ⇒ Object
readonly
Returns the value of attribute conns.
-
#int_types ⇒ Object
readonly
Returns the value of attribute int_types.
-
#opts ⇒ Object
readonly
Returns the value of attribute opts.
-
#sep_col ⇒ Object
readonly
Returns the value of attribute sep_col.
-
#sep_table ⇒ Object
readonly
Returns the value of attribute sep_table.
-
#sep_val ⇒ Object
readonly
Returns the value of attribute sep_val.
Class Method Summary collapse
-
.const_missing(name) ⇒ Object
Autoloader for subclasses..
Instance Method Summary collapse
- #args ⇒ Object
-
#clean ⇒ Object
Clean up various memory-stuff if possible.
-
#clone_conn(args = {}) ⇒ Object
Clones the current database-connection with possible extra arguments.
-
#cloned_conn(args = nil, &block) ⇒ Object
Clones the connection, executes the given block and closes the connection again.
-
#close ⇒ Object
The all driver-database-connections.
-
#cols ⇒ Object
Returns the columns-module and spawns it if it isnt already spawned.
-
#conn_exec ⇒ Object
Returns a driver-object based on the current thread and free driver-objects.
-
#connect ⇒ Object
Actually connects to the database.
-
#copy_to(db, args = {}) ⇒ Object
Copies the content of the current database to another instance of Knj::Db.
-
#data ⇒ Object
Returns the data of this database in a hash.
-
#date_in(date_obj) ⇒ Object
Takes a valid date-db-string and converts it into a Datet.
-
#date_out(date_obj = Datet.new, args = {}) ⇒ Object
Returns a string which can be used in SQL with the current driver.
-
#delete(tablename, arr_terms, args = nil) ⇒ Object
Deletes rows from the database.
-
#esc_col(str) ⇒ Object
Escapes the given string to be used as a column.
-
#esc_table(str) ⇒ Object
Escapes the given string to be used as a table.
-
#escape(string) ⇒ Object
(also: #esc)
Escapes a string to be safe-to-use in a query-string.
-
#free_thread ⇒ Object
Frees the current driver from the current thread.
-
#get_and_register_thread ⇒ Object
Registers a driver to the current thread.
-
#indexes ⇒ Object
Returns the index-module and spawns it if it isnt already spawned.
-
#initialize(opts) ⇒ Db
constructor
A new instance of Db.
-
#insert(tablename, arr_insert, args = nil) ⇒ Object
Simply inserts data into a table.
-
#insert_multi(tablename, arr_hashes, args = nil) ⇒ Object
Simply and optimal insert multiple rows into a table in a single query.
-
#lastID ⇒ Object
(also: #last_id)
Returns the last inserted ID.
-
#makeWhere(arr_terms, driver = nil) ⇒ Object
Internally used to generate SQL.
-
#method_missing(method_name, *args) ⇒ Object
Proxies the method to the driver.
-
#optimize(args = nil) ⇒ Object
Optimizes all tables in the database.
-
#q(str, args = nil, &block) ⇒ Object
Executes a query and returns the result.
-
#q_buffer(&block) ⇒ Object
Yields a query-buffer and flushes at the end of the block given.
-
#query(string) ⇒ Object
Executes a query and returns the result.
-
#query_ubuf(string, &block) ⇒ Object
Execute an ubuffered query and returns the result.
-
#select(tablename, arr_terms = nil, args = nil, &block) ⇒ Object
Makes a select from the given arguments: table-name, where-terms and other arguments as limits and orders.
- #setOpts(arr_opts) ⇒ Object
-
#single(tablename, arr_terms = nil, args = {}) ⇒ Object
(also: #selectsingle)
Returns a single row from a database.
-
#spawn ⇒ Object
Spawns a new driver (useally done automatically).
-
#sqlspecs ⇒ Object
Returns the SQLSpec-module and spawns it if it isnt already spawned.
-
#tables ⇒ Object
Returns the table-module and spawns it if it isnt already spawned.
-
#transaction(&block) ⇒ Object
Beings a transaction and commits when the block ends.
-
#update(tablename, arr_update, arr_terms = {}, args = nil) ⇒ Object
Simple updates rows.
Constructor Details
#initialize(opts) ⇒ Db
Returns a new instance of Db.
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/knj/knjdb/libknjdb.rb', line 28 def initialize(opts) require "#{$knjpath}threadhandler" self.setOpts(opts) if opts != nil @int_types = ["int", "bigint", "tinyint", "smallint", "mediumint"] if !@opts[:threadsafe] require "monitor" @mutex = Monitor.new end @debug = @opts[:debug] self.conn_exec do |driver| @sep_table = driver.sep_table @sep_col = driver.sep_col @sep_val = driver.sep_val @esc_driver = driver end end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method_name, *args) ⇒ Object
Proxies the method to the driver.
Examples
db.method_on_driver
761 762 763 764 765 766 767 768 769 |
# File 'lib/knj/knjdb/libknjdb.rb', line 761 def method_missing(method_name, *args) self.conn_exec do |driver| if driver.respond_to?(method_name.to_sym) return driver.send(method_name, *args) end end raise "Method not found: #{method_name}" end |
Instance Attribute Details
#conn ⇒ Object (readonly)
Returns the value of attribute conn.
26 27 28 |
# File 'lib/knj/knjdb/libknjdb.rb', line 26 def conn @conn end |
#conns ⇒ Object (readonly)
Returns the value of attribute conns.
26 27 28 |
# File 'lib/knj/knjdb/libknjdb.rb', line 26 def conns @conns end |
#int_types ⇒ Object (readonly)
Returns the value of attribute int_types.
26 27 28 |
# File 'lib/knj/knjdb/libknjdb.rb', line 26 def int_types @int_types end |
#opts ⇒ Object (readonly)
Returns the value of attribute opts.
26 27 28 |
# File 'lib/knj/knjdb/libknjdb.rb', line 26 def opts @opts end |
#sep_col ⇒ Object (readonly)
Returns the value of attribute sep_col.
26 27 28 |
# File 'lib/knj/knjdb/libknjdb.rb', line 26 def sep_col @sep_col end |
#sep_table ⇒ Object (readonly)
Returns the value of attribute sep_table.
26 27 28 |
# File 'lib/knj/knjdb/libknjdb.rb', line 26 def sep_table @sep_table end |
#sep_val ⇒ Object (readonly)
Returns the value of attribute sep_val.
26 27 28 |
# File 'lib/knj/knjdb/libknjdb.rb', line 26 def sep_val @sep_val end |
Class Method Details
.const_missing(name) ⇒ Object
Autoloader for subclasses..
20 21 22 23 24 |
# File 'lib/knj/knjdb/libknjdb.rb', line 20 def self.const_missing(name) require "#{$knjpath}knjdb/#{name.to_s.downcase}.rb" raise "Still not defined: '#{name}'." if !Knj::Db.const_defined?(name) return Knj::Db.const_get(name) end |
Instance Method Details
#args ⇒ Object
50 51 52 |
# File 'lib/knj/knjdb/libknjdb.rb', line 50 def args return @opts end |
#clean ⇒ Object
Clean up various memory-stuff if possible.
150 151 152 153 154 155 156 157 158 |
# File 'lib/knj/knjdb/libknjdb.rb', line 150 def clean if @conns @conns.objects.each do |data| data[:object].clean if data[:object].respond_to?("clean") end elsif @conn @conn.clean if @conn.respond_to?("clean") end end |
#clone_conn(args = {}) ⇒ Object
Clones the current database-connection with possible extra arguments.
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 |
# File 'lib/knj/knjdb/libknjdb.rb', line 170 def clone_conn(args = {}) conn = Knj::Db.new(@opts.clone.merge(args)) if block_given? begin yield(conn) ensure conn.close end return nil else return conn end end |
#cloned_conn(args = nil, &block) ⇒ Object
Clones the connection, executes the given block and closes the connection again.
Examples
db.cloned_conn do |conn|
conn.q('SELCET * FROM users') do |data|
print data[:name]
end
end
577 578 579 580 581 582 583 584 585 586 587 588 589 590 |
# File 'lib/knj/knjdb/libknjdb.rb', line 577 def cloned_conn(args = nil, &block) clone_conn_args = { :threadsafe => false } clone_conn_args.merge!(args[:clone_args]) if args and args[:clone_args] dbconn = self.clone_conn(clone_conn_args) begin yield(dbconn) ensure dbconn.close end end |
#close ⇒ Object
The all driver-database-connections.
161 162 163 164 165 166 167 |
# File 'lib/knj/knjdb/libknjdb.rb', line 161 def close @conn.close if @conn @conns.destroy if @conns @conn = nil @conns = nil end |
#cols ⇒ Object
Returns the columns-module and spawns it if it isnt already spawned.
698 699 700 701 702 703 704 705 706 707 |
# File 'lib/knj/knjdb/libknjdb.rb', line 698 def cols if !@cols require "#{File.dirname(__FILE__)}/drivers/#{@opts[:type]}/knjdb_#{@opts[:type]}_columns" if (!@opts.key?(:require) or @opts[:require]) @cols = Kernel.const_get("KnjDB_#{@opts[:type]}".to_sym).const_get(:Columns).new( :db => self ) end return @cols end |
#conn_exec ⇒ Object
Returns a driver-object based on the current thread and free driver-objects.
Examples
db.conn_exec do |driver|
str = driver.escape('something̈́')
end
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 |
# File 'lib/knj/knjdb/libknjdb.rb', line 497 def conn_exec if tcur = Thread.current and tcur[:knjdb] tid = self.__id__ if tcur[:knjdb].key?(tid) yield(tcur[:knjdb][tid]) return nil end end if @conns conn = @conns.get_and_lock begin yield(conn) return nil ensure @conns.free(conn) end elsif @conn @mutex.synchronize do yield(@conn) return nil end end raise "Could not figure out how to find a driver to use?" end |
#connect ⇒ Object
Actually connects to the database. This is useually done automatically.
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
# File 'lib/knj/knjdb/libknjdb.rb', line 70 def connect if @opts[:threadsafe] @conns = Knj::Threadhandler.new @conns.on_spawn_new do self.spawn end @conns.on_inactive do |data| data[:obj].close end @conns.on_activate do |data| data[:obj].reconnect end else @conn = self.spawn end end |
#copy_to(db, args = {}) ⇒ Object
Copies the content of the current database to another instance of Knj::Db.
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 |
# File 'lib/knj/knjdb/libknjdb.rb', line 187 def copy_to(db, args = {}) data["tables"].each do |table| table_args = nil table_args = args["tables"][table["name"].to_s] if args and args["tables"] and args["tables"][table["name"].to_s] next if table_args and table_args["skip"] table.delete("indexes") if table.key?("indexes") and args["skip_indexes"] db.tables.create(table["name"], table) limit_from = 0 limit_incr = 1000 loop do ins_arr = [] q_rows = self.select(table["name"], {}, {"limit_from" => limit_from, "limit_to" => limit_incr}) while d_rows = q_rows.fetch col_args = nil if table_args and table_args["columns"] d_rows.each do |col_name, col_data| col_args = table_args["columns"][col_name.to_s] if table_args and table_args["columns"] d_rows[col_name] = "" if col_args and col_args["empty"] end end ins_arr << d_rows end break if ins_arr.empty? db.insert_multi(table["name"], ins_arr) limit_from += limit_incr end end end |
#data ⇒ Object
226 227 228 229 230 231 232 233 234 235 |
# File 'lib/knj/knjdb/libknjdb.rb', line 226 def data tables_ret = [] tables.list.each do |name, table| tables_ret << table.data end return { "tables" => tables_ret } end |
#date_in(date_obj) ⇒ Object
Takes a valid date-db-string and converts it into a Datet.
Examples
db.date_in(‘2012-05-20 22:06:09’) #=> 2012-05-20 22:06:09 +0200
677 678 679 680 681 682 683 |
# File 'lib/knj/knjdb/libknjdb.rb', line 677 def date_in(date_obj) if @esc_driver.respond_to?(:date_in) return @esc_driver.date_in(date_obj) end return Datet.in(date_obj) end |
#date_out(date_obj = Datet.new, args = {}) ⇒ Object
Returns a string which can be used in SQL with the current driver.
Examples
str = db.date_out(Time.now) #=> “2012-05-20 22:06:09”
666 667 668 669 670 671 672 |
# File 'lib/knj/knjdb/libknjdb.rb', line 666 def date_out(date_obj = Datet.new, args = {}) if @esc_driver.respond_to?(:date_out) return @esc_driver.date_out(date_obj, args) end return Datet.in(date_obj).dbstr(args) end |
#delete(tablename, arr_terms, args = nil) ⇒ Object
Deletes rows from the database.
Examples
db.delete(:users, => “Doe”)
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 |
# File 'lib/knj/knjdb/libknjdb.rb', line 447 def delete(tablename, arr_terms, args = nil) sql = "DELETE FROM #{@sep_table}#{tablename}#{@sep_table}" if arr_terms != nil and !arr_terms.empty? sql << " WHERE #{self.makeWhere(arr_terms)}" end return sql if args and args[:return_sql] self.conn_exec do |driver| driver.query(sql) end return nil end |
#esc_col(str) ⇒ Object
Escapes the given string to be used as a column.
654 655 656 |
# File 'lib/knj/knjdb/libknjdb.rb', line 654 def esc_col(str) return @esc_driver.esc_col(str) end |
#esc_table(str) ⇒ Object
Escapes the given string to be used as a table.
659 660 661 |
# File 'lib/knj/knjdb/libknjdb.rb', line 659 def esc_table(str) return @esc_driver.esc_table(str) end |
#escape(string) ⇒ Object Also known as: esc
Escapes a string to be safe-to-use in a query-string.
Examples
db.q(“INSERT INTO users (name) VALUES (‘#Knj::Db.dbdb.esc(’John’)‘)”)
647 648 649 |
# File 'lib/knj/knjdb/libknjdb.rb', line 647 def escape(string) return @esc_driver.escape(string) end |
#free_thread ⇒ Object
Frees the current driver from the current thread.
138 139 140 141 142 143 144 145 146 147 |
# File 'lib/knj/knjdb/libknjdb.rb', line 138 def free_thread thread_cur = Thread.current tid = self.__id__ if thread_cur[:knjdb] and thread_cur[:knjdb].key?(tid) db = thread_cur[:knjdb][tid] thread_cur[:knjdb].delete(tid) @conns.free(db) if @conns end end |
#get_and_register_thread ⇒ Object
Registers a driver to the current thread.
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 |
# File 'lib/knj/knjdb/libknjdb.rb', line 113 def get_and_register_thread raise "KnjDB-object is not in threadding mode." if !@conns thread_cur = Thread.current tid = self.__id__ thread_cur[:knjdb] = {} if !thread_cur[:knjdb] if thread_cur[:knjdb][tid] #An object has already been spawned - free that first to avoid endless "used" objects. self.free_thread end thread_cur[:knjdb][tid] = @conns.get_and_lock if !thread_cur[:knjdb][tid] #If block given then be ensure to free thread after yielding. if block_given? begin yield ensure self.free_thread end end end |
#indexes ⇒ Object
Returns the index-module and spawns it if it isnt already spawned.
710 711 712 713 714 715 716 717 718 719 |
# File 'lib/knj/knjdb/libknjdb.rb', line 710 def indexes if !@indexes require "#{File.dirname(__FILE__)}/drivers/#{@opts[:type]}/knjdb_#{@opts[:type]}_indexes" if (!@opts.key?(:require) or @opts[:require]) @indexes = Kernel.const_get("KnjDB_#{@opts[:type]}".to_sym).const_get(:Indexes).new( :db => self ) end return @indexes end |
#insert(tablename, arr_insert, args = nil) ⇒ Object
Simply inserts data into a table.
Examples
db.insert(:users, => “John”, :lastname => “Doe”) id = db.insert(:users, => “John”, :lastname => “Doe”, :return_id => true) sql = db.insert(:users, => “John”, :lastname => “Doe”, :return_sql => true) #=> “INSERT INTO ‘users` (`name`, `lastname`) VALUES (’John’, ‘Doe’)”
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 |
# File 'lib/knj/knjdb/libknjdb.rb', line 243 def insert(tablename, arr_insert, args = nil) sql = "INSERT INTO #{@sep_table}#{tablename}#{@sep_table}" if !arr_insert or arr_insert.empty? #This is the correct syntax for inserting a blank row in MySQL. if @opts[:type].to_s == "mysql" sql << " VALUES ()" elsif @opts[:type].to_s == "sqlite3" sql << " DEFAULT VALUES" else raise "Unknown database-type: '#{@opts[:type]}'." end else sql << " (" first = true arr_insert.each do |key, value| if first first = false else sql << ", " end sql << "#{@sep_col}#{key}#{@sep_col}" end sql << ") VALUES (" first = true arr_insert.each do |key, value| if first first = false else sql << ", " end sql << "#{@sep_val}#{@esc_driver.escape(value)}#{@sep_val}" end sql << ")" end return sql if args and args[:return_sql] self.conn_exec do |driver| driver.query(sql) return driver.lastID if args and args[:return_id] return nil end end |
#insert_multi(tablename, arr_hashes, args = nil) ⇒ Object
Simply and optimal insert multiple rows into a table in a single query. Uses the drivers functionality if supported or inserts each row manually.
Examples
db.insert_multi(:users, [
{:name => "John", :lastname => "Doe"},
{:name => "Kasper", :lastname => "Johansen"}
])
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 |
# File 'lib/knj/knjdb/libknjdb.rb', line 301 def insert_multi(tablename, arr_hashes, args = nil) return false if arr_hashes.empty? if @esc_driver.respond_to?(:insert_multi) if args and args[:return_sql] return [@esc_driver.insert_multi(tablename, arr_hashes, args)] end self.conn_exec do |driver| return driver.insert_multi(tablename, arr_hashes, args) end else ret = [] if args and (args[:return_id] or args[:return_sql]) arr_hashes.each do |hash| if ret ret << self.insert(tablename, hash, args) else self.insert(tablename, hash, args) end end if ret return ret else return nil end end end |
#lastID ⇒ Object Also known as: last_id
Returns the last inserted ID.
Examples
id = db.last_id
635 636 637 638 639 |
# File 'lib/knj/knjdb/libknjdb.rb', line 635 def lastID self.conn_exec do |driver| return driver.lastID end end |
#makeWhere(arr_terms, driver = nil) ⇒ Object
Internally used to generate SQL.
Examples
sql = db.makeWhere(=> “Doe”, driver_obj)
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 |
# File 'lib/knj/knjdb/libknjdb.rb', line 467 def makeWhere(arr_terms, driver = nil) sql = "" first = true arr_terms.each do |key, value| if first first = false else sql << " AND " end if value.is_a?(Array) raise "Array for column '#{key}' was empty." if value.empty? sql << "#{@sep_col}#{key}#{@sep_col} IN (#{Knj::ArrayExt.join(:arr => value, :sep => ",", :surr => "'", :callback => proc{|ele| self.esc(ele)})})" elsif value.is_a?(Hash) raise "Dont know how to handle hash." else sql << "#{@sep_col}#{key}#{@sep_col} = #{@sep_val}#{@esc_driver.escape(value)}#{@sep_val}" end end return sql end |
#optimize(args = nil) ⇒ Object
Optimizes all tables in the database.
747 748 749 750 751 752 753 754 755 |
# File 'lib/knj/knjdb/libknjdb.rb', line 747 def optimize(args = nil) STDOUT.puts "Beginning optimization of database." if @debug or (args and args[:debug]) self.tables.list do |table| STDOUT.puts "Optimizing table: '#{table.name}'." if @debug or (args and args[:debug]) table.optimize end return nil end |
#q(str, args = nil, &block) ⇒ Object
Executes a query and returns the result. If a block is given the result is iterated over that block instead and it returns nil.
Examples
db.q(‘SELECT * FROM users’) do |data|
print data[:name]
end
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 |
# File 'lib/knj/knjdb/libknjdb.rb', line 598 def q(str, args = nil, &block) #If the query should be executed in a new connection unbuffered. if args if args[:cloned_ubuf] raise "No block given." if !block self.cloned_conn(:clone_args => args[:clone_args]) do |cloned_conn| ret = cloned_conn.query_ubuf(str) ret.each(&block) end return nil else raise "Invalid arguments given: '#{args}'." end end ret = self.query(str) if block ret.each(&block) return nil end return ret end |
#q_buffer(&block) ⇒ Object
Yields a query-buffer and flushes at the end of the block given.
626 627 628 629 |
# File 'lib/knj/knjdb/libknjdb.rb', line 626 def q_buffer(&block) Knj::Db::Query_buffer.new(:db => self, &block) return nil end |
#query(string) ⇒ Object
Executes a query and returns the result.
Examples
res = db.query(‘SELECT * FROM users’) while data = res.fetch
print data[:name]
end
533 534 535 536 537 538 539 540 541 542 543 544 545 546 |
# File 'lib/knj/knjdb/libknjdb.rb', line 533 def query(string) if @debug print "SQL: #{string}\n" if @debug.is_a?(Fixnum) and @debug >= 2 print caller.join("\n") print "\n" end end self.conn_exec do |driver| return driver.query(string) end end |
#query_ubuf(string, &block) ⇒ Object
Execute an ubuffered query and returns the result.
Examples
db.query_ubuf(‘SELECT * FROM users’) do |data|
print data[:name]
end
554 555 556 557 558 559 560 561 562 563 564 565 566 567 |
# File 'lib/knj/knjdb/libknjdb.rb', line 554 def query_ubuf(string, &block) ret = nil self.conn_exec do |driver| ret = driver.query_ubuf(string, &block) end if block ret.each(&block) return nil end return ret end |
#select(tablename, arr_terms = nil, args = nil, &block) ⇒ Object
Makes a select from the given arguments: table-name, where-terms and other arguments as limits and orders. Also takes a block to avoid raping of memory.
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 |
# File 'lib/knj/knjdb/libknjdb.rb', line 367 def select(tablename, arr_terms = nil, args = nil, &block) #Set up vars. sql = "" args_q = nil select_sql = "*" #Give 'cloned_ubuf' argument to 'q'-method. if args and args[:cloned_ubuf] args_q = {:cloned_ubuf => true} end #Set up IDQuery-stuff if that is given in arguments. if args and args[:idquery] if args[:idquery] == true select_sql = "`id`" col = :id else select_sql = "`#{self.esc_col(args[:idquery])}`" col = args[:idquery] end end sql = "SELECT #{select_sql} FROM #{@sep_table}#{tablename}#{@sep_table}" if arr_terms != nil and !arr_terms.empty? sql << " WHERE #{self.makeWhere(arr_terms)}" end if args != nil if args["orderby"] sql << " ORDER BY #{args["orderby"]}" end if args["limit"] sql << " LIMIT #{args["limit"]}" end if args["limit_from"] and args["limit_to"] raise "'limit_from' was not numeric: '#{args["limit_from"]}'." if !(Float(args["limit_from"]) rescue false) raise "'limit_to' was not numeric: '#{args["limit_to"]}'." if !(Float(args["limit_to"]) rescue false) sql << " LIMIT #{args["limit_from"]}, #{args["limit_to"]}" end end #Do IDQuery if given in arguments. if args and args[:idquery] res = Knj::Db::Idquery.new(:db => self, :table => tablename, :query => sql, :col => col, &block) else res = self.q(sql, args_q, &block) end #Return result if a block wasnt given. if block return nil else return res end end |
#setOpts(arr_opts) ⇒ Object
54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/knj/knjdb/libknjdb.rb', line 54 def setOpts(arr_opts) @opts = {} arr_opts.each do |key, val| @opts[key.to_sym] = val end if RUBY_PLATFORM == "java" @opts[:subtype] = "java" elsif @opts[:type] == "sqlite3" and RUBY_PLATFORM.index("mswin32") != nil @opts[:subtype] = "ironruby" end self.connect end |
#single(tablename, arr_terms = nil, args = {}) ⇒ Object Also known as: selectsingle
Returns a single row from a database.
Examples
row = db.single(:users, => “Doe”)
430 431 432 433 434 435 436 437 438 439 |
# File 'lib/knj/knjdb/libknjdb.rb', line 430 def single(tablename, arr_terms = nil, args = {}) args["limit"] = 1 #Experienced very weird memory leak if this was not done by block. Maybe bug in Ruby 1.9.2? - knj self.select(tablename, arr_terms, args) do |data| return data end return false end |
#spawn ⇒ Object
Spawns a new driver (useally done automatically).
Examples
driver_instance = db.spawn
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 |
# File 'lib/knj/knjdb/libknjdb.rb', line 93 def spawn raise "No type given (#{@opts.keys.join(",")})." if !@opts[:type] fpaths = [ "drivers/#{@opts[:type]}/knjdb_#{@opts[:type]}.rb", "libknjdb_#{@opts[:type]}.rb" ] fpaths.each do |fpath| rpath = "#{File.dirname(__FILE__)}/#{fpath}" if (!@opts.key?(:require) or @opts[:require]) and File.exists?(rpath) require rpath break end end return Kernel.const_get("KnjDB_#{@opts[:type]}").new(self) end |
#sqlspecs ⇒ Object
Returns the SQLSpec-module and spawns it if it isnt already spawned.
722 723 724 725 726 727 728 729 730 731 |
# File 'lib/knj/knjdb/libknjdb.rb', line 722 def sqlspecs if !@sqlspecs require "#{File.dirname(__FILE__)}/drivers/#{@opts[:type]}/knjdb_#{@opts[:type]}_sqlspecs" if (!@opts.key?(:require) or @opts[:require]) @sqlspecs = Kernel.const_get("KnjDB_#{@opts[:type]}".to_sym).const_get(:Sqlspecs).new( :db => self ) end return @sqlspecs end |
#tables ⇒ Object
Returns the table-module and spawns it if it isnt already spawned.
686 687 688 689 690 691 692 693 694 695 |
# File 'lib/knj/knjdb/libknjdb.rb', line 686 def tables if !@tables require "#{File.dirname(__FILE__)}/drivers/#{@opts[:type]}/knjdb_#{@opts[:type]}_tables" if (!@opts.key?(:require) or @opts[:require]) @tables = Kernel.const_get("KnjDB_#{@opts[:type]}".to_sym).const_get(:Tables).new( :db => self ) end return @tables end |
#transaction(&block) ⇒ Object
Beings a transaction and commits when the block ends.
Examples
db.transaction do |db|
db.insert(:users, {:name => "John"})
db.insert(:users, {:name => "Kasper"})
end
740 741 742 743 744 |
# File 'lib/knj/knjdb/libknjdb.rb', line 740 def transaction(&block) self.conn_exec do |driver| driver.transaction(&block) end end |
#update(tablename, arr_update, arr_terms = {}, args = nil) ⇒ Object
Simple updates rows.
Examples
db.update(:users, => “John”, => “Doe”)
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 |
# File 'lib/knj/knjdb/libknjdb.rb', line 334 def update(tablename, arr_update, arr_terms = {}, args = nil) return false if arr_update.empty? sql = "" sql << "UPDATE #{@sep_col}#{tablename}#{@sep_col} SET " first = true arr_update.each do |key, value| if first first = false else sql << ", " end #Convert dates to valid dbstr. value = self.date_out(value) if value.is_a?(Datet) or value.is_a?(Time) sql << "#{@sep_col}#{key}#{@sep_col} = " sql << "#{@sep_val}#{@esc_driver.escape(value)}#{@sep_val}" end if arr_terms and arr_terms.length > 0 sql << " WHERE #{self.makeWhere(arr_terms)}" end return sql if args and args[:return_sql] self.conn_exec do |driver| driver.query(sql) end end |