lib/ezframe/database.rb in ezframe-0.2.0 vs lib/ezframe/database.rb in ezframe-0.3.0
- old
+ new
@@ -1,27 +1,28 @@
# frozen_string_literal: true
-require "logger"
-
module Ezframe
class DB
class << self
attr_accessor :sequel, :pool
def init(dbfile = nil, opts = {})
@dbfile = dbfile || ENV["EZFRAME_DB"] || Config[:database]
+ unless @dbfile
+ raise "database settings error: dbfile=#{Config[:database]}"
+ end
if Config[:use_connection_pool] || opts[:use_connection_pool]
@pool = Sequel::ConnectionPool(max_connections: 10) do
- Sequel.connect(@dbfile, loggers: [Logger])
+ Sequel.connect(@dbfile, loggers: [EzLog])
end
else
connect(@dbfile)
end
end
def connect(dbfile = nil)
dbfile ||= @dbfile
- @sequel = Sequel.connect(dbfile, loggers: [Logger])
+ @sequel = Sequel.connect(dbfile, EzLogs: [EzLog])
return @sequel
end
def disconnect
@sequel.disconnect
@@ -115,58 +116,64 @@
return res_a
end
# テーブル生成
def create_table(table_name, dbtype_h)
- %w[id created_at updated_at].each do |key|
+ %w[id created_at updated_at deleted_at].each do |key|
dbtype_h.delete(key.to_sym)
end
# puts "create_table: #{table_name}"
if @dbfile.index("postgres")
@sequel.create_table(table_name) do
primary_key :id, identity: true
dbtype_h.each do |key, dbtype|
column(key, dbtype)
end
column(:created_at, :timestamp, default: Sequel::CURRENT_TIMESTAMP)
- column(:updated_at, :timestamp, default: Sequel::CURRENT_TIMESTAMP)
+ column(:updated_at, :timestamp)
+ column(:deleted_at, :timestamp)
end
else
@sequel.create_table(table_name) do
primary_key :id, auto_increment: true
dbtype_h.each do |key, dbtype|
column(key, dbtype)
end
column(:created_at, :timestamp, default: Sequel::CURRENT_TIMESTAMP)
- column(:updated_at, :timestamp, default: Sequel::CURRENT_TIMESTAMP)
+ column(:updated_at, :timestamp)
+ column(:deleted_at, :timestamp)
end
end
end
def insert(table_name, val_h)
dataset(table_name).insert(val_h)
end
- def update(dataset, val_h)
- val_h.update({ updated_at: Time.now() })
- dataset.update(val_h)
+ def update(dataset, id, val_h)
+ val_h.update({ updated_at: Time.now })
+ dataset.where(id: id).update(val_h)
end
+
+ def delete(dataset, id)
+ dataset.where(id: id).update({ deleted_at: Time.now })
+ end
end
class Cache
class << self
def [](table)
@store ||= {}
dataset = DB.dataset(table.to_sym)
- # Logger.debug("DB::Cache: #{table}")
+ # EzLog.debug("DB::Cache: #{table}")
unless @store[table.to_sym]
- data_a = dataset.all
+ data_a = dataset.where(deleted_at: nil).all
h = {}
data_a.each {|data| h[data[:id]] = data }
@store[table.to_sym] = h
end
- # Logger.debug(@store[table.to_sym])
+ # EzLog.debug(@store[table.to_sym])
return @store[table.to_sym]
end
end
end
end