Class: Gemite::Database

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

Overview

Gemiteコード上の db = sqlite("app.db") で得られるオブジェクトの実体。 仕様18〜22の select/insert/update/delete/exec をSQLに組み立てて実行する。

Constant Summary collapse

IDENTIFIER =
/\A[A-Za-z_][A-Za-z0-9_]*\z/

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ Database

Returns a new instance of Database.



12
13
14
# File 'lib/gemite/database.rb', line 12

def initialize(path)
  @handle = SQLite3FFI::Handle.new(path)
end

Instance Method Details

#closeObject



73
74
75
# File 'lib/gemite/database.rb', line 73

def close
  @handle.close
end

#delete(table, opts = {}) ⇒ Object

where: val, ... に一致する行をDELETEする。



64
65
66
67
68
69
70
71
# File 'lib/gemite/database.rb', line 64

def delete(table, opts = {})
  table_sql = quote_identifier(table)
  where_hash = opts.is_a?(Hash) ? (opts[:where] || opts["where"]) : nil
  clause, params = build_where(where_hash)
  sql = "DELETE FROM #{table_sql}#{clause}"
  result = @handle.execute(sql, params)
  result[:changes]
end

#exec(sql) ⇒ Object

生SQLを実行する(CREATE TABLE等、戻り値を使わない用途)。



17
18
19
20
# File 'lib/gemite/database.rb', line 17

def exec(sql)
  @handle.exec(sql.to_s)
  nil
end

#insert(table, values) ⇒ Object

val, ... をINSERTする。



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/gemite/database.rb', line 32

def insert(table, values)
  values = values || {}
  table_sql = quote_identifier(table)
  cols = values.keys
  return nil if cols.empty?

  col_sql = cols.map { |c| quote_identifier(c) }.join(", ")
  placeholders = (["?"] * cols.length).join(", ")
  sql = "INSERT INTO #{table_sql} (#{col_sql}) VALUES (#{placeholders})"
  result = @handle.execute(sql, cols.map { |c| values[c] })
  result[:rowid]
end

#select(table, opts = {}) ⇒ Object

全件、または where: val, ... 条件でSELECTする。



23
24
25
26
27
28
29
# File 'lib/gemite/database.rb', line 23

def select(table, opts = {})
  table_sql = quote_identifier(table)
  where_hash = opts.is_a?(Hash) ? (opts[:where] || opts["where"]) : nil
  clause, params = build_where(where_hash)
  sql = "SELECT * FROM #{table_sql}#{clause}"
  @handle.query(sql, params)
end

#update(table, values, opts = {}) ⇒ Object

val, ... でUPDATEする。where: val, ... で対象を絞る。



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/gemite/database.rb', line 46

def update(table, values, opts = {})
  values = values || {}
  table_sql = quote_identifier(table)
  cols = values.keys
  return 0 if cols.empty?

  set_sql = cols.map { |c| "#{quote_identifier(c)} = ?" }.join(", ")
  set_params = cols.map { |c| values[c] }

  where_hash = opts.is_a?(Hash) ? (opts[:where] || opts["where"]) : nil
  clause, where_params = build_where(where_hash)

  sql = "UPDATE #{table_sql} SET #{set_sql}#{clause}"
  result = @handle.execute(sql, set_params + where_params)
  result[:changes]
end