Class: Tina4::Database

Inherits:
Object
  • Object
show all
Defined in:
lib/tina4/database.rb

Constant Summary collapse

DRIVERS =
{
  "sqlite" => "Tina4::Drivers::SqliteDriver",
  "sqlite3" => "Tina4::Drivers::SqliteDriver",
  "postgres" => "Tina4::Drivers::PostgresDriver",
  "postgresql" => "Tina4::Drivers::PostgresDriver",
  "mysql" => "Tina4::Drivers::MysqlDriver",
  "mssql" => "Tina4::Drivers::MssqlDriver",
  "sqlserver" => "Tina4::Drivers::MssqlDriver",
  "firebird" => "Tina4::Drivers::FirebirdDriver",
  "mongodb" => "Tina4::Drivers::MongodbDriver",
  "mongo" => "Tina4::Drivers::MongodbDriver",
  "odbc" => "Tina4::Drivers::OdbcDriver"
}.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(connection_string = nil, username: nil, password: nil, driver_name: nil, pool: 0) ⇒ Database

Returns a new instance of Database.



104
105
106
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
# File 'lib/tina4/database.rb', line 104

def initialize(connection_string = nil, username: nil, password: nil, driver_name: nil, pool: 0)
  @connection_string = connection_string || ENV["DATABASE_URL"]
  @username = username || ENV["DATABASE_USERNAME"]
  @password = password || ENV["DATABASE_PASSWORD"]
  @driver_name = driver_name || detect_driver(@connection_string)
  @pool_size = pool  # 0 = single connection, N>0 = N pooled connections
  @connected = false

  # Query cache — off by default, opt-in via TINA4_DB_CACHE=true
  @cache_enabled = truthy?(ENV["TINA4_DB_CACHE"])
  @cache_ttl = (ENV["TINA4_DB_CACHE_TTL"] || "30").to_i
  @query_cache = {}  # key => { expires_at:, value: }
  @cache_hits = 0
  @cache_misses = 0
  @cache_mutex = Mutex.new

  if @pool_size > 0
    # Pooled mode — create a ConnectionPool with lazy driver creation
    @pool = ConnectionPool.new(
      @pool_size,
      driver_factory: method(:create_driver),
      connection_string: @connection_string,
      username: @username,
      password: @password
    )
    @driver = nil
    @connected = true
  else
    # Single-connection mode — current behavior
    @pool = nil
    @driver = create_driver
    connect
  end
end

Instance Attribute Details

#connectedObject (readonly)

Returns the value of attribute connected.



69
70
71
# File 'lib/tina4/database.rb', line 69

def connected
  @connected
end

#driverObject (readonly)

Returns the value of attribute driver.



69
70
71
# File 'lib/tina4/database.rb', line 69

def driver
  @driver
end

#driver_nameObject (readonly)

Returns the value of attribute driver_name.



69
70
71
# File 'lib/tina4/database.rb', line 69

def driver_name
  @driver_name
end

#poolObject (readonly)

Returns the value of attribute pool.



69
70
71
# File 'lib/tina4/database.rb', line 69

def pool
  @pool
end

Class Method Details

.create(url, username: "", password: "", pool: 0) ⇒ Object

Static factory — cross-framework consistency: Database.create(url)



86
87
88
89
90
# File 'lib/tina4/database.rb', line 86

def self.create(url, username: "", password: "", pool: 0)
  new(url, username: username.empty? ? nil : username,
           password: password.empty? ? nil : password,
           pool: pool)
end

.from_env(env_key: "DATABASE_URL", pool: 0) ⇒ Object

Construct a Database from environment variables. Returns nil if the named env var is not set.



94
95
96
97
98
99
100
101
102
# File 'lib/tina4/database.rb', line 94

def self.from_env(env_key: "DATABASE_URL", pool: 0)
  url = ENV[env_key]
  return nil if url.nil? || url.strip.empty?

  new(url,
      username: ENV["DATABASE_USERNAME"],
      password: ENV["DATABASE_PASSWORD"],
      pool: pool)
end

Instance Method Details

#active_countObject

Number of connections currently created (lazy pool connections counted).



428
429
430
431
432
433
434
# File 'lib/tina4/database.rb', line 428

def active_count
  if @pool
    @pool.active_count
  else
    @connected ? 1 : 0
  end
end

#cache_clearObject



186
187
188
189
190
191
192
# File 'lib/tina4/database.rb', line 186

def cache_clear
  @cache_mutex.synchronize do
    @query_cache.clear
    @cache_hits = 0
    @cache_misses = 0
  end
end

#cache_statsObject

── Query Cache ──────────────────────────────────────────────



174
175
176
177
178
179
180
181
182
183
184
# File 'lib/tina4/database.rb', line 174

def cache_stats
  @cache_mutex.synchronize do
    {
      enabled: @cache_enabled,
      hits: @cache_hits,
      misses: @cache_misses,
      size: @query_cache.size,
      ttl: @cache_ttl
    }
  end
end

#checkin(_driver) ⇒ Object

Return a driver to the pool. No-op for round-robin pool or single connection.



442
443
444
# File 'lib/tina4/database.rb', line 442

def checkin(_driver)
  # no-op
end

#checkoutObject

Check out a driver from the pool (or return the single driver).



437
438
439
# File 'lib/tina4/database.rb', line 437

def checkout
  current_driver
end

#closeObject



154
155
156
157
158
159
160
161
# File 'lib/tina4/database.rb', line 154

def close
  if @pool
    @pool.close_all
  elsif @driver && @connected
    @driver.close
  end
  @connected = false
end

#close_allObject

Close all pooled connections (or the single connection).



447
448
449
# File 'lib/tina4/database.rb', line 447

def close_all
  close
end

#columns(table_name) ⇒ Object Also known as: get_columns



388
389
390
# File 'lib/tina4/database.rb', line 388

def columns(table_name)
  current_driver.columns(table_name)
end

#commitObject

Commit the current transaction — matches PHP/Python/Node API.



372
373
374
# File 'lib/tina4/database.rb', line 372

def commit
  current_driver.commit
end

#connectObject



139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/tina4/database.rb', line 139

def connect
  @driver.connect(@connection_string, username: @username, password: @password)
  @connected = true

  # Enable autocommit if TINA4_AUTOCOMMIT env var is set
  if truthy?(ENV["TINA4_AUTOCOMMIT"]) && @driver.respond_to?(:autocommit=)
    @driver.autocommit = true
  end

  Tina4::Log.info("Database connected: #{@driver_name}")
rescue => e
  Tina4::Log.error("Database connection failed: #{e.message}")
  @connected = false
end

#current_driverObject

Get the current driver — from pool (round-robin) or single connection.



164
165
166
167
168
169
170
# File 'lib/tina4/database.rb', line 164

def current_driver
  if @pool
    @pool.checkout
  else
    @driver
  end
end

#delete(table, filter = {}, params = nil) ⇒ Object



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

def delete(table, filter = {}, params = nil)
  cache_invalidate if @cache_enabled
  drv = current_driver

  # List of hashes — delete each row
  if filter.is_a?(Array)
    filter.each { |row| delete(table, row) }
    return { success: true }
  end

  # String filter — raw WHERE clause with optional params
  if filter.is_a?(String)
    sql = "DELETE FROM #{table}"
    sql += " WHERE #{filter}" unless filter.empty?
    drv.execute(sql, Array(params))
    return { success: true }
  end

  # Hash filter — build WHERE from keys
  where_parts = filter.keys.map { |k| "#{k} = #{drv.placeholder}" }
  sql = "DELETE FROM #{table}"
  sql += " WHERE #{where_parts.join(' AND ')}" unless filter.empty?
  drv.execute(sql, filter.values)
  { success: true }
end

#execute(sql, params = []) ⇒ Object

Execute a write statement. Returns true/false for simple writes. Returns DatabaseResult if SQL contains RETURNING, CALL, EXEC, or SELECT.



325
326
327
328
329
330
331
332
333
334
335
336
337
338
# File 'lib/tina4/database.rb', line 325

def execute(sql, params = [])
  cache_invalidate if @cache_enabled
  result = current_driver.execute(sql, params)
  @last_error = nil
  sql_upper = sql.strip.upcase
  if sql_upper.include?("RETURNING") || sql_upper.start_with?("CALL ") ||
     sql_upper.start_with?("EXEC ") || sql_upper.start_with?("SELECT ")
    return result
  end
  true
rescue => e
  @last_error = e.message
  false
end

#execute_many(sql, params_list = []) ⇒ Object



340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'lib/tina4/database.rb', line 340

def execute_many(sql, params_list = [])
  results = []
  drv = current_driver
  drv.begin_transaction
  begin
    params_list.each do |params|
      results << drv.execute(sql, params)
    end
    drv.commit
  rescue => e
    drv.rollback
    raise e
  end
  results
end

#fetch(sql, params = [], limit: 100, offset: nil) ⇒ Object



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

def fetch(sql, params = [], limit: 100, offset: nil)
  offset ||= 0
  drv = current_driver

  effective_sql = sql
  # Skip appending LIMIT if SQL already has one
  has_limit = sql.upcase.split("--")[0].include?("LIMIT")
  if limit && !has_limit
    effective_sql = drv.apply_limit(effective_sql, limit, offset)
  end

  if @cache_enabled
    key = cache_key(effective_sql, params)
    cached = cache_get(key)
    if cached
      @cache_mutex.synchronize { @cache_hits += 1 }
      return cached
    end
    result = drv.execute_query(effective_sql, params)
    result = Tina4::DatabaseResult.new(result, sql: effective_sql, db: self)
    cache_set(key, result)
    @cache_mutex.synchronize { @cache_misses += 1 }
    return result
  end

  rows = drv.execute_query(effective_sql, params)
  Tina4::DatabaseResult.new(rows, sql: effective_sql, db: self)
end

#fetch_one(sql, params = []) ⇒ Object



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/tina4/database.rb', line 223

def fetch_one(sql, params = [])
  if @cache_enabled
    key = cache_key(sql + ":ONE", params)
    cached = cache_get(key)
    if cached
      @cache_mutex.synchronize { @cache_hits += 1 }
      return cached
    end
    result = fetch(sql, params, limit: 1)
    value = result.first
    cache_set(key, value)
    @cache_mutex.synchronize { @cache_misses += 1 }
    return value
  end

  result = fetch(sql, params, limit: 1)
  result.first
end

#get_adapterInteger

Pre-generate the next available primary key ID using engine-aware strategies.

Race-safe implementation using a ‘tina4_sequences` table for SQLite/MySQL/MSSQL fallback. Each call atomically increments the stored counter, so concurrent callers never receive the same value.

  • Firebird: auto-creates a generator if missing, then increments via GEN_ID.

  • PostgreSQL: tries nextval() on the named sequence, auto-creates it if missing.

  • SQLite/MySQL/MSSQL: atomic UPDATE on ‘tina4_sequences` table.

  • Returns 1 if the table is empty or does not exist.

Returns the underlying driver object (pool’s current driver or single driver).

Parameters:

  • table (String)

    Table name

  • pk_column (String)

    Primary key column name (default: “id”)

  • generator_name (String, nil)

    Override for sequence/generator name

Returns:

  • (Integer)

    The next available ID



418
419
420
# File 'lib/tina4/database.rb', line 418

def get_adapter
  current_driver
end

#get_errorObject

Return the last execute() error message, or nil.



312
313
314
# File 'lib/tina4/database.rb', line 312

def get_error
  @last_error
end

#get_last_idObject

Return the last insert ID from execute() or insert().



317
318
319
320
321
# File 'lib/tina4/database.rb', line 317

def get_last_id
  current_driver.last_insert_id
rescue
  nil
end

#get_next_id(table, pk_column: "id", generator_name: nil) ⇒ Object



451
452
453
454
455
456
457
458
459
460
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
492
493
494
495
496
497
498
499
500
501
# File 'lib/tina4/database.rb', line 451

def get_next_id(table, pk_column: "id", generator_name: nil)
  drv = current_driver

  # Firebird — use generators
  if @driver_name == "firebird"
    gen_name = generator_name || "GEN_#{table.upcase}_ID"

    # Auto-create the generator if it does not exist
    begin
      drv.execute("CREATE GENERATOR #{gen_name}")
    rescue
      # Generator already exists — ignore
    end

    rows = drv.execute_query("SELECT GEN_ID(#{gen_name}, 1) AS NEXT_ID FROM RDB$DATABASE")
    row = rows.is_a?(Array) ? rows.first : nil
    val = row_value(row, :NEXT_ID) || row_value(row, :next_id)
    return val&.to_i || 1
  end

  # PostgreSQL — try sequence first, auto-create if missing
  if @driver_name == "postgres"
    seq_name = generator_name || "#{table.downcase}_#{pk_column.downcase}_seq"
    begin
      rows = drv.execute_query("SELECT nextval('#{seq_name}') AS next_id")
      row = rows.is_a?(Array) ? rows.first : nil
      val = row_value(row, :next_id) || row_value(row, :nextval)
      return val.to_i if val
    rescue
      # Sequence does not exist — auto-create it seeded from MAX
      begin
        max_rows = drv.execute_query("SELECT COALESCE(MAX(#{pk_column}), 0) AS max_id FROM #{table}")
        max_row = max_rows.is_a?(Array) ? max_rows.first : nil
        max_val = row_value(max_row, :max_id)
        start_val = max_val ? max_val.to_i + 1 : 1
        drv.execute("CREATE SEQUENCE #{seq_name} START WITH #{start_val}")
        drv.commit rescue nil
        rows = drv.execute_query("SELECT nextval('#{seq_name}') AS next_id")
        row = rows.is_a?(Array) ? rows.first : nil
        val = row_value(row, :next_id) || row_value(row, :nextval)
        return val&.to_i || start_val
      rescue
        # Fall through to sequence table fallback
      end
    end
  end

  # SQLite / MySQL / MSSQL / PostgreSQL fallback — atomic sequence table
  seq_key = generator_name || "#{table}.#{pk_column}"
  sequence_next(seq_key, table: table, pk_column: pk_column)
end

#insert(table, data) ⇒ Object



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/tina4/database.rb', line 242

def insert(table, data)
  cache_invalidate if @cache_enabled
  drv = current_driver

  # List of hashes — batch insert
  if data.is_a?(Array)
    return { success: true, affected_rows: 0 } if data.empty?
    keys = data.first.keys.map(&:to_s)
    placeholders = drv.placeholders(keys.length)
    sql = "INSERT INTO #{table} (#{keys.join(', ')}) VALUES (#{placeholders})"
    params_list = data.map { |row| keys.map { |k| row[k.to_sym] || row[k] } }
    return execute_many(sql, params_list)
  end

  columns = data.keys.map(&:to_s)
  placeholders = drv.placeholders(columns.length)
  sql = "INSERT INTO #{table} (#{columns.join(', ')}) VALUES (#{placeholders})"
  drv.execute(sql, data.values)
  { success: true, last_id: drv.last_insert_id }
end

#pool_sizeObject

Returns the configured pool size, or 1 for single-connection mode.



423
424
425
# File 'lib/tina4/database.rb', line 423

def pool_size
  @pool_size > 0 ? @pool_size : 1
end

#rollbackObject

Roll back the current transaction — matches PHP/Python/Node API.



377
378
379
# File 'lib/tina4/database.rb', line 377

def rollback
  current_driver.rollback
end

#start_transactionObject

Begin a transaction without a block — matches PHP/Python/Node API.



367
368
369
# File 'lib/tina4/database.rb', line 367

def start_transaction
  current_driver.begin_transaction
end

#table_exists?(table_name) ⇒ Boolean Also known as: table_exists

Returns:

  • (Boolean)


395
396
397
# File 'lib/tina4/database.rb', line 395

def table_exists?(table_name)
  tables.any? { |t| t.downcase == table_name.to_s.downcase }
end

#tablesObject Also known as: get_tables



381
382
383
# File 'lib/tina4/database.rb', line 381

def tables
  current_driver.tables
end

#transactionObject



356
357
358
359
360
361
362
363
364
# File 'lib/tina4/database.rb', line 356

def transaction
  drv = current_driver
  drv.begin_transaction
  yield self
  drv.commit
rescue => e
  drv.rollback
  raise e
end

#update(table, data, filter = {}, params = nil) ⇒ Object



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/tina4/database.rb', line 263

def update(table, data, filter = {}, params = nil)
  cache_invalidate if @cache_enabled
  drv = current_driver

  # String filter with explicit params array
  if filter.is_a?(String) && !params.nil?
    set_parts = data.keys.map { |k| "#{k} = #{drv.placeholder}" }
    sql = "UPDATE #{table} SET #{set_parts.join(', ')}"
    sql += " WHERE #{filter}" unless filter.empty?
    drv.execute(sql, data.values + Array(params))
    return { success: true }
  end

  set_parts = data.keys.map { |k| "#{k} = #{drv.placeholder}" }
  where_parts = filter.keys.map { |k| "#{k} = #{drv.placeholder}" }
  sql = "UPDATE #{table} SET #{set_parts.join(', ')}"
  sql += " WHERE #{where_parts.join(' AND ')}" unless filter.empty?
  values = data.values + filter.values
  drv.execute(sql, values)
  { success: true }
end