-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase_connection.rb
75 lines (61 loc) · 1.81 KB
/
base_connection.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
require 'byebug'
require 'singleton'
require 'sqlite3'
require 'active_support/inflector'
require_relative 'base_object'
require_relative 'base_table'
require_relative "base_relation"
require_relative 'Modules/associatable'
require_relative 'Modules/validator'
require_relative 'Modules/equalizer'
require_relative 'Modules/searchable'
require_relative "sastman/sql_ast"
module BaseConnection
class << self
def connect(connection)
raise "#{connection} not a valid file name" unless File.exist?(connection)
@db = _connect(connection)
classes = discover_tables(@db)
generate_classes!(@db, classes)
end
private
def _connect(connection)
Class.new SQLite3::Database do
include Singleton
define_method :initialize do
super connection
self.type_translation = true
self.results_as_hash = true
end
end
end
def discover_tables(db)
tables = []
db.instance.execute("SELECT name FROM sqlite_master").each { |table|
tables << table['name']
}
tables
end
def generate_classes!(db, tables)
classes = []
tables.each { |table_name|
next if /^sqlite_/.match?(table_name)
table = BaseTable.new(table_name, *db.instance.execute("PRAGMA table_info(#{table_name})"))
klass = Object.const_set(table_name.classify, Class.new(BaseObject) {
self.instance_variable_set(:@db, db)
self.instance_variable_set(:@table, table)
def self.db; @db; end
def self.table; @table; end
attr_reader :db, :table
extend Associatable
extend Validator
extend Searchable
include Equalizer
})
classes << klass
}
@db = nil
classes
end
end
end