Class: Tina4::ORM

Inherits:
Object
  • Object
show all
Includes:
FieldTypes
Defined in:
lib/tina4/orm.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods included from FieldTypes

included

Constructor Details

#initialize(attributes = {}) ⇒ ORM

Returns a new instance of ORM.



445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
# File 'lib/tina4/orm.rb', line 445

def initialize(attributes = {})
  @persisted = false
  @errors = []
  @relationship_cache = {}
  attributes.each do |key, value|
    setter = "#{key}="
    __send__(setter, value) if respond_to?(setter)
  end
  # Set defaults
  self.class.field_definitions.each do |name, opts|
    if __send__(name).nil? && opts[:default]
      __send__("#{name}=", opts[:default])
    end
  end
end

Class Method Details

.all(limit: nil, offset: nil, order_by: nil, include: nil) ⇒ Object

-> list



259
260
261
262
263
264
265
266
267
268
269
# File 'lib/tina4/orm.rb', line 259

def all(limit: nil, offset: nil, order_by: nil, include: nil) # -> list[Self]
  sql = "SELECT * FROM #{table_name}"
  if soft_delete
    sql += " WHERE #{soft_delete_field} IS NULL OR #{soft_delete_field} = 0"
  end
  sql += " ORDER BY #{order_by}" if order_by
  results = db.fetch(sql, [], limit: limit, offset: offset)
  instances = results.map { |row| from_hash(row) }
  eager_load(instances, include) if include
  instances
end

.auto_crudObject

Auto-CRUD flag: when set to true, registers this model for CRUD route generation



65
66
67
# File 'lib/tina4/orm.rb', line 65

def auto_crud
  @auto_crud || false
end

.auto_crud=(val) ⇒ Object



69
70
71
72
73
74
# File 'lib/tina4/orm.rb', line 69

def auto_crud=(val)
  @auto_crud = val
  if val
    Tina4::AutoCrud.register(self) if defined?(Tina4::AutoCrud)
  end
end

.auto_mapObject

Auto-map flag (no-op in Ruby since snake_case is native)



56
57
58
# File 'lib/tina4/orm.rb', line 56

def auto_map
  @auto_map.nil? ? true : @auto_map
end

.auto_map=(val) ⇒ Object



60
61
62
# File 'lib/tina4/orm.rb', line 60

def auto_map=(val)
  @auto_map = val
end

.belongs_to(name, class_name: nil, foreign_key: nil) ⇒ Object

belongs_to :user, class_name: “User”, foreign_key: “user_id”



108
109
110
111
112
113
114
115
116
117
118
# File 'lib/tina4/orm.rb', line 108

def belongs_to(name, class_name: nil, foreign_key: nil) # -> nil
  relationship_definitions[name] = {
    type: :belongs_to,
    class_name: class_name || name.to_s.split("_").map(&:capitalize).join,
    foreign_key: foreign_key || "#{name}_id"
  }

  define_method(name) do
    load_belongs_to(name)
  end
end

.cached(sql, params = [], ttl: 60, limit: 20, offset: 0, include: nil) ⇒ Object

SQL query with in-memory result caching. Results are cached by (class, sql, params, limit, offset) for ttl seconds.



314
315
316
317
318
319
320
321
322
323
# File 'lib/tina4/orm.rb', line 314

def cached(sql, params = [], ttl: 60, limit: 20, offset: 0, include: nil) # -> list[Self]
  @_query_cache ||= Tina4::QueryCache.new(default_ttl: ttl, max_size: 500)
  cache_key = Tina4::QueryCache.query_key("#{name}:#{sql}", params + [limit, offset])
  hit = @_query_cache.get(cache_key)
  return hit unless hit.nil?

  results = select(sql, params, limit: limit, offset: offset, include: include)
  @_query_cache.set(cache_key, results, ttl: ttl, tags: [name])
  results
end

.clear_cacheObject

Clear all cached query results for this model.



326
327
328
# File 'lib/tina4/orm.rb', line 326

def clear_cache # -> nil
  @_query_cache&.clear_tag(name)
end

.clear_rel_cacheObject

Clear the relationship cache on all loaded instances (class-level helper). Useful after bulk operations when you want to force relationship re-loads.



408
409
410
411
# File 'lib/tina4/orm.rb', line 408

def clear_rel_cache # -> nil
  @_rel_cache = {}
  nil
end

.count(conditions = nil, params = []) ⇒ Object

-> int



283
284
285
286
287
288
289
290
291
292
293
# File 'lib/tina4/orm.rb', line 283

def count(conditions = nil, params = []) # -> int
  sql = "SELECT COUNT(*) as cnt FROM #{table_name}"
  where_parts = []
  if soft_delete
    where_parts << "(#{soft_delete_field} IS NULL OR #{soft_delete_field} = 0)"
  end
  where_parts << "(#{conditions})" if conditions
  sql += " WHERE #{where_parts.join(' AND ')}" unless where_parts.empty?
  result = db.fetch_one(sql, params)
  result[:cnt].to_i
end

.create(attributes = {}) ⇒ Object

-> Self



295
296
297
298
299
# File 'lib/tina4/orm.rb', line 295

def create(attributes = {}) # -> Self
  instance = new(attributes)
  instance.save
  instance
end

.create_tableObject

-> bool



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
365
366
367
368
369
370
371
372
373
374
375
# File 'lib/tina4/orm.rb', line 336

def create_table # -> bool
  return true if db.table_exists?(table_name)

  type_map = {
    integer: "INTEGER",
    string: "VARCHAR(255)",
    text: "TEXT",
    float: "REAL",
    decimal: "REAL",
    boolean: "INTEGER",
    date: "DATE",
    datetime: "DATETIME",
    timestamp: "TIMESTAMP",
    blob: "BLOB",
    json: "TEXT"
  }

  col_defs = []
  field_definitions.each do |name, opts|
    sql_type = type_map[opts[:type]] || "TEXT"
    if opts[:type] == :string && opts[:length]
      sql_type = "VARCHAR(#{opts[:length]})"
    end

    parts = ["#{name} #{sql_type}"]
    parts << "PRIMARY KEY" if opts[:primary_key]
    parts << "AUTOINCREMENT" if opts[:auto_increment]
    parts << "NOT NULL" if !opts[:nullable] && !opts[:primary_key]
    if opts[:default] && !opts[:auto_increment]
      default_val = opts[:default].is_a?(String) ? "'#{opts[:default]}'" : opts[:default]
      parts << "DEFAULT #{default_val}"
    end
    col_defs << parts.join(" ")
  end

  sql = "CREATE TABLE IF NOT EXISTS #{table_name} (#{col_defs.join(', ')})"
  db.execute(sql)
  db.commit
  true
end

.dbObject



20
21
22
# File 'lib/tina4/orm.rb', line 20

def db
  @db || Tina4.database || auto_discover_db
end

.db=(database) ⇒ Object

Per-model database binding



25
26
27
# File 'lib/tina4/orm.rb', line 25

def db=(database)
  @db = database
end

.eager_load(instances, include_list) ⇒ Object

Eager load relationships for a collection of instances (prevents N+1). include is an array of relationship names, supporting dot notation for nesting.



170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/tina4/orm.rb', line 170

def eager_load(instances, include_list)
  return if instances.nil? || instances.empty?

  # Group includes: top-level and nested
  top_level = {}
  include_list.each do |inc|
    parts = inc.to_s.split(".", 2)
    rel_name = parts[0].to_sym
    top_level[rel_name] ||= []
    top_level[rel_name] << parts[1] if parts.length > 1
  end

  top_level.each do |rel_name, nested|
    rel = relationship_definitions[rel_name]
    next unless rel

    klass = Object.const_get(rel[:class_name])
    pk = primary_key_field || :id

    case rel[:type]
    when :has_one, :has_many
      fk = rel[:foreign_key] || "#{name.split('::').last.downcase}_id"
      pk_values = instances.map { |inst| inst.__send__(pk) }.compact.uniq
      next if pk_values.empty?

      placeholders = pk_values.map { "?" }.join(",")
      sql = "SELECT * FROM #{klass.table_name} WHERE #{fk} IN (#{placeholders})"
      results = klass.db.fetch(sql, pk_values)
      related_records = results.map { |row| klass.from_hash(row) }

      # Eager load nested
      klass.eager_load(related_records, nested) unless nested.empty?

      # Group by FK
      grouped = {}
      related_records.each do |record|
        fk_val = record.__send__(fk.to_sym) if record.respond_to?(fk.to_sym)
        (grouped[fk_val] ||= []) << record
      end

      instances.each do |inst|
        pk_val = inst.__send__(pk)
        records = grouped[pk_val] || []
        if rel[:type] == :has_one
          inst.instance_variable_get(:@relationship_cache)[rel_name] = records.first
        else
          inst.instance_variable_get(:@relationship_cache)[rel_name] = records
        end
      end

    when :belongs_to
      fk = rel[:foreign_key] || "#{rel_name}_id"
      fk_values = instances.map { |inst|
        inst.respond_to?(fk.to_sym) ? inst.__send__(fk.to_sym) : nil
      }.compact.uniq
      next if fk_values.empty?

      related_pk = klass.primary_key_field || :id
      placeholders = fk_values.map { "?" }.join(",")
      sql = "SELECT * FROM #{klass.table_name} WHERE #{related_pk} IN (#{placeholders})"
      results = klass.db.fetch(sql, fk_values)
      related_records = results.map { |row| klass.from_hash(row) }

      klass.eager_load(related_records, nested) unless nested.empty?

      lookup = {}
      related_records.each { |r| lookup[r.__send__(related_pk)] = r }

      instances.each do |inst|
        fk_val = inst.respond_to?(fk.to_sym) ? inst.__send__(fk.to_sym) : nil
        inst.instance_variable_get(:@relationship_cache)[rel_name] = lookup[fk_val]
      end
    end
  end
end

.exists(pk_value) ⇒ Object

Return true if a record with the given primary key exists.



308
309
310
# File 'lib/tina4/orm.rb', line 308

def exists(pk_value) # -> bool
  find(pk_value) != nil
end

.field_mappingObject

Field mapping: { ‘db_column’ => ‘ruby_attribute’ }



47
48
49
# File 'lib/tina4/orm.rb', line 47

def field_mapping
  @field_mapping || {}
end

.field_mapping=(map) ⇒ Object



51
52
53
# File 'lib/tina4/orm.rb', line 51

def field_mapping=(map)
  @field_mapping = map
end

.find(filter = {}, limit: 100, offset: 0, order_by: nil, include: nil, **extra_filter) ⇒ Object

Find records by filter dict. Always returns an array.

Usage:

User.find(name: "Alice")                  → [User, ...]
User.find({age: 18}, limit: 10)           → [User, ...]
User.find(order_by: "name ASC")            → [User, ...]
User.find                                  → all records

Use find_by_id(id) for single-record primary key lookup.



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/tina4/orm.rb', line 139

def find(filter = {}, limit: 100, offset: 0, order_by: nil, include: nil, **extra_filter) # -> list[Self]
  # Integer or string-digit argument → primary key lookup (returns single record or nil)
  return find_by_id(filter) if filter.is_a?(Integer)

  # Merge keyword-style filters: find(name: "Alice") and find({name: "Alice"}) both work
  filter = filter.merge(extra_filter) unless extra_filter.empty?
  conditions = []
  params = []

  filter.each do |key, value|
    col = field_mapping[key.to_s] || key
    conditions << "#{col} = ?"
    params << value
  end

  if soft_delete
    conditions << "(#{soft_delete_field} IS NULL OR #{soft_delete_field} = 0)"
  end

  sql = "SELECT * FROM #{table_name}"
  sql += " WHERE #{conditions.join(' AND ')}" unless conditions.empty?
  sql += " ORDER BY #{order_by}" if order_by

  results = db.fetch(sql, params, limit: limit, offset: offset)
  instances = results.map { |row| from_hash(row) }
  eager_load(instances, include) if include
  instances
end

.find_by_id(id, include: nil) ⇒ Object

Find a single record by primary key. Returns instance or nil.



397
398
399
400
401
402
403
404
# File 'lib/tina4/orm.rb', line 397

def find_by_id(id, include: nil) # -> Self | nil
  pk = primary_key_field || :id
  sql = "SELECT * FROM #{table_name} WHERE #{pk} = ?"
  if soft_delete
    sql += " AND (#{soft_delete_field} IS NULL OR #{soft_delete_field} = 0)"
  end
  select_one(sql, [id], include: include)
end

.find_or_fail(id) ⇒ Object

-> Self



301
302
303
304
305
# File 'lib/tina4/orm.rb', line 301

def find_or_fail(id) # -> Self
  result = find(id)
  raise "#{name} with #{primary_key_field || :id}=#{id} not found" if result.nil?
  result
end

.from_hash(hash) ⇒ Object



383
384
385
386
387
388
389
390
391
392
393
394
# File 'lib/tina4/orm.rb', line 383

def from_hash(hash)
  instance = new
  mapping_reverse = field_mapping.invert
  hash.each do |key, value|
    # Apply field mapping (db_col => ruby_attr)
    attr_name = mapping_reverse[key.to_s] || key
    setter = "#{attr_name}="
    instance.__send__(setter, value) if instance.respond_to?(setter)
  end
  instance.instance_variable_set(:@persisted, true)
  instance
end

.get_dbObject

Return the database connection used by this model.



414
415
416
# File 'lib/tina4/orm.rb', line 414

def get_db # -> Database
  db
end

.get_db_column(property) ⇒ Object

Map a Ruby property name to its database column name using field_mapping. Returns the column name as a symbol.



420
421
422
423
# File 'lib/tina4/orm.rb', line 420

def get_db_column(property) # -> Symbol
  col = field_mapping[property.to_s] || property
  col.to_sym
end

.has_many(name, class_name: nil, foreign_key: nil) ⇒ Object

has_many :posts, class_name: “Post”, foreign_key: “user_id”



95
96
97
98
99
100
101
102
103
104
105
# File 'lib/tina4/orm.rb', line 95

def has_many(name, class_name: nil, foreign_key: nil) # -> nil
  relationship_definitions[name] = {
    type: :has_many,
    class_name: class_name || name.to_s.sub(/s$/, "").split("_").map(&:capitalize).join,
    foreign_key: foreign_key
  }

  define_method(name) do
    load_has_many(name)
  end
end

.has_one(name, class_name: nil, foreign_key: nil) ⇒ Object

has_one :profile, class_name: “Profile”, foreign_key: “user_id”



82
83
84
85
86
87
88
89
90
91
92
# File 'lib/tina4/orm.rb', line 82

def has_one(name, class_name: nil, foreign_key: nil) # -> nil
  relationship_definitions[name] = {
    type: :has_one,
    class_name: class_name || name.to_s.split("_").map(&:capitalize).join,
    foreign_key: foreign_key
  }

  define_method(name) do
    load_has_one(name)
  end
end

.queryTina4::QueryBuilder

Create a fluent QueryBuilder pre-configured for this model’s table and database.

Usage:

results = User.query.where("active = ?", [1]).order_by("name").get

Returns:



126
127
128
# File 'lib/tina4/orm.rb', line 126

def query # -> QueryBuilder
  QueryBuilder.from_table(table_name, db: db)
end

.relationship_definitionsObject

Relationship definitions



77
78
79
# File 'lib/tina4/orm.rb', line 77

def relationship_definitions
  @relationship_definitions ||= {}
end

.scope(name, filter_sql, params = []) ⇒ Object

-> nil



377
378
379
380
381
# File 'lib/tina4/orm.rb', line 377

def scope(name, filter_sql, params = []) # -> nil
  define_singleton_method(name) do |limit: 20, offset: 0|
    where(filter_sql, params)
  end
end

.select(sql, params = [], limit: nil, offset: nil, include: nil) ⇒ Object

-> list



271
272
273
274
275
276
# File 'lib/tina4/orm.rb', line 271

def select(sql, params = [], limit: nil, offset: nil, include: nil) # -> list[Self]
  results = db.fetch(sql, params, limit: limit, offset: offset)
  instances = results.map { |row| from_hash(row) }
  eager_load(instances, include) if include
  instances
end

.select_one(sql, params = [], include: nil) ⇒ Object

-> Self | nil



278
279
280
281
# File 'lib/tina4/orm.rb', line 278

def select_one(sql, params = [], include: nil) # -> Self | nil
  results = select(sql, params, limit: 1, include: include)
  results.first
end

.soft_deleteObject

Soft delete configuration



30
31
32
# File 'lib/tina4/orm.rb', line 30

def soft_delete
  @soft_delete || false
end

.soft_delete=(val) ⇒ Object



34
35
36
# File 'lib/tina4/orm.rb', line 34

def soft_delete=(val)
  @soft_delete = val
end

.soft_delete_fieldObject



38
39
40
# File 'lib/tina4/orm.rb', line 38

def soft_delete_field
  @soft_delete_field || :is_deleted
end

.soft_delete_field=(val) ⇒ Object



42
43
44
# File 'lib/tina4/orm.rb', line 42

def soft_delete_field=(val)
  @soft_delete_field = val
end

.where(conditions, params = [], limit: 20, offset: 0, include: nil) ⇒ Object

-> list



246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/tina4/orm.rb', line 246

def where(conditions, params = [], limit: 20, offset: 0, include: nil) # -> list[Self]
  sql = "SELECT * FROM #{table_name}"
  if soft_delete
    sql += " WHERE (#{soft_delete_field} IS NULL OR #{soft_delete_field} = 0) AND (#{conditions})"
  else
    sql += " WHERE #{conditions}"
  end
  results = db.fetch(sql, params, limit: limit, offset: offset)
  instances = results.map { |row| from_hash(row) }
  eager_load(instances, include) if include
  instances
end

.with_trashed(conditions = "1=1", params = [], limit: 20, offset: 0) ⇒ Object

-> list



330
331
332
333
334
# File 'lib/tina4/orm.rb', line 330

def with_trashed(conditions = "1=1", params = [], limit: 20, offset: 0) # -> list[Self]
  sql = "SELECT * FROM #{table_name} WHERE #{conditions}"
  results = db.fetch(sql, params, limit: limit, offset: offset)
  results.map { |row| from_hash(row) }
end

Instance Method Details

#belongs_to(related_class, foreign_key: nil) ⇒ Object



782
783
784
785
786
787
788
# File 'lib/tina4/orm.rb', line 782

def belongs_to(related_class, foreign_key: nil)
  fk = foreign_key || "#{related_class.name.split('::').last.downcase}_id"
  fk_value = respond_to?(fk.to_sym) ? __send__(fk.to_sym) : nil
  return nil unless fk_value

  related_class.find_by_id(fk_value)
end

#deleteObject

-> bool



493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
# File 'lib/tina4/orm.rb', line 493

def delete # -> bool
  pk = self.class.primary_key_field || :id
  pk_value = __send__(pk)
  return false unless pk_value

  self.class.db.transaction do |db|
    if self.class.soft_delete
      db.update(
        self.class.table_name,
        { self.class.soft_delete_field => 1 },
        { pk => pk_value }
      )
    else
      db.delete(self.class.table_name, { pk => pk_value })
    end
  end
  @persisted = false
  true
end

#errorsObject



596
597
598
# File 'lib/tina4/orm.rb', line 596

def errors
  @errors
end

#force_deleteObject

-> bool



513
514
515
516
517
518
519
520
521
522
523
# File 'lib/tina4/orm.rb', line 513

def force_delete # -> bool
  pk = self.class.primary_key_field || :id
  pk_value = __send__(pk)
  raise "Cannot delete: no primary key value" unless pk_value

  self.class.db.transaction do |db|
    db.delete(self.class.table_name, { pk => pk_value })
  end
  @persisted = false
  true
end

#has_many(related_class, foreign_key: nil, limit: 100, offset: 0) ⇒ Object



769
770
771
772
773
774
775
776
777
778
779
780
# File 'lib/tina4/orm.rb', line 769

def has_many(related_class, foreign_key: nil, limit: 100, offset: 0)
  pk = self.class.primary_key_field || :id
  pk_value = __send__(pk)
  return [] unless pk_value

  fk = foreign_key || "#{self.class.name.split('::').last.downcase}_id"
  results = related_class.db.fetch(
    "SELECT * FROM #{related_class.table_name} WHERE #{fk} = ?",
    [pk_value], limit: limit, offset: offset
  )
  results.map { |row| related_class.from_hash(row) }
end

#has_one(related_class, foreign_key: nil) ⇒ Object

── Imperative relationship methods (ad-hoc, like Python/PHP/Node) ──



757
758
759
760
761
762
763
764
765
766
767
# File 'lib/tina4/orm.rb', line 757

def has_one(related_class, foreign_key: nil)
  pk = self.class.primary_key_field || :id
  pk_value = __send__(pk)
  return nil unless pk_value

  fk = foreign_key || "#{self.class.name.split('::').last.downcase}_id"
  result = related_class.db.fetch_one(
    "SELECT * FROM #{related_class.table_name} WHERE #{fk} = ?", [pk_value]
  )
  result ? related_class.from_hash(result) : nil
end

#load(filter = nil, params = [], include: nil) ⇒ Object

Load a record into this instance via select_one. Returns true if found and loaded, false otherwise. Load a record into this instance.

Usage:

orm.id = 1; orm.load          — uses PK already set
orm.load("id = ?", [1])       — filter with params
orm.load("id = 1")            — filter string

Returns true if a record was found, false otherwise.



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
# File 'lib/tina4/orm.rb', line 564

def load(filter = nil, params = [], include: nil) # -> bool
  @relationship_cache = {}
  table = self.class.table_name

  if filter.nil?
    pk = self.class.primary_key
    pk_col = self.class.field_mapping[pk.to_s] || pk
    pk_value = __send__(pk)
    return false if pk_value.nil?
    sql = "SELECT * FROM #{table} WHERE #{pk_col} = ?"
    params = [pk_value]
  else
    sql = "SELECT * FROM #{table} WHERE #{filter}"
  end

  result = self.class.select_one(sql, params, include: include)
  return false unless result

  mapping_reverse = self.class.field_mapping.invert
  result.to_h.each do |key, value|
    attr_name = mapping_reverse[key.to_s] || key
    setter = "#{attr_name}="
    __send__(setter, value) if respond_to?(setter)
  end
  @persisted = true
  true
end

#persisted?Boolean

Returns:

  • (Boolean)


592
593
594
# File 'lib/tina4/orm.rb', line 592

def persisted?
  @persisted
end

#restoreObject

-> bool



525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
# File 'lib/tina4/orm.rb', line 525

def restore # -> bool
  raise "Model does not support soft delete" unless self.class.soft_delete

  pk = self.class.primary_key_field || :id
  pk_value = __send__(pk)
  raise "Cannot restore: no primary key value" unless pk_value

  self.class.db.transaction do |db|
    db.update(
      self.class.table_name,
      { self.class.soft_delete_field => 0 },
      { pk => pk_value }
    )
  end
  __send__("#{self.class.soft_delete_field}=", 0) if respond_to?("#{self.class.soft_delete_field}=")
  true
end

#saveObject

-> Self | bool



461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
# File 'lib/tina4/orm.rb', line 461

def save # -> Self | bool
  @errors = []
  @relationship_cache = {} # Clear relationship cache on save
  validate_fields
  return false unless @errors.empty?

  data = to_db_hash(exclude_nil: true)
  pk = self.class.primary_key_field || :id
  pk_value = __send__(pk)

  self.class.db.transaction do |db|
    if @persisted && pk_value
      filter = { pk => pk_value }
      data.delete(pk)
      # Remove mapped primary key too
      mapped_pk = self.class.field_mapping[pk.to_s]
      data.delete(mapped_pk.to_sym) if mapped_pk
      db.update(self.class.table_name, data, filter)
    else
      result = db.insert(self.class.table_name, data)
      if result[:last_id] && respond_to?("#{pk}=")
        __send__("#{pk}=", result[:last_id])
      end
      @persisted = true
    end
  end
  true
rescue => e
  @errors << e.message
  false
end

#select(*fields) ⇒ Object



675
676
677
678
679
680
# File 'lib/tina4/orm.rb', line 675

def select(*fields)
  fields_str = fields.map(&:to_s).join(", ")
  pk = self.class.primary_key_field || :id
  pk_value = __send__(pk)
  self.class.db.fetch_one("SELECT #{fields_str} FROM #{self.class.table_name} WHERE #{pk} = ?", [pk_value])
end

#to_arrayObject Also known as: to_list

-> list



661
662
663
# File 'lib/tina4/orm.rb', line 661

def to_array # -> list
  to_h.values
end

#to_assoc(include: nil, case: 'snake') ⇒ Object



653
654
655
# File 'lib/tina4/orm.rb', line 653

def to_assoc(include: nil, case: 'snake')
  to_h(include: include, case: binding.local_variable_get(:case))
end

#to_dict(include: nil, case: 'snake') ⇒ Object



649
650
651
# File 'lib/tina4/orm.rb', line 649

def to_dict(include: nil, case: 'snake')
  to_h(include: include, case: binding.local_variable_get(:case))
end

#to_h(include: nil, case: 'snake') ⇒ Object

Convert to hash using Ruby attribute names. Optionally include relationships via the include keyword. case: ‘snake’ (default) returns snake_case keys, ‘camel’ returns camelCase keys.



603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
# File 'lib/tina4/orm.rb', line 603

def to_h(include: nil, case: 'snake') # -> dict
  hash = {}
  self.class.field_definitions.each_key do |name|
    hash[name] = __send__(name)
  end

  if include
    # Group includes: top-level and nested
    top_level = {}
    include.each do |inc|
      parts = inc.to_s.split(".", 2)
      rel_name = parts[0].to_sym
      top_level[rel_name] ||= []
      top_level[rel_name] << parts[1] if parts.length > 1
    end

    top_level.each do |rel_name, nested|
      next unless self.class.relationship_definitions.key?(rel_name)
      related = __send__(rel_name)
      if related.nil?
        hash[rel_name] = nil
      elsif related.is_a?(Array)
        hash[rel_name] = related.map { |r| r.to_h(include: nested.empty? ? nil : nested, case: binding.local_variable_get(:case)) }
      else
        hash[rel_name] = related.to_h(include: nested.empty? ? nil : nested, case: binding.local_variable_get(:case))
      end
    end
  end

  case_mode = binding.local_variable_get(:case)
  if case_mode == 'camel'
    camel_hash = {}
    hash.each do |key, value|
      camel_key = Tina4.snake_to_camel(key.to_s).to_sym
      camel_hash[camel_key] = value
    end
    return camel_hash
  end

  hash
end

#to_hash(include: nil, case: 'snake') ⇒ Object



645
646
647
# File 'lib/tina4/orm.rb', line 645

def to_hash(include: nil, case: 'snake')
  to_h(include: include, case: binding.local_variable_get(:case))
end

#to_json(include: nil, **_args) ⇒ Object

-> str



667
668
669
# File 'lib/tina4/orm.rb', line 667

def to_json(include: nil, **_args) # -> str
  JSON.generate(to_h(include: include))
end

#to_object(include: nil, case: 'snake') ⇒ Object



657
658
659
# File 'lib/tina4/orm.rb', line 657

def to_object(include: nil, case: 'snake')
  to_h(include: include, case: binding.local_variable_get(:case))
end

#to_sObject



671
672
673
# File 'lib/tina4/orm.rb', line 671

def to_s
  "#<#{self.class.name} #{to_h}>"
end

#validateObject

-> list



543
544
545
546
547
548
549
550
551
552
# File 'lib/tina4/orm.rb', line 543

def validate # -> list[str]
  errors = []
  self.class.field_definitions.each do |name, opts|
    value = __send__(name)
    if !opts[:nullable] && value.nil? && !opts[:auto_increment] && !opts[:default]
      errors << "#{name} cannot be null"
    end
  end
  errors
end