87 lines
2.3 KiB
Ruby
87 lines
2.3 KiB
Ruby
|
# SPDX-License-Identifier: Apache-2.0
|
||
|
# Copyright (C) 2021 OKTET Labs Ltd. All rights reserved.
|
||
|
|
||
|
#
|
||
|
# SQL class for Diary Management Application
|
||
|
#
|
||
|
|
||
|
class SQL_Cache < Hash
|
||
|
def initialize(sql, table, string_expr)
|
||
|
@sql = sql
|
||
|
@name = table
|
||
|
@string_expr = string_expr
|
||
|
@lists = Hash.new
|
||
|
@fields = @sql.columns(@name).collect { |col| col["name"] }
|
||
|
super(0)
|
||
|
end
|
||
|
|
||
|
attr_reader :sql, :name
|
||
|
attr_accessor :string_expr
|
||
|
|
||
|
def search(where)
|
||
|
list = Array.new
|
||
|
@sql.select_all("select * from #{@name} where #{where} order by id") do |row|
|
||
|
self[row["id"]] = row.to_h
|
||
|
list.push(self[row["id"]])
|
||
|
end
|
||
|
list
|
||
|
end
|
||
|
private :search
|
||
|
|
||
|
def list(where)
|
||
|
if not @lists[where]
|
||
|
@lists[where] = search(where).collect do |entry|
|
||
|
string = @string_expr.dup
|
||
|
entry.each do |field, value|
|
||
|
string.gsub!(/#\{#{field}\}/, value.to_s) if value
|
||
|
end
|
||
|
[entry["id"].to_s, string]
|
||
|
end
|
||
|
end
|
||
|
@lists[where]
|
||
|
end
|
||
|
|
||
|
def [](id)
|
||
|
id = id.to_i
|
||
|
if super(id) == 0
|
||
|
if search("id = #{id}").length != 1
|
||
|
self[id] = nil
|
||
|
end
|
||
|
end
|
||
|
super(id)
|
||
|
end
|
||
|
|
||
|
def create(data)
|
||
|
fields = data.keys & @fields
|
||
|
@sql.do("insert into #{@name} (" +
|
||
|
fields.join(", ") +
|
||
|
") values (" + fields.collect do "?" end.join(", ") +
|
||
|
")",
|
||
|
*(fields.collect do |field| data[field] end))
|
||
|
@sql.select_one("select last_insert_id()")[0]
|
||
|
end
|
||
|
|
||
|
def modify(id, data)
|
||
|
fields = (@fields & self[id].keys) - ["id"]
|
||
|
changes = fields.inject([]) do |ch, field|
|
||
|
if data.has_key?(field) and data[field] != self[id][field]
|
||
|
ch.push(field)
|
||
|
else
|
||
|
ch
|
||
|
end
|
||
|
end
|
||
|
@sql.do("update #{@name} set " +
|
||
|
changes.collect do |field|
|
||
|
field + " = ?"
|
||
|
end.join(", ") + " where id = #{id}",
|
||
|
*(changes.collect do |field| data[field] end)
|
||
|
) if changes.length > 0
|
||
|
end
|
||
|
|
||
|
def delete(id)
|
||
|
@sql.do("delete from #{@name} where id = #{id}")
|
||
|
super(id)
|
||
|
end
|
||
|
end
|
||
|
|