Class: Doraemon::SQLiteDatabase

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/doraemon/sqlite_database.rb

Instance Method Summary collapse

Constructor Details

#initializeSQLiteDatabase

Returns a new instance of SQLiteDatabase.



29
30
31
# File 'lib/doraemon/sqlite_database.rb', line 29

def initialize
  self.connect
end

Instance Method Details

#active_scene(uid, scene_id) ⇒ Object



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/doraemon/sqlite_database.rb', line 119

def active_scene(uid, scene_id)
  puts __method__.to_s
  @mutex.lock
  scenes = execute("SELECT * FROM scenes WHERE is_actived = true AND uid = #{uid}")
  if scenes.empty?
    execute("UPDATE scenes SET is_actived = true WHERE id = #{scene_id} AND uid = #{uid}")
    @mutex.unlock
    yield(true) if block_given?
  else
    scene = scenes.first
    execute("UPDATE scenes SET is_actived = false WHERE id = #{scene['id']}")
    execute("UPDATE scenes SET is_actived = true WHERE id = #{scene_id} AND uid = #{uid}")
    @mutex.unlock
    yield(true) if block_given?
  end
end

#add_scene(uid, name) {|scene| ... } ⇒ Object

给指定 uid 增加场景

Yields:

  • (scene)


93
94
95
96
97
98
99
100
101
102
# File 'lib/doraemon/sqlite_database.rb', line 93

def add_scene(uid, name)
  puts __method__.to_s
  @mutex.lock
  execute("INSERT INTO scenes (name, uid) VALUES ('#{name}', #{uid})")
  result = execute("SELECT seq FROM sqlite_sequence WHERE name = 'scenes'")
  id = result.first['seq']
  scene = {id: id, name: name, isActived: false, apiCount: 0}
  @mutex.unlock
  yield(scene) if block_given?
end

#connectObject



15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/doraemon/sqlite_database.rb', line 15

def connect
  Dir.mkdir workdir unless File.exist?(workdir)
  puts "Database file path: #{database_file_path}"
  is_db_exist = File.exist? database_file_path
  puts "Database exist: #{is_db_exist}"
  @conn = SQLite3::Database.new database_file_path
  @conn.results_as_hash = true
  if !is_db_exist
    puts "Creating tables"
    create_tables
  end
  @mutex = Mutex.new
end

#connected?Boolean

Returns:

  • (Boolean)


33
34
35
# File 'lib/doraemon/sqlite_database.rb', line 33

def connected?
  @conn != nil
end

#create_api(scene_id, path) {|api| ... } ⇒ Object

创建 scene_id 场景下名为 path 的 api

Yields:

  • (api)


171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/doraemon/sqlite_database.rb', line 171

def create_api(scene_id, path)
  puts __method__.to_s
  path = path[1, path.length] if path.start_with?('/')
  contents = Base64.strict_encode64('{
  "code": 0,
  "msg": "请求已成功处理",
  "res": {

  }
}')
  @mutex.lock
  execute("INSERT INTO apis (scene_id, path, contents) VALUES (#{scene_id}, '#{path}', '#{contents}')")
  result = execute("SELECT seq FROM sqlite_sequence WHERE name = 'apis'")
  @mutex.unlock
  id = result.first['seq']
  api = {id: id, path: path, enabled: true, contents: contents}
  yield(api) if block_given?
end

#create_tablesObject



241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/doraemon/sqlite_database.rb', line 241

def create_tables
  @conn.execute <<-SQL
    -- 服务基础配置表
    CREATE TABLE IF NOT EXISTS configure (
      id INTEGER PRIMARY KEY AUTOINCREMENT,   -- 配置 id
      next_port INTEGER NOT NULL              -- 下一个可用端口号
    );
  SQL
  @conn.execute <<-SQL
    -- 用户表
    CREATE TABLE IF NOT EXISTS users (
      uid INTEGER PRIMARY KEY AUTOINCREMENT,  -- 用户 id
      username VARCHAR(32) NOT NULL,          -- 用户名
      port INTEGER NOT NULL,                  -- 端口号
      reg_tm bigint NOT NULL                  -- 注册时间
    );
  SQL
  @conn.execute <<-SQL
    -- 服务基础配置表
    CREATE TABLE IF NOT EXISTS scenes (
      id INTEGER PRIMARY KEY AUTOINCREMENT,   -- 场景 id
      name VARCHAR(128) NOT NULL,             -- 场景名
      uid INTEGER NOT NULL,                   -- 场景的所属用户 id
      is_actived BOOLEAN DEFAULT false        -- 是否被激活了
    );
  SQL
  @conn.execute <<-SQL
    -- API 表
    CREATE TABLE IF NOT EXISTS apis (
      id INTEGER PRIMARY KEY AUTOINCREMENT,   -- API id
      scene_id INTEGER NOT NULL,              -- API 所属的场景 id
      path VARCHAR(128) NOT NULL,             -- API 路径
      enabled BOOLEAN DEFAULT true,           -- API 是否启用
      contents TEXT NOT NULL DEFAULT ''       -- API mock 内容
    );
  SQL
  @conn.execute <<-SQL
    -- 初始化下一个可用端口号为 20001
    insert into configure (next_port) values (20001);
  SQL
end

#database_file_pathObject



233
234
235
# File 'lib/doraemon/sqlite_database.rb', line 233

def database_file_path
  File.join(workdir, 'app.db')
end

#delete_api(id) {|true| ... } ⇒ Object

删除 api

Yields:

  • (true)


191
192
193
194
195
196
197
# File 'lib/doraemon/sqlite_database.rb', line 191

def delete_api(id)
  puts __method__.to_s
  @mutex.lock
  execute("DELETE FROM apis WHERE id = #{id}")
  @mutex.unlock
  yield(true) if block_given?
end

#execute(sql) ⇒ Object



37
38
39
40
# File 'lib/doraemon/sqlite_database.rb', line 37

def execute(sql)
  puts "    #{sql}"
  @conn.execute(sql)
end

#modify_api(id, enabled, path) {|true| ... } ⇒ Object

修改 api

Yields:

  • (true)


200
201
202
203
204
205
206
# File 'lib/doraemon/sqlite_database.rb', line 200

def modify_api(id, enabled, path)
  puts __method__.to_s
  @mutex.lock
  execute("UPDATE apis SET enabled = #{enabled}, path = '#{path}' WHERE id = #{id}")
  @mutex.unlock
  yield(true) if block_given?
end

#query_actived_scene(uid) {|scene_id| ... } ⇒ Object

查询用户当前激活的场景

Yields:

  • (scene_id)


223
224
225
226
227
228
229
230
231
# File 'lib/doraemon/sqlite_database.rb', line 223

def query_actived_scene(uid)
  puts __method__.to_s
  @mutex.lock
  result = execute("SELECT * FROM scenes WHERE uid = #{uid} AND is_actived = true")
  @mutex.unlock
  scene = result.first
  scene_id = scene.nil? ? -1 : scene['id'].to_i
  yield(scene_id) if block_given?
end

#query_api_contents(scene_id, path) {|api| ... } ⇒ Object

查询 scene_id 场景下指定路径的 api

Yields:

  • (api)


209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/doraemon/sqlite_database.rb', line 209

def query_api_contents(scene_id, path)
  puts __method__.to_s
  path = path[1, path.length-1] if path.start_with?('/')
  @mutex.lock
  result = execute("SELECT * FROM apis WHERE scene_id = #{scene_id} AND path = '#{path}' AND enabled = true")
  @mutex.unlock
  api = result.first
  if !api.nil?
    api['contents'] = Base64.strict_decode64(api['contents']).force_encoding("utf-8")
  end
  yield(api) if block_given?
end

#query_apis(scene_id) {|name, is_actived, apis| ... } ⇒ Object

获取对应场景下的所有 api

Yields:

  • (name, is_actived, apis)


137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/doraemon/sqlite_database.rb', line 137

def query_apis(scene_id)
  puts __method__.to_s
  @mutex.lock
  scene_result = execute("SELECT * FROM scenes WHERE id = #{scene_id}")
  name = scene_result.first['name']
  is_actived = scene_result.first['is_actived'] == 1
  result = execute("SELECT * FROM apis WHERE scene_id = #{scene_id} ORDER BY id")
  @mutex.unlock
  apis = []
  result.each do |x|
    apis << {
      id: x['id'], 
      path: x['path'], 
      enabled: x['enabled'] == 1, 
      contents: x['contents']
    }
  end
  yield(name, is_actived, apis) if block_given?
end

#query_scenes(uid) {|scenes| ... } ⇒ Object

获取对应 uid 的所有场景信息

Yields:

  • (scenes)


105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/doraemon/sqlite_database.rb', line 105

def query_scenes(uid)
  puts __method__.to_s
  @mutex.lock
  result = execute("SELECT * FROM scenes WHERE uid = #{uid} ORDER BY id")
  scenes = []
  result.each do |x|
    api_count_result = execute("SELECT COUNT(id) FROM apis WHERE scene_id = #{x['id']}")
    api_count = api_count_result.first["COUNT(id)"]
    scenes << {id: x['id'], name: x['name'], isActived: x['is_actived'] == 1, apiCount: api_count}
  end
  @mutex.unlock
  yield(scenes) if block_given?
end

#query_user(username) ⇒ Object

使用用户名查询端口



63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/doraemon/sqlite_database.rb', line 63

def query_user(username)
  puts __method__.to_s
  @mutex.lock
  result = execute "SELECT * FROM users WHERE username = '#{username}'"
  @mutex.unlock
  if result.empty?
    puts "#{username} not register yet."
    yield if block_given?
  else
    user = result.first
    yield({port: user['port'].to_i, username: username, uid: user['uid'].to_i}) if block_given?
  end
end

#query_user_with_uid(uid) ⇒ Object

使用用户 id 查询用户信息



78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/doraemon/sqlite_database.rb', line 78

def query_user_with_uid(uid)
  puts __method__.to_s
  @mutex.lock
  result = execute("SELECT * FROM users WHERE uid = #{uid}")
  @mutex.unlock
  if result.empty?
    puts "UID [#{uid}] not register yet."
    yield if block_given?
  else
    user = result.first
    yield({port: user['port'].to_i, username: user['username'], uid: user['uid'].to_i}) if block_given?
  end
end

#register_user(username) ⇒ Object

注册一个用户



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/doraemon/sqlite_database.rb', line 43

def register_user(username)
  puts __method__.to_s
  @mutex.lock
  usernames = execute("SELECT uid FROM users WHERE username = '#{username}'")
  if usernames.empty?
    next_port = execute("SELECT next_port FROM configure WHERE id = 1")
    port = next_port.first['next_port'].to_i
    reg_tm = (Time.now.to_f * 1000).to_i
    execute("INSERT INTO users (username, port, reg_tm) VALUES ('#{username}', #{port}, #{reg_tm})")
    uid = @conn.last_insert_row_id
    execute("UPDATE configure SET next_port = #{port+1} WHERE id = 1")
    @mutex.unlock
    yield(true, uid) if block_given?
  else
    @mutex.unlock
    yield(false, -1) if block_given?
  end
end

#save_apis(scene_id, apis) {|true| ... } ⇒ Object

保存 scene_id 场景下的所有 api

Yields:

  • (true)


158
159
160
161
162
163
164
165
166
167
168
# File 'lib/doraemon/sqlite_database.rb', line 158

def save_apis(scene_id, apis)
  puts __method__.to_s
  @mutex.lock
  apis.each do |api|
    contents = Base64.strict_encode64(api['contents'])
    id = api['id']
    @conn.execute("UPDATE apis SET contents = '#{contents}' WHERE id = #{id}")
  end
  @mutex.unlock
  yield(true) if block_given?
end

#workdirObject



237
238
239
# File 'lib/doraemon/sqlite_database.rb', line 237

def workdir
  File.join(Dir.home, '.doraemon')
end