Class: Og::SqlStore

Inherits:
Store
  • Object
show all
Defined in:
lib/og/store/sql.rb,
lib/og/store/sql/join.rb

Overview

Extends SqlStore by adding join related methods.

Instance Attribute Summary collapse

Attributes inherited from Store

#ogmanager

Instance Method Summary collapse

Methods inherited from Store

#commit, #delete, #force_save!, #insert, #rollback, #save, #start, #transaction, #update_attributes

Constructor Details

#initialize(options) ⇒ SqlStore

Initialize the store. – Override in the adapter. ++



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/og/store/sql.rb', line 29

def initialize(options)
  super

  # The default Ruby <-> SQL type mappings, should be valid 
  # for most RDBM systems.

  @typemap = {
    Integer => 'integer',
    Fixnum => 'integer',
    Float => 'float',
    String => 'text',
    Time => 'timestamp',
    Date => 'date',
    TrueClass => 'boolean',
    Object => 'text',
    Array => 'text',
    Hash => 'text',
    Og::Blob => 'bytea' # psql
  }
end

Instance Attribute Details

#connObject

The connection to the SQL backend.



18
19
20
# File 'lib/og/store/sql.rb', line 18

def conn
  @conn
end

#typemapObject

Ruby type <-> SQL type mappings.



22
23
24
# File 'lib/og/store/sql.rb', line 22

def typemap
  @typemap
end

Instance Method Details

#aggregate(term = 'COUNT(*)', options = {}) ⇒ Object Also known as: calculate

Perform an aggregation or calculation over query results. This low level method is used by the Entity calculation / aggregation methods.

Options

:field = the return type.

Example

calculate ‘COUNT(*)’ calculate ‘MIN(age)’ calculate ‘SUM(age)’, :group => :name



280
281
282
283
284
285
286
287
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
# File 'lib/og/store/sql.rb', line 280

def aggregate(term = 'COUNT(*)', options = {})
  # Leave this .dup here, causes problems because options are changed
  options = options.dup
  
  klass = options[:class]
  field = options[:field]
  
  # Rename search term, SQL92 but _not_ SQL89 compatible
  options.update(:select => "#{term} AS #{term[/^\w+/]}")
  
  unless options[:group] || options[:group_by]
    options.delete(:order)
    options.delete(:order_by)
  end
  
  sql = resolve_options(klass, options)
  
  if anno = klass.ann[field]
    return_type = anno.class
  end
  return_type ||= Integer
  
  if options[:group] || options[:group_by]
    # This is an aggregation, so return the calculated values
    # as an array.
    values = []
    res = query(sql)
    res.each_row do |row, idx|
      values << type_cast(return_type, row[0])
    end
    return values
  else
    return type_cast(return_type, query(sql).first_value)
  end
  
end

#closeObject

– Override in the adapter. ++



54
55
56
57
# File 'lib/og/store/sql.rb', line 54

def close
  @conn.close
  super
end

#count(options = {}) ⇒ Object

Perform a count query.



320
321
322
# File 'lib/og/store/sql.rb', line 320

def count(options = {})
  calculate('COUNT(*)', options).to_i
end

#create_db(options) ⇒ Object

Creates the database where Og managed objects are serialized. – Override in the adapter. ++



65
66
67
# File 'lib/og/store/sql.rb', line 65

def create_db(options)
  Logger.info "Created database '#{options[:name]}'"
end

#create_field_map(klass) ⇒ Object

Get the fields from the database table. Also handles the change of ordering of the fields in the table.

To ignore a database field use the ignore_fields annotation ie,

class Article

ann self, :ignore_fields => [ :tsearch_idx, :ext_field ]

end

other aliases for ignore_fiels: ignore_field, ignore_column. – Even though great care has been taken to make this method reusable, oveeride if needed in your adapter. ++



810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
# File 'lib/og/store/sql.rb', line 810

def create_field_map(klass)
  res = query "SELECT * FROM #{klass.table} LIMIT 1"
  map = {}

  # Check if the field should be ignored.
  
  ignore = klass.ann.self[:ignore_field] || klass.ann.self[:ignore_fields] || klass.ann.self[:ignore_columns]   

  res.fields.each_with_index do |f, i|
    field_name = f.to_sym
    unless (ignore and ignore.include?(field_name))
      map[field_name] = i
    end
  end

  return map
ensure
  res.close if res
end

#create_table(klass) ⇒ Object

Create the SQL table where instances of the given class will be serialized.



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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
# File 'lib/og/store/sql.rb', line 337

def create_table(klass)
  fields = fields_for_class(klass)

  sql = "CREATE TABLE #{klass.table} (#{fields.join(', ')}"

  # Create table constraints.

  if constraints = klass.ann.self[:sql_constraint]
    sql << ", #{constraints.join(', ')}"
  end

  # Set the table type (Mysql default, InnoDB, Hash, etc)
  
  if table_type = @options[:table_type]
    sql << ") TYPE = #{table_type};"  
  else
    sql << ")"
  end

  # Create indices.
  #
  # An example index definition:
  #
  # classs MyClass
  #   attr_accessor :age, Fixnum, :index => true, :pre_index => ..., :post_index => ...
  # end

  for idx in sql_indices_for_class(klass)
    anno = klass.ann(idx)
    idx = idx.to_s
    pre_sql, post_sql = anno[:pre_index], options[:post_index]
    idxname = idx.gsub(/ /, "").gsub(/,/, "_").gsub(/\(.*\)/, "")
    sql << " CREATE #{pre_sql} INDEX #{klass.table}_#{idxname}_idx #{post_sql} ON #{klass.table} (#{idx});"  
  end

  begin
    exec(sql, false)
    Logger.info "Created table '#{klass.table}'."
  rescue Object => ex
    if table_already_exists_exception? ex
      # Don't return yet. Fall trough to also check for the 
      # join table.
    else
      handle_sql_exception(ex, sql)
    end
  end

  # Create join tables if needed. Join tables are used in
  # 'many_to_many' relations.

  if join_tables = klass.ann.self[:join_tables] 
    for info in join_tables
      begin
        create_join_table_sql(info).each do |sql|
          exec(sql, false)
        end
        Logger.debug "Created jointable '#{info[:table]}'." if $DBG
      rescue Object => ex
        if table_already_exists_exception? ex
          Logger.debug 'Join table already exists' if $DBG
        else
          raise
        end
      end
    end
  end
end

#delete_all(klass) ⇒ Object

Delete all instances of the given class from the backend.



326
327
328
329
330
# File 'lib/og/store/sql.rb', line 326

def delete_all(klass)
  sql = "DELETE FROM #{klass.table}"
  sql << " WHERE ogtype='#{klass}'" if klass.schema_inheritance? and not klass.schema_inheritance_root?
  exec sql
end

#destroy_db(options) ⇒ Object Also known as: drop_db

Destroys the database where Og managed objects are serialized. – Override in the adapter. ++



75
76
77
# File 'lib/og/store/sql.rb', line 75

def destroy_db(options)
  Logger.info "Dropped database '#{options[:name]}'"
end

#drop_table(klass) ⇒ Object Also known as: destroy

Drop the sql table where objects of this class are persisted.



408
409
410
411
412
413
414
415
416
417
# File 'lib/og/store/sql.rb', line 408

def drop_table(klass)
  # Remove leftover data from some join tabkes.
  klass.relations.each do |rel|
    if rel.class.to_s == "Og::JoinsMany" and rel.join_table
      target_class =  rel.target_class
      exec "DELETE FROM #{rel.join_table}"
    end
  end
  exec "DROP TABLE #{klass.table}"
end

#enchant(klass, manager) ⇒ Object

Performs SQL related enchanting to the class. This method is further extended in more specialized adapters to add backend specific enchanting.

Defines:

  • the OGTABLE constant, and .table / .schema aliases.

  • the index method for defing sql indices.

  • precompiles the object lifecycle callbacks.



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/og/store/sql.rb', line 107

def enchant(klass, manager)
  # setup the table where this class is mapped.

  if klass.schema_inheritance_child?
    # farms: allow deeper inheritance (TODO: use annotation :superclass)
    klass.const_set 'OGTABLE', table(klass.schema_inheritance_root_class)
  else
    klass.const_set 'OGTABLE', table(klass)
  end

  # Define table and schema aliases for OGTABLE.
  
  klass.module_eval %{
    def self.table; OGTABLE; end
    def self.schema; OGTABLE; end
  }

  eval_og_allocate(klass)

  # Perform base store enchantment.
  
  super

  unless klass.polymorphic_parent?
    # precompile class specific lifecycle methods.
    
    eval_og_create_schema(klass)
    eval_og_insert(klass)
    eval_og_update(klass)
    eval_og_delete(klass)

    # create the table if needed.
    
    klass.allocate.og_create_schema(self)

    # finish up with eval_og_read, since we can't do that
    # until after the table is created.
    # Possible FIXME:  This means you can't do any find-type
    # operations in og_create_schema.  Luckily, you're most
    # likely to want to do .create, which is covered by 
    # og_insert.
    
    eval_og_read(klass)
  end
end

#eval_og_allocate(klass) ⇒ Object

Precompile a class specific allocate method. If this is an STI parent classes it reads the class from the resultset.



996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
# File 'lib/og/store/sql.rb', line 996

def eval_og_allocate(klass)  
  if klass.schema_inheritance? 
    klass.module_eval %{
      def self.og_allocate(res, row = 0)
        Object.constant(res['ogtype']).allocate
      rescue TypeError => e
        # TODO: use res['ogtype'] here, this is slow!
        # But res['ogtype'] isn't implemented in -pr and some mysql exts,
        # create compat layer
        col = ogmanager.store.create_field_map(self)[:ogtype]
        ogmanager.put_store
        Object.constant(res[col]).allocate
      end
    }
  else
    klass.module_eval %{
      def self.og_allocate(res, row = 0)
        self.allocate
      end
    }
  end
end

#eval_og_create_schema(klass) ⇒ Object

Creates the schema for this class. Can be intercepted with aspects to add special behaviours.



978
979
980
981
982
983
984
985
986
987
988
989
990
991
# File 'lib/og/store/sql.rb', line 978

def eval_og_create_schema(klass)
  klass.module_eval %{
    def og_create_schema(store)
      if Og.create_schema
        #{insert_advices :pre, :og_create_schema, klass, :advices}
        unless self.class.schema_inheritance_child?
          store.create_table #{klass}
        end
        store.evolve_schema(#{klass})
        #{insert_advices :post, :og_create_schema, klass, :advices}
      end
    end
  }
end

#eval_og_delete(klass) ⇒ Object

Compiles the og_delete method for this class. This method is used to delete instances of this class.



950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
# File 'lib/og/store/sql.rb', line 950

def eval_og_delete klass
  klass.module_eval %{
    def og_delete(store, cascade = true)
      #{insert_advices :pre, :og_delete, klass, :advices}
      
      if cascade
        
        transaction do |tx|
          tx.exec "DELETE FROM #{klass.table} WHERE #{pk_field klass}=\#{pk}"
          if descendants = #{klass}.ann.self[:descendants]
            descendants.each do |dclass, foreign_key|
              tx.exec "DELETE FROM \#{dclass::OGTABLE} WHERE \#{foreign_key}=\#{pk}"
            end
          end
        end
        
      else
        tx.exec "DELETE FROM #{klass.table} WHERE #{pk_field klass}=\#{pk}"
      end
      
      #{insert_advices :post, :og_delete, klass, :advices}
    end
  }
end

#eval_og_insert(klass) ⇒ Object

Compile the og_insert method for the class. This method is used to create insert the object into a new Row in the database. – Override the og_insert_kernel method to customize for adapters. ++



847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
# File 'lib/og/store/sql.rb', line 847

def eval_og_insert(klass)
  fields = []
  values = []
  
  for a in klass.serializable_attributes
    anno = klass.ann(a)
    fields << field_for_attribute(a, anno)
    values << write_attr(a, anno) 
  end

  # If the class participates in STI, automatically insert
  # an ogtype serializable attribute.
  
  if klass.schema_inheritance?
    values[fields.index(:ogtype)] = quote(klass.name)
  end

  fields = fields.join(', ')
  values = values.join(', ')
      
  sql = "INSERT INTO #{klass.table} (#{fields}) VALUES (#{values})"

  klass.module_eval %{ 
    def og_insert(store)
      #{insert_advices :pre, :og_insert, klass, :advices}
      #{insert_sql sql, klass}
      #{insert_advices :post, :og_insert, klass, :advices}
    end
  }
end

#eval_og_read(klass) ⇒ Object

Compile the og_read method for the class. This method is used to read (deserialize) the given class from the store. In order to allow for changing field/attribute orders a field mapping hash is used.



920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
# File 'lib/og/store/sql.rb', line 920

def eval_og_read(klass)
  code = []
  
  attrs = klass.attributes
  field_map = create_field_map(klass)

  for a in attrs
    anno = klass.ann(a)
    
    f = field_for_attribute(a, anno)

    if col = field_map[f]
      code << "@#{a} = #{read_attr a, anno, col}"
    end
  end

  code = code.join('; ')

  klass.module_eval %{
     def og_read(res, row = 0, offset = 0)
      #{insert_advices :pre, :og_read, klass, :advices}
      #{code}
      #{insert_advices :post, :og_read, klass, :advices}
    end
  }
end

#eval_og_update(klass) ⇒ Object

Compile the og_update method for the class.



889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
# File 'lib/og/store/sql.rb', line 889

def eval_og_update(klass)
  pk = klass.primary_key

  updates = []
  
  for a in klass.serializable_attributes.reject { |a| a == pk }
    anno = klass.ann(a)
    updates << "#{field_for_attribute a, anno}=#{write_attr a, anno}"
  end

  updates = updates.join(', ')
  
  sql = "UPDATE #{klass.table} SET #{updates} WHERE #{pk_field klass}=#\{@#{pk}\}"

  klass.module_eval %{
    def og_update(store, options = nil)
      #{insert_advices :pre, :og_update, klass, :advices}
      sql = "#{sql}"
      sql << " AND \#{options[:condition]}" if options and options[:condition]
      changed = store.sql_update(sql)
      #{insert_advices :post, :og_update, klass, :advices}
      return changed
    end
  }    
end

#exec(sql, rescue_exception = true) ⇒ Object

Perform an sql query with no results.



444
445
446
447
448
449
450
451
452
453
# File 'lib/og/store/sql.rb', line 444

def exec(sql, rescue_exception = true)
  Logger.debug sql if $DBG
  exec_statement(sql)
rescue Object => ex
  if rescue_exception
    handle_sql_exception(ex, sql)
  else 
    raise
  end
end

#exec_statement(sql) ⇒ Object

– Override. ++



459
460
461
# File 'lib/og/store/sql.rb', line 459

def exec_statement(sql)
  return @conn.exec(sql)
end

#field_for_attribute(a, anno) ⇒ Object

Return the SQL table field for the given serializable attribute. You can override the default field name by annotating the attribute with a :field annotation.



651
652
653
# File 'lib/og/store/sql.rb', line 651

def field_for_attribute(a, anno)
  (f = anno[:field]) ? f : a
end

#field_sql_for_attribute(a, anno) ⇒ Object



655
656
657
658
659
660
661
662
663
664
665
666
667
668
# File 'lib/og/store/sql.rb', line 655

def field_sql_for_attribute(a, anno)
  field = field_for_attribute(a, anno).to_s

  if anno.sql?
    field << " #{anno.sql}"
  else
    field << " #{sql_type_for_class(anno.class)}"
    field << " UNIQUE" if anno.unique?  
    field << " DEFAULT #{quote(anno.default)} NOT NULL" if anno.default?
    field << " #{anno.extra_sql}" if anno.extra_sql?
  end

  return field
end

#fields_for_class(klass) ⇒ Object

Create the fields that correspond to the class serializable attributes. The generated fields array is used in create_table.

If the property has an :sql annotation this overrides the default mapping. If the property has an :extra_sql annotation the extra sql is appended after the default mapping.



678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
# File 'lib/og/store/sql.rb', line 678

def fields_for_class(klass)
  fields = []
  attrs = serializable_attributes_for_class(klass)

  for a in attrs
    anno = klass.ann[a]
    if anno.null?
      klass.subclasses.each do |subklass|
        anno = subklass.ann[a] if anno.null?
      end
    end
    fields << field_sql_for_attribute(a, anno)
  end

  return fields
end

#find(options) ⇒ Object

Find a collection of objects.

Examples

User.find(:condition => ‘age > 15’, :order => ‘score ASC’, :offet => 10, :limit =>10) Comment.find(:include => :entry)



233
234
235
236
237
# File 'lib/og/store/sql.rb', line 233

def find(options)  
  klass = options[:class]
  sql = resolve_options(klass, options)
  read_all(query(sql), klass, options)
end

#find_one(options) ⇒ Object

Find one object.



241
242
243
244
245
246
247
# File 'lib/og/store/sql.rb', line 241

def find_one(options)
  klass = options[:class]
  # gmosx, THINK: should not set this by default.
  # options[:limit] ||= 1        
  sql = resolve_options(klass, options)
  read_one(query(sql), klass, options)
end

#force_primary_key(klass) ⇒ Object

Force the creation of a primary key class.



88
89
90
91
92
93
94
95
# File 'lib/og/store/sql.rb', line 88

def force_primary_key(klass)
  # Automatically add an :oid serializable field if none is 
  # defined and no other primary key is defined.
  
  if klass.primary_key == :oid and !klass.attributes.include?(:oid)
    klass.attr_accessor :oid, Fixnum, :sql => primary_key_type
  end
end

#handle_sql_exception(ex, sql = nil) ⇒ Object

Gracefully handle a backend exception.

Raises:



465
466
467
468
469
470
471
472
# File 'lib/og/store/sql.rb', line 465

def handle_sql_exception(ex, sql = nil)
  Logger.error "DB error #{ex}, [#{sql}]"
  Logger.error ex.backtrace.join("\n")
  raise StoreException.new(ex, sql) if Og.raise_store_exceptions

  # FIXME: should return :error or something.
  return nil 
end

#insert_sql(sql, klass) ⇒ Object

The insert sql statements.



880
881
882
883
884
885
# File 'lib/og/store/sql.rb', line 880

def insert_sql(sql, klass)
  %{
  store.exec "#{sql}"
  @#{klass.primary_key} = store.last_insert_id
  }
end

#join(obj1, obj2, table, options = nil) ⇒ Object

Relate two objects through an intermediate join table. Typically used in joins_many and many_to_many relations.



134
135
136
137
138
139
140
141
142
# File 'lib/og/store/sql/join.rb', line 134

def join(obj1, obj2, table, options = nil)
  first, second = join_object_ordering(obj1, obj2)
  first_key, second_key = ordered_join_table_keys(obj1.class, obj2.class)
  if options
    exec "INSERT INTO #{table} (#{first_key},#{second_key}, #{options.keys.join(',')}) VALUES (#{first.pk},#{second.pk}, #{options.values.map { |v| quote(v) }.join(',')})"
  else
    exec "INSERT INTO #{table} (#{first_key},#{second_key}) VALUES (#{first.pk}, #{second.pk})"
  end
end

#last_insert_id(klass = nil) ⇒ Object

Return the last inserted row id. – Override –



489
490
491
# File 'lib/og/store/sql.rb', line 489

def last_insert_id(klass = nil)
  # return last insert id
end

#load(pk, klass) ⇒ Object Also known as: exist?

Loads an object from the store using the primary key. Returns nil if the passes pk is nil.



158
159
160
161
162
163
164
165
# File 'lib/og/store/sql.rb', line 158

def load(pk, klass)
  return nil unless pk
  
  sql = "SELECT * FROM #{klass.table} WHERE #{pk_field klass}=#{quote(pk)}"
  sql << " AND ogtype='#{klass}'" if klass.schema_inheritance_child?
  res = query sql
  read_one(res, klass)
end

#pk_field(klass) ⇒ Object

Generates the SQL field of the primary key for this class.



832
833
834
835
# File 'lib/og/store/sql.rb', line 832

def pk_field klass
  pk = klass.primary_key
  return klass.ann(pk)[:field] || pk
end

#prepare_statement(condition) ⇒ Object

takes an array, the first parameter of which is a prepared statement style string; this handles parameter escaping.



607
608
609
610
611
612
613
614
# File 'lib/og/store/sql.rb', line 607

def prepare_statement(condition)
  args = condition.dup
  str = args.shift
  # ? handles a single type.
  # ?* handles an array.
  args.each { |arg| str.sub!(/\?\*/, quotea(arg)); str.sub!(/\?/, quote(arg)) }
  condition = str
end

#primary_key_typeObject

The type used for default primary keys.



82
83
84
# File 'lib/og/store/sql.rb', line 82

def primary_key_type
  'integer PRIMARY KEY'
end

#query(sql, rescue_exception = true) ⇒ Object

Perform an sql query with results.



423
424
425
426
427
428
429
430
431
432
# File 'lib/og/store/sql.rb', line 423

def query(sql, rescue_exception = true)
  Logger.debug sql if $DBG
  return query_statement(sql)
rescue Object => ex
  if rescue_exception
    handle_sql_exception(ex, sql)
  else 
    raise
  end
end

#query_statement(sql) ⇒ Object

– Override. ++



438
439
440
# File 'lib/og/store/sql.rb', line 438

def query_statement(sql)
  return @conn.query(sql)
end

#read_all(res, klass, options = nil) ⇒ Object

Deserialize all objects from the ResultSet.



1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
# File 'lib/og/store/sql.rb', line 1100

def read_all(res, klass, options = nil)
  return [] if res.blank?

  if options and join_relations = options[:include]
    join_relations = [join_relations].flatten.collect do |n| 
      klass.relation(n) 
    end
  end

  objects = []

  if options and options[:select]
    res.each_row do |res_row, row|    
      obj = klass.og_allocate(res_row, row)
      read_row(obj, res, res_row, row)
      objects << obj
    end
  else
    res.each_row do |res_row, row|    
      obj = klass.og_allocate(res_row, row)
      obj.og_read(res_row, row)
      read_join_relations(obj, res_row, row, join_relations) if join_relations
      objects << obj
    end
  end

  return objects

ensure
  res.close
end

#read_attr(s, a, col) ⇒ Object

Generate code to deserialize an SQL table field into an attribute. – No need to optimize this, used only to precalculate code. ++



765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
# File 'lib/og/store/sql.rb', line 765

def read_attr(s, a, col)
  store = self.class
  
  if a.class.ancestor? Integer
    "#{store}.parse_int(res[#{col} + offset])"

  elsif a.class.ancestor? Float
    "#{store}.parse_float(res[#{col} + offset])"

  elsif a.class.ancestor? String
    "res[#{col} + offset]"

  elsif a.class.ancestor? Time
    "#{store}.parse_timestamp(res[#{col} + offset])"

  elsif a.class.ancestor? Date
    "#{store}.parse_date(res[#{col} + offset])"

  elsif a.class.ancestor? TrueClass
    "#{store}.parse_boolean(res[#{col} + offset])"

  elsif a.class.ancestor? Og::Blob
    "#{store}.parse_blob(res[#{col} + offset])"

  else 
    "YAML::load(res[#{col} + offset])"
  end        
end

#read_fieldObject

Read a field (column) from a result set row.



1039
1040
# File 'lib/og/store/sql.rb', line 1039

def read_field
end

#read_join_relations(obj, res_row, row, join_relations) ⇒ Object

Deserialize the join relations.



1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
# File 'lib/og/store/sql.rb', line 1055

def read_join_relations(obj, res_row, row, join_relations)
  offset = obj.class.serializable_attributes.size 

  for rel in join_relations 
    rel_obj = rel[:target_class].og_allocate(res_row, row)
    rel_obj.og_read(res_row, row, offset) 
    offset += rel_obj.class.serializable_attributes.size 
    obj.instance_variable_set("@#{rel[:name]}", rel_obj)
  end
end

#read_one(res, klass, options = nil) ⇒ Object

Deserialize one object from the ResultSet.



1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
# File 'lib/og/store/sql.rb', line 1068

def read_one(res, klass, options = nil)
  return nil if res.blank?

  if options and join_relations = options[:include]
    join_relations = [join_relations].flatten.collect do |n| 
      klass.relation(n) 
    end
  end

  res_row = res.next
  
  # causes STI classes to come back as the correct child class 
  # if accessed from the superclass.
  
  klass = Og::Entity::entity_from_string(res_row[0]) if klass.schema_inheritance?
  obj = klass.og_allocate(res_row, 0)

  if options and options[:select]
    read_row(obj, res, res_row, 0)
  else
    obj.og_read(res_row)
    read_join_relations(obj, res_row, 0, join_relations) if join_relations
  end

  return obj

ensure
  res.close
end

#read_row(obj, res, res_row, row) ⇒ Object

Dynamicaly deserializes a result set row into an object. Used for specialized queries or join queries. Please note that this deserialization method is slower than the precompiled og_read method.



1047
1048
1049
1050
1051
# File 'lib/og/store/sql.rb', line 1047

def read_row(obj, res, res_row, row)
  res.fields.each_with_index do |field, idx|
    obj.instance_variable_set "@#{field}", res_row[idx]
  end
end

#reload(obj, pk) ⇒ Object

Reloads an object from the store. Returns nil if the passes pk is nil.



171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/og/store/sql.rb', line 171

def reload(obj, pk)
  return nil unless pk

  klass = obj.class
  raise 'Cannot reload unmanaged object' unless obj.saved?
  sql = "SELECT * FROM #{klass.table} WHERE #{pk_field klass}=#{quote(pk)}"
  sql << " AND ogtype='#{klass}'" if klass.schema_inheritance_child?
  res = query sql
  obj.og_read(res.next, 0)
ensure
  res.close if res
end

#resolve_limit_options(options, sql) ⇒ Object

Subclasses can override this if they need some other order. This is needed because different backends require different order of the keywords.



620
621
622
623
624
625
626
627
628
# File 'lib/og/store/sql.rb', line 620

def resolve_limit_options(options, sql)
  if limit = options[:limit]
    sql << " LIMIT #{limit}"

    if offset = options[:offset]
      sql << " OFFSET #{offset}"
    end
  end
end

#resolve_options(klass, options) ⇒ Object

Resolve the finder options. Also takes scope into account. This method handles among other the following cases:

User.find :condition => “name LIKE ‘g%’”, :order => ‘name ASC’ User.find :where => “name LIKE ‘g%’”, :order => ‘name ASC’ User.find :sql => “WHERE name LIKE ‘g%’ ORDER BY name ASC” User.find :condition => [ ‘name LIKE ?’, ‘g%’ ], :order => ‘name ASC’, :limit => 10

If an array is passed as a condition, use prepared statement style escaping. For example:

User.find :condition => [ ‘name = ? AND age > ?’, ‘gmosx’, 12 ]

Proper escaping is performed to avoid SQL injection attacks. – FIXME: cleanup/refactor, this is an IMPORTANT method. ++



511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
# File 'lib/og/store/sql.rb', line 511

def resolve_options(klass, options)
  # Factor in scope.
  
  if scope = klass.get_scope
    scope = scope.dup
    scond = scope.delete(:condition)
    scope.update(options)
    options = scope
  end

  if sql = options[:sql]
    sql = "SELECT * FROM #{klass.table} " + sql unless sql =~ /SELECT/i
    return sql
  end

  tables = [klass::OGTABLE]

  if included = options[:include]
    join_conditions = []

    for name in [included].flatten
      if rel = klass.relation(name)
        target_table = rel[:target_class]::OGTABLE
        tables << target_table

        if rel.is_a?(JoinsMany)
          tables << rel[:join_table]
          owner_key, target_key = klass.ogmanager.store.join_table_keys(klass, rel[:target_class])
          join_conditions << "#{rel.join_table}.#{owner_key}=#{klass::OGTABLE}.#{rel.owner_class.primary_key} AND \
                              #{rel.join_table}.#{target_key}=#{rel.target_class::OGTABLE}.#{rel.target_class.primary_key}"
        else
          join_conditions << "#{klass::OGTABLE}.#{rel.foreign_key}=#{target_table}.#{rel.target_class.primary_key}"
        end
      else
        raise 'Unknown relation name'
      end
    end

    fields = tables.collect { |t| "#{t}.*" }.join(',')

    update_condition options, join_conditions.join(' AND ')
  elsif fields = options[:select]
    # query the provided fields.
  else
    fields = '*'
  end

  if join_table = options[:join_table]
    tables << join_table
    update_condition options, options[:join_condition]
  end

  # Factor in scope in the conditions.
  
  update_condition(options, scond) if scond

  # rp: type is not set in all instances such as Class.first 
  # so this fix goes here for now.
  
  if ogtype = options[:type] || (klass.schema_inheritance_child? ? "#{klass}" : nil)
    update_condition options, "ogtype='#{ogtype}'"
  end

  sql = "SELECT #{fields} FROM #{tables.join(',')}"

  if condition = options[:condition] || options[:where]
    # If an array is passed as a condition, use prepared 
    # statement style escaping. 
           
    if condition.is_a?(Array)
      condition = prepare_statement(condition)
    end

    sql << " WHERE #{condition}"
  end
  
  if group = options[:group] || options[:group_by]
    sql << " GROUP BY #{group}"
  end

  if order = options[:order] || options[:order_by]
    sql << " ORDER BY #{order}"
  end

  resolve_limit_options(options, sql)

  if extra = options[:extra] || options[:extra_sql]
    sql << " #{extra}"
  end

  return sql
end

#select(sql, klass) ⇒ Object Also known as: find_by_sql

Perform a custom sql query and deserialize the results.



252
253
254
255
# File 'lib/og/store/sql.rb', line 252

def select(sql, klass)
  sql = "SELECT * FROM #{klass.table} " + sql unless sql =~ /SELECT/i
  read_all(query(sql), klass)
end

#select_one(sql, klass) ⇒ Object Also known as: find_by_sql_one

Specialized one result version of select.



260
261
262
263
# File 'lib/og/store/sql.rb', line 260

def select_one(sql, klass)
  sql = "SELECT * FROM #{klass.table} " + sql unless sql =~ /SELECT/i
  read_one(query(sql), klass)
end

#serializable_attributes_for_class(klass) ⇒ Object

Return either the serializable attributes for the class or, in the case of schema inheritance, all of the serializable attributes of the class hierarchy, starting from the schema inheritance root class.



637
638
639
640
641
642
643
644
645
# File 'lib/og/store/sql.rb', line 637

def serializable_attributes_for_class(klass) 
  attrs = klass.serializable_attributes
  if klass.schema_inheritance?
    for desc in klass.schema_inheritance_root_class.descendents
      attrs.concat desc.serializable_attributes
    end
  end
  return attrs.uniq
end

#sql_indices_for_class(klass) ⇒ Object

Returns the SQL indexed serializable attributes for the given class.



698
699
700
701
702
703
704
705
706
# File 'lib/og/store/sql.rb', line 698

def sql_indices_for_class klass
  indices = []

  for a in klass.serializable_attributes
    indices << a if klass.ann(a).index?
  end

  return indices
end

#sql_type_for_class(klass) ⇒ Object

Return the SQL type for the given Ruby class.



710
711
712
# File 'lib/og/store/sql.rb', line 710

def sql_type_for_class klass
  @typemap[klass]    
end

#sql_update(sql) ⇒ Object

Perform an sql update, return the number of updated rows. – Override ++



479
480
481
482
# File 'lib/og/store/sql.rb', line 479

def sql_update(sql)
  exec(sql)
  # return affected rows.
end

#table_exists?(table) ⇒ Boolean Also known as: table_exist?

Returns true if a table exists within the database, false otherwise.

Returns:

  • (Boolean)


1145
1146
1147
# File 'lib/og/store/sql.rb', line 1145

def table_exists?(table)
  table_info(table) ? true : false
end

#type_cast(klass, val) ⇒ Object



1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
# File 'lib/og/store/sql.rb', line 1021

def type_cast(klass, val)
  typemap = {
    Time      => :parse_timestamp,
    Date      => :parse_date,
    TrueClass => :parse_boolean
  }

  if method = typemap[klass]
    send(method, val)
  else
    Integer(val) rescue Float(val) rescue raise "No conversion for #{klass} (#{val.inspect})"
  end
end

#unjoin(obj1, obj2, table) ⇒ Object

Unrelate two objects be removing their relation from the join table.



147
148
149
150
151
# File 'lib/og/store/sql/join.rb', line 147

def unjoin(obj1, obj2, table)
  first, second = join_object_ordering(obj1, obj2)
  first_key, second_key = ordered_join_table_keys(obj1.class, obj2.class)
  exec "DELETE FROM #{table} WHERE #{first_key}=#{first.pk} AND #{second_key}=#{second.pk}"    
end

#update(obj, options = nil) ⇒ Object

If an attributes collection is provided, only updates the selected attributes. Pass the required attributes as symbols or strings. – gmosx, THINK: condition is not really useful here :( ++



191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/og/store/sql.rb', line 191

def update(obj, options = nil)
  if options and attrs = options[:only]
    if attrs.is_a?(Array)
      set = []
      for a in attrs
        set << "#{a}=#{quote(obj.send(a))}"
      end
      set = set.join(',')
    else
      set = "#{attrs}=#{quote(obj.send(attrs))}"
    end
    sql = "UPDATE #{obj.class.table} SET #{set} WHERE #{pk_field obj.class}=#{quote(obj.pk)}"
    sql << " AND #{options[:condition]}" if options[:condition]
    sql_update(sql)
  else
    obj.og_update(self, options)
  end
end

#update_by_sql(target, set, options = nil) ⇒ Object

More generalized method, also allows for batch updates.



212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/og/store/sql.rb', line 212

def update_by_sql(target, set, options = nil)
  set = set.gsub(/@/, '')

  if target.is_a? Class
    sql = "UPDATE #{target.table} SET #{set} "
    sql << " WHERE #{options[:condition]}" if options and options[:condition]
    sql_update(sql)
  else
    sql = "UPDATE #{target.class.table} SET #{set} WHERE #{pk_field target.class}=#{quote(target.pk)}"
    sql << " AND #{options[:condition]}" if options and options[:condition]
    sql_update(sql)
  end      
end

#update_condition(options, cond, joiner = 'AND') ⇒ Object

Helper method that updates the condition string.



1134
1135
1136
1137
1138
1139
1140
# File 'lib/og/store/sql.rb', line 1134

def update_condition(options, cond, joiner = 'AND')
  if options[:condition]
    [options[:condition]].flatten[0] <<  " #{joiner} #{cond}"
  else
    options[:condition] = cond
  end
end

#write_attr(s, a) ⇒ Object

Generate code to serialize an attribute to an SQL table field. YAML is used (instead of Marshal) to store general Ruby objects to be more portable.

Input

  • s = attribute symbol

  • a = attribute annotations

– No need to optimize this, used only to precalculate code. FIXME: add extra handling for float. ++



729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
# File 'lib/og/store/sql.rb', line 729

def write_attr(s, a)
  store = self.class
  
  if a.class.ancestor? Integer
    "#\{@#{s} || 'NULL'\}"
  
  elsif a.class.ancestor? Float
    "#\{@#{s} || 'NULL'\}"    
  
  elsif a.class.ancestor? String
    %|#\{@#{s} ? "'#\{#{store}.escape(@#{s})\}'" : 'NULL'\}|
  
  elsif a.class.ancestor? Time
    %|#\{@#{s} ? "'#\{#{store}.timestamp(@#{s})\}'" : 'NULL'\}|
  
  elsif a.class.ancestor? Date 
    %|#\{@#{s} ? "'#\{#{store}.date(@#{s})\}'" : 'NULL'\}|
  
  elsif a.class.ancestor? TrueClass
    "#\{@#{s} ? \"'t'\" : 'NULL' \}"
  
  elsif a.class.ancestor? Og::Blob 
    %|#\{@#{s} ? "'#\{#{store}.escape(#{store}.blob(@#{s}))\}'" : 'NULL'\}|      
  
  else 
    # keep the '' for nil symbols.
    %|#\{@#{s} ? "'#\{#{store}.escape(@#{s}.to_yaml)\}'" : "''"\}|
  end
end