Class: KSDatabase

Inherits:
Object show all
Extended by:
Forwardable
Includes:
DRbUndumped
Defined in:
lib/kansas/Database.rb

Constant Summary collapse

@@partial_to_complete_map =
{}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(arg1 = nil, arg2 = nil, arg3 = nil, arg4 = nil) ⇒ KSDatabase

Initialize Kansas. Kansas optionally accepts a database handle. This allows an external system, such as a database connection pool, to be used with Kansas.



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/kansas/Database.rb', line 72

def initialize(arg1 = nil, arg2 = nil, arg3 = nil, arg4 = nil)
  # If a database handle is passed in as the first arg, then the second should be an options has.
  # If the first arg is a string, then it is assumed to be a dsn and the next two args will be
  # username and password, followed by options.
  if String === arg1
    dsn = arg1
    username = arg2
    password = arg3
    options = arg4 ? arg4 : {}
  else
    dbh = arg1
    options = arg2 ? arg2 : {}
  end
  
  if dbh
    @dbh = dbh
    @options = options
  elsif dsn
    connect_using(dsn,username,password,options)
    new_dbh
  else
    @options = options
  end

  @objects = {}
  @changed = []    
    @remote_to_local_map = {}
  set_autocommit
end

Instance Attribute Details

#dbhObject

Returns the value of attribute dbh.



66
67
68
# File 'lib/kansas/Database.rb', line 66

def dbh
  @dbh
end

#optionsObject (readonly)

Returns the value of attribute options.



65
66
67
# File 'lib/kansas/Database.rb', line 65

def options
  @options
end

#tablesObject (readonly)

Returns the value of attribute tables.



65
66
67
# File 'lib/kansas/Database.rb', line 65

def tables
  @tables
end

Class Method Details

.partial_to_complete_mapObject



61
62
63
# File 'lib/kansas/Database.rb', line 61

def KSDatabase.partial_to_complete_map
  @@partial_to_complete_map
end

Instance Method Details

#all_tablesObject Also known as: map_all_tables



520
521
522
523
524
525
526
527
# File 'lib/kansas/Database.rb', line 520

def all_tables
  query do |dbh|
    dbh.tables.each do |table_name|
      Kansas.log("Defining table: #{table_name} as #{canonical(table_name)}") if $DEBUG
      table(canonical(table_name), table_name)
    end
  end
end

#autocommitObject



134
135
136
# File 'lib/kansas/Database.rb', line 134

def autocommit
  autocommit?
end

#autocommit=(setting) ⇒ Object



138
139
140
# File 'lib/kansas/Database.rb', line 138

def autocommit=(setting)
  set_autocommit setting
end

#autocommit?Boolean

Returns:

  • (Boolean)


130
131
132
# File 'lib/kansas/Database.rb', line 130

def autocommit?
  @options[:autocommit]
end

#changed(obj) ⇒ Object



513
514
515
516
517
518
# File 'lib/kansas/Database.rb', line 513

def changed(obj)
  @changed << obj
  if autocommit?
    commit
  end
end

#check_query_args(*args) ⇒ Object



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
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/kansas/Database.rb', line 190

def check_query_args(*args)
  tables = []
  read_only = false
  final_value = args.length > 1 ? args.last : nil
  sql = ''
  
  args.each do |table|
    if table == :__read_only__
      read_only = true
      next
    end
    
    final_flag = (table == final_value)
    table = table.to_s if table.kind_of?(Symbol)
    if table.kind_of?(String)
      tclass = get_table_from_string(table)
      if tclass
        table = tclass
      else
        if final_flag
          sql << table
        else
          self.map_all_tables
          table = get_table_from_string(table)
        end
      end
    end
    tables << table if table
  end
  
  unless sql != ''
    if tables.length == 0
      raise KSNoTable, "KSNoTable: No valid tables were found to operate against."
    else
      tables.each do |t|
        unless t.respond_to?(:is_a_kstable?)
          raise KSBadTable.new,"KSBadTable: #{t} is not a valid table."
        end
      end
    end
  end  

  [tables,sql,read_only]
end

#commitObject

Commit transaction to the database.



476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
# File 'lib/kansas/Database.rb', line 476

def commit
  query do |dbh|
    dbh.transaction do
      @changed.uniq.each do |o|
        if o.kind_of?(String)
          query {|innerdbh| innerdbh.do o.to_s}
        elsif o.pending_deletion?
          delete_one o
        elsif o.serialized?
          store_object o
        else
          insert_object o
        end
        o.rollback_buffer = []
      end
      @changed.clear
    end
    dbh.commit
  end
end

#connect_using(dsn, user, password, options = {}) ⇒ Object Also known as: connectUsing

Set the parameters used for making a DBI connection.



104
105
106
107
108
109
# File 'lib/kansas/Database.rb', line 104

def connect_using(dsn, user, password, options = {})
  @dsn = dsn
  @user = user
  @password = password
  @options = options
end

#count(*args) ⇒ Object

Returns only a count of the records selected by the query.



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
# File 'lib/kansas/Database.rb', line 288

def count(*args)
  error_recovery ||= false
  results = nil
  tables,sql = check_query_args(*args)

  if block_given?
    context = KSExpression::Context.new(*tables)
    yield_args = tables.collect {|t| KSTableExpr.new(t,context)}
    queryExpr = yield *yield_args
    sql = queryExpr.count_sql
  elsif sql == ''
    sql = "SELECT count(*) FROM #{tables.collect {|t| t.table_name}.join(',')}"
  end
  
  Kansas::log("select: '#{sql}'") if $DEBUG

  rawResults = query do |dbh|
    dbh.select_all(sql) do |row|
      results = row[0]
    end
  end

  results
rescue DBI::DatabaseError => e
  unless error_recovery
    error_recovery = true
    new_dbh
    retry
  else
    raise e
  end
end

#decoupled_object(table, rowdata = {}) ⇒ Object

Use decoupled_object() to create an object that is not yet connected to a database.



400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'lib/kansas/Database.rb', line 400

def decoupled_object(table, rowdata = {})
  table = table.to_s if table.is_a? Symbol
  if table.kind_of? String
    if @remote_to_local_map.has_key?(table)
      table = self.class.const_get @remote_to_local_map[table]
    elsif KSDatabase.partial_to_complete_map.has_key?(table)
      table = self.class.const_get KSDatabase.partial_to_complete_map[table]
    else
      table = nil
    end
  end
  
               
               rowdata.dup.each do |k,v|
                       if k.is_a?(Symbol)
                               rowdata.delete(k)
                               rowdata[k.to_s] = v
                       end
               end
  table.new.load(rowdata)
end

#delete(table, sql = nil) ⇒ Object

Delete removes one or more rows from the database. It also returns an array of objects matching the rows deleted. If Autocommit is not on, it will return the array of rows that would be deleted _at the time of the call_ and will defer the actual deletion from the database until a commit() is invoked.



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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
# File 'lib/kansas/Database.rb', line 337

def delete(table, sql=nil)
  error_recovery ||= false
  table = table.to_s if table.kind_of?(Symbol)
  
  if table.kind_of?(String)
    if @remote_to_local_map.has_key?(table)
      table = self.class.const_get @remote_to_local_map[table]
    elsif KSDatabase.partial_to_complete_map.has_key?(table)
      table = self.class.const_get KSDatabase.partial_to_complete_map[table]
    else
      table = nil
    end
  end

  unless Class === table
    raise KSBadTable,"KSBadTable: #{table} is not a valid table."
  end

  if block_given?
    queryExpr = yield KSTableExpr.new(table)
    select_sql = queryExpr.sql
    delete_sql = queryExpr.delete_sql
  elsif sql == nil
    select_sql = "SELECT * FROM #{table.table_name}"
    delete_sql = "DELETE FROM #{table.table_name}"
  end

  Kansas::log("delete: '#{sql}'") if $DEBUG

  results = []
  rawResults = query do |dbh|
    dbh.select_all(select_sql) do |row|
      results.push add_object(table.new.load(row.to_h, self))
    end
  end
  
  if autocommit?
    query {|dbh| dbh.do delete_sql}
  else
    changed delete_sql
  end
  
  results
rescue DBI::DatabaseError => e
  unless error_recovery
    error_recovery = true
    new_dbh
    retry
  else
    raise e
  end
end

#delete_one(object) ⇒ Object



390
391
392
393
394
395
# File 'lib/kansas/Database.rb', line 390

def delete_one(object)
  sql = "DELETE FROM #{object.table_name} #{build_where(object)}"
  result = query {|dbh| dbh.do sql}
  unregister_object object
  result
end

#exists?(*args, &block) ⇒ Boolean

A convenience usage of count(). Returns true if the query would return any number of rows, or false if the query would not return any rows.

Returns:

  • (Boolean)


324
325
326
327
328
329
330
# File 'lib/kansas/Database.rb', line 324

def exists?(*args,&block)
  if block
    0 < count(*args) {|*blockargs| block.call(*blockargs)}
  else
    0 < count(*args)
  end
end

#get_object(table, key) ⇒ Object



160
161
162
163
164
165
166
167
168
# File 'lib/kansas/Database.rb', line 160

def get_object(table, key)
  unless obj = has_object?(table,key)
    if obj = load_object(table,key,true)
      obj.set_serialized
      register_object(obj)
    end
  end
  obj
end

#get_table_from_string(table) ⇒ Object



180
181
182
183
184
185
186
187
188
# File 'lib/kansas/Database.rb', line 180

def get_table_from_string(table)
  if KSDatabase.partial_to_complete_map.has_key?(table)
    table = self.class.const_get KSDatabase.partial_to_complete_map[table]
  elsif @remote_to_local_map.has_key?(table)
    table = self.class.const_get @remote_to_local_map[table]
  else
    nil
  end
end

#has_object?(table, key) ⇒ Boolean

Returns:

  • (Boolean)


151
152
153
154
155
156
157
158
# File 'lib/kansas/Database.rb', line 151

def has_object?(table, key)
if tableHash = @objects[table]
  tableHash[key]     
else
  @objects[table] = {}
  nil
end
end

#new_dbhObject Also known as: newDbh



112
113
114
# File 'lib/kansas/Database.rb', line 112

def new_dbh
  @dbh = DBI.connect(@dsn, @user, @password) if @dsn
end

#new_object(table, rowdata = {}) ⇒ Object Also known as: newObject

Use new_object() to create new records within a table.



424
425
426
427
428
429
430
431
432
433
434
435
436
# File 'lib/kansas/Database.rb', line 424

def new_object(table,rowdata = {})
  object = decoupled_object(table,rowdata)
  register_object object
  object.context = self
  if autocommit?
    insert_object object
    object.set_serialized
  else
    changed object
  end
  
  object
end

#query(*args, &blk) ⇒ Object



117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/kansas/Database.rb', line 117

def query(*args,&blk)
  error_recovery ||= false
  yield(@dbh,*args)
rescue Exception => e
  unless error_recovery
    error_recovery = true
    new_dbh
    retry
  else
    raise e
  end
end

#register_and_insert_object(object) ⇒ Object

Take a table object that is not tied to the database and tie it.



441
442
443
444
445
446
447
# File 'lib/kansas/Database.rb', line 441

def register_and_insert_object(object)
  register_object object
  object.context = self
  insert_object object
  object.set_serialized
  object
end

#rollbackObject

Rollback uncommitted transactions on an object so that they never get to the database.



500
501
502
503
504
505
506
507
508
509
510
511
# File 'lib/kansas/Database.rb', line 500

def rollback
  if @transaction_flag
    raise KSRollback
  else
    @changed.uniq.each do |o|
      next if o.kind_of?(String)
      o.rollback
    end
    @changed.clear
  end
  query {|dbh| dbh.rollback}
end

#select(*args) ⇒ Object

Selects from a table. If a block is given, that block will be used to construct the SQL statement. Otherwise, if a SQL statement was given as the second argument, that statement will be used. If no statement was given, the default is to select * from the table provided as the first argument. The table can either be specified by passing the class for the table to use (e.x. KSDatabase::Students), by passing the remote name (i.e. the name of the actual database table), or by passing the local name for the table that was given when mapping the table. Most of the time the local name or the remote name should be used as it works just as well as the full class name.

Note that select’d currently operates outside of the local rollback cache.



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
# File 'lib/kansas/Database.rb', line 248

def select(*args)
  error_recovery ||= false
  results = []
  tables,sql,read_only = check_query_args(*args)

  if block_given?
    context = KSExpression::Context.new(*tables)
    yield_args = tables.collect {|t| KSTableExpr.new(t,context)}
    queryExpr = yield *yield_args
    sql = queryExpr.select_sql
  elsif sql == ''
    sql = "SELECT * FROM #{tables.collect {|t| t.table_name}.join(',')}"
  end
  
  Kansas::log("select: '#{sql}'") if $DEBUG

  rawResults = query do |dbh|
    dbh.select_all(sql) do |row|
      results << add_object(tables[0].new.load(row.to_h, self, read_only))
    end
  end

  results
rescue DBI::DatabaseError => e
  unless error_recovery
    error_recovery = true
    new_dbh
    retry
  else
    raise e
  end
end

#select_first(*args, &blk) ⇒ Object

Return only one value from a query.



283
284
285
# File 'lib/kansas/Database.rb', line 283

def select_first(*args,&blk)
  select(*args) {|*yargs| blk.call(*yargs)}.first
end

#set_autocommit(setting = nil) ⇒ Object Also known as: setAutocommit



142
143
144
145
146
147
148
# File 'lib/kansas/Database.rb', line 142

def set_autocommit(setting = nil)
  if setting != nil
    @options[:autocommit] = setting ? true : false
  else
    @options[:autocommit] = true
  end
end

#store_object(object) ⇒ Object

Updates the record in the database for the object.



172
173
174
175
176
177
178
# File 'lib/kansas/Database.rb', line 172

def store_object(object)
  #sql = build_update(object) + build_where(object)
  #query {|dbh| dbh.do(sql)}
  rs = build_update(object)
  sql = rs.first + build_where(object)
  query {|dbh| dbh.do(sql,*rs.last)}
end

#table(local_name, remote_name = nil) ⇒ Object Also known as: map_table



530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
# File 'lib/kansas/Database.rb', line 530

def table(local_name, remote_name=nil)
  local_name = local_name.to_s
  remote_name = local_name unless remote_name
  remote_name = remote_name.to_s
  
  old_local_name = local_name
  local_name  = make_constant_name(local_name)
  table = Class.new(KSTable)
  table.const_set('Name', remote_name)
  table.const_set('Database', self)
  table.all_fields
  
  @remote_to_local_map[remote_name] = local_name
  KSDatabase.partial_to_complete_map[old_local_name] = local_name
  addTable(local_name, table)
end

#transactionObject

Block oriented interface to commit/rollback.



450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
# File 'lib/kansas/Database.rb', line 450

def transaction
  old_autocommit = autocommit?
  old_dbh_autocommit = @dbh['AutoCommit']
  set_autocommit false
  @dbh['AutoCommit'] = false
  @transaction_flag = true
  begin
    commit
    yield self
      commit
  rescue KSRollback
    # We caught a Rollback; this isn't really an error.
    @transaction_flag = false
    rollback
  rescue Exception
  # Something bad happened.
  @transaction_flag = false
  rollback
  raise
  end
  set_autocommit(old_autocommit)
  @dbh['AutoCommit'] = old_dbh_autocommit
end