This repository has been archived by the owner on Jun 20, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.cr
70 lines (57 loc) · 2.09 KB
/
base.cr
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
require "../granite_orm"
require "db"
# The Base Adapter specifies the interface that will be used by the model
# objects to perform actions against a specific database. Each adapter needs
# to implement these methods.
abstract class Granite::Adapter::Base
property database : DB::Database
def initialize(adapter : String)
if url = ENV["DATABASE_URL"]? || replace_env_vars(settings(adapter)["database"].to_s)
@database = DB.open(url)
else
raise "database url needs to be set in the config/database.yml or DATABASE_URL environment variable"
end
end
DATABASE_YML = "config/database.yml"
def settings(adapter : String)
if File.exists?(DATABASE_YML) &&
(yaml = YAML.parse(File.read DATABASE_YML)) &&
(settings = yaml[adapter])
settings
else
return {"database": ""}
end
end
def open(&block)
yield @database
end
# remove all rows from a table and reset the counter on the id.
abstract def clear(table_name)
# select performs a query against a table. The table_name and fields are
# configured using the sql_mapping directive in your model. The clause and
# params is the query and params that is passed in via .all() method
abstract def select(table_name, fields, clause = "", params = nil, &block)
# select_one is used by the find method.
# abstract def select_one(table_name, fields, field, id, &block)
# This will insert a row in the database and return the id generated.
abstract def insert(table_name, fields, params) : Int64
# This will update a row in the database.
abstract def update(table_name, primary_name, fields, params)
# This will delete a row from the database.
abstract def delete(table_name, primary_name, value)
# method used to replace the environment variable if exists
private def replace_env_vars(url)
Granite::Adapter::Base.env(url)
end
# class level method so we can test it
def self.env(url)
regex = /\$\{(.*?)\}/
if regex.match(url)
url = url.gsub(regex) do |match|
ENV[match.gsub("${", "").gsub("}", "")]
end
else
return url
end
end
end