Class: MIDB::API::Model

Inherits:
Object
  • Object
show all
Defined in:
lib/midb/server_model.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(jsf, db, engine) ⇒ Model

Constructor



22
23
24
25
26
27
# File 'lib/midb/server_model.rb', line 22

def initialize(jsf, db, engine)
  @jsf = jsf
  @db = db
  @engine = engine
  @hooks = engine.hooks
end

Instance Attribute Details

#dbObject

Returns the value of attribute db.



13
14
15
# File 'lib/midb/server_model.rb', line 13

def db
  @db
end

#engineObject

Returns the value of attribute engine.



13
14
15
# File 'lib/midb/server_model.rb', line 13

def engine
  @engine
end

#hooksObject

Returns the value of attribute hooks.



13
14
15
# File 'lib/midb/server_model.rb', line 13

def hooks
  @hooks
end

#jsfObject

Returns the value of attribute jsf.



13
14
15
# File 'lib/midb/server_model.rb', line 13

def jsf
  @jsf
end

Instance Method Details

#delete(id) ⇒ Object

Delete a resource



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/midb/server_model.rb', line 192

def delete(id)
  # Check if the ID exists
  db = MIDB::API::Dbengine.new(@engine.config, @db)
  dbc = db.connect()
  dbq = db.query(dbc, "SELECT * FROM #{self.get_structure.values[0].split('/')[0]} WHERE id=#{id};")
  if not db.length(dbq) > 0
    resp = MIDB::Interface::Server.json_error(404, "ID not found").to_json
    @engine.http_status = 404
    bad_request = true
  else
    # ID Found, so let's delete it. (including linked resources!)
    jss = self.get_structure() # Referencing

    where_clause = {}
    tables = []
    main_table = jss.values[0].split('/')[0]
    where_clause[main_table] = "id=#{id}"

    jss.each do |k, v|
      table = v.split("/")[0]
      tables.push table unless tables.include? table
      # Check if it's a linked resource, generate WHERE clause accordingly
      if v.split("/").length > 2
        match = v.split("/")[2]
        matching_field = match.split("->")[0]
        row_field = match.split("->")[1]
        # We have to run the subquery now because it'll be deleted later!
        subq = "SELECT #{row_field} FROM #{main_table} WHERE #{where_clause[main_table]};"
        res = db.query(dbc, subq)
        subqres = db.extract(res, row_field)
        where_clause[table] ||= "#{matching_field}=#{subqres}"
      else
        # Normal WHERE clause
        where_clause[table] ||= "id=#{id}"
      end
    end

    # Generate and run queries
    results = []
    tables.each do |tb|
      query = "DELETE FROM #{tb} WHERE #{where_clause[tb]};"
      results.push db.query(dbc, query)
    end
    @engine.http_status = "200 OK"
    resp = {status: "200 OK"}
  end
  return resp
end

#get_all_entriesObject

Get all the entries from the database



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
# File 'lib/midb/server_model.rb', line 285

def get_all_entries()
  jso = Hash.new()
     
  # Connect to database
  dbe = MIDB::API::Dbengine.new(@engine.config, @db)
  dblink = dbe.connect()
  rows = dbe.query(dblink, "SELECT * FROM #{self.get_structure.values[0].split('/')[0]};")
  if rows == false
    return MIDB::Interface::Server.json_error(400, "Bad Request")
  end
  # Iterate over all rows of this table
  rows.each do |row|
    jso[row["id"]] = self.get_structure
    self.get_structure.each do |name, dbi|
      table = dbi.split("/")[0]
      field = dbi.split("/")[1]
      # Must-match relations ("table2/field/table2-field->row-field")
      if dbi.split("/").length > 2
        match = dbi.split("/")[2]
        matching_field = match.split("->")[0]
        row_field = match.split("->")[1]
        query = dbe.query(dblink, "SELECT #{field} FROM #{table} WHERE #{matching_field}=#{row[row_field]};")
      else
        query = dbe.query(dblink, "SELECT #{field} from #{table} WHERE id=#{row['id']};")
      end
      if query == false
        return MIDB::Interface::Server.json_error(400, "Bad Request")
      end
      jso[row["id"]][name] = dbe.length(query) > 0 ? dbe.extract(query,field) : "unknown"
      jso[row["id"]][name] = @hooks.format_field(name, jso[row["id"]][name])
    end
  end
  @hooks.after_get_all_entries(dbe.length(rows))
  return jso
end

#get_column_entries(column) ⇒ Object

Get all the entries from the database belonging to a column



323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
# File 'lib/midb/server_model.rb', line 323

def get_column_entries(column)
  jso = Hash.new() 
  jss = self.get_structure()
  db_column = nil
  # Is the column recognized?
  if jss.has_key? column then
    db_column = jss[column].split("/")[1]
  else
    return MIDB::Interface::Server.json_error(400, "Bad Request")
  end
  
  # Connect to database
  dbe = MIDB::API::Dbengine.new(@engine.config, @db)
  dblink = dbe.connect()
  rows = dbe.query(dblink, "SELECT * FROM #{self.get_structure.values[0].split('/')[0]};")
  if rows == false
    return MIDB::Interface::Server.json_error(400, "Bad Request")
  end
  # Iterate over all rows of this table
  rows.each do |row|

    name = column
    dbi = jss[name]
    table = dbi.split("/")[0]
    field = dbi.split("/")[1]
    # Must-match relations ("table2/field/table2-field->row-field")
    if dbi.split("/").length > 2
      match = dbi.split("/")[2]
      matching_field = match.split("->")[0]
      row_field = match.split("->")[1]
      query = dbe.query(dblink, "SELECT #{field} FROM #{table} WHERE #{matching_field}=#{row[row_field]};")
    else
      query = dbe.query(dblink, "SELECT #{field} from #{table} WHERE id=#{row['id']};")
    end
    if query == false
      return MIDB::Interface::Server.json_error(400, "Bad Request")
    end
    jso[row["id"]] = {}
    jso[row["id"]][name] = dbe.length(query) > 0 ? dbe.extract(query,field) : "unknown"
    jso[row["id"]][name] = @hooks.format_field(name, jso[row["id"]][name])
  end
  @hooks.after_get_all_entries(dbe.length(rows))
  return jso
end

#get_entries(id) ⇒ Object

Get an entry with a given id.



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
282
# File 'lib/midb/server_model.rb', line 244

def get_entries(id)
  jso = Hash.new()

  dbe = MIDB::API::Dbengine.new(@engine.config, @db)
  dblink = dbe.connect()
  rows = dbe.query(dblink, "SELECT * FROM #{self.get_structure.values[0].split('/')[0]} WHERE id=#{id};")
  if rows == false
    return MIDB::Interface::Server.json_error(400, "Bad Request")
  end
  if dbe.length(rows) > 0
    rows.each do |row|
      jso[row["id"]] = self.get_structure
      self.get_structure.each do |name, dbi|
        table = dbi.split("/")[0]
        field = dbi.split("/")[1]
        # Must-match relations ("table2/field/table2-field->row-field")
        if dbi.split("/").length > 2
          match = dbi.split("/")[2]
          matching_field = match.split("->")[0]
          row_field = match.split("->")[1]
          query = dbe.query(dblink, "SELECT #{field} FROM #{table} WHERE #{matching_field}=#{row[row_field]};")
        else
          query = dbe.query(dblink, "SELECT #{field} from #{table} WHERE id=#{row['id']};")
        end
        if query == false
          return MIDB::Interface::Server.json_error(400, "Bad Request")
        end
        jso[row["id"]][name] = dbe.length(query) > 0 ? dbe.extract(query,field) : "unknown"
        jso[row["id"]][name] = @hooks.format_field(name, jso[row["id"]][name])
      end
    end
    @engine.http_status = "200 OK"
  else
    @engine.http_status = "404 Not Found"
    jso = MIDB::Interface::Server.json_error(404, "Not Found")
  end
  return jso

end

#get_matching_rows(column, pattern) ⇒ Object

Get all the entries from the database belonging to a column matching a pattern



369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
# File 'lib/midb/server_model.rb', line 369

def get_matching_rows(column, pattern)
  jso = Hash.new() 
  jss = self.get_structure()
  db_column = nil
  # Is the column recognized?
  if jss.has_key? column then
    db_column = jss[column].split("/")[1]
  else
    return MIDB::Interface::Server.json_error(400, "Bad Request")
  end
  
  # Connect to database
  dbe = MIDB::API::Dbengine.new(@engine.config, @db)
  dblink = dbe.connect()
  rows = dbe.query(dblink, "SELECT * FROM #{self.get_structure.values[0].split('/')[0]};")
  if rows == false
    return MIDB::Interface::Server.json_error(400, "Bad Request")
  end
  # Iterate over all rows of this table
  rows.each do |row|
    # Does this row match?
    bufd = jss[column]
    b_table = bufd.split("/")[0]
    b_field = bufd.split("/")[1]
    # The column is in another table, let's find it
    if bufd.split("/").length > 2    
      b_match = bufd.split("/")[2]
      b_m_field = b_match.split("->")[0]
      b_r_field = b_match.split("->")[1]

      bquery = dbe.query(dblink, "SELECT #{b_field} FROM #{b_table} WHERE (#{b_m_field}=#{row[b_r_field]} AND #{db_column} LIKE '%#{pattern}%');")
    else
      # It's in the same main table, let's see if it matches
      bquery = dbe.query(dblink, "SELECT #{b_field} FROM #{b_table} WHERE (id=#{row['id']} AND #{db_column} LIKE '%#{pattern}%');")
    end

    # Unless the query has been successful (thus this row matches), skip to the next row
    unless dbe.length(bquery) > 0
      next
    end

    jso[row["id"]] = self.get_structure

    self.get_structure.each do |name, dbi|
      table = dbi.split("/")[0]
      field = dbi.split("/")[1]
      # Must-match relations ("table2/field/table2-field->row-field")
      if dbi.split("/").length > 2
        match = dbi.split("/")[2]
        matching_field = match.split("->")[0]
        row_field = match.split("->")[1]
        query = dbe.query(dblink, "SELECT #{field} FROM #{table} WHERE #{matching_field}=#{row[row_field]};")
      else
        query = dbe.query(dblink, "SELECT #{field} from #{table} WHERE id=#{row['id']};")
      end
      if query == false
        next
      end
      jso[row["id"]][name] = dbe.length(query) > 0 ? dbe.extract(query,field) : "unknown"
      jso[row["id"]][name] = @hooks.format_field(name, jso[row["id"]][name])
    end
  end
  @hooks.after_get_all_entries(dbe.length(rows))
  return jso
end

#get_structureObject

Safely get the structure



30
31
32
# File 'lib/midb/server_model.rb', line 30

def get_structure()
  JSON.parse(IO.read("./json/#{@jsf}.json"))["id"]
end

#post(data) ⇒ Object

Act on POST requests - create a new resource



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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/midb/server_model.rb', line 44

def post(data)
  jss = self.get_structure() # For referencing purposes

  input = self.query_to_hash(data)
  bad_request = false
  resp = nil
  jss.each do |key, value|
    # Check if we have it on the query too
    unless input.has_key? key
      resp = MIDB::Interface::Server.json_error(400, "Bad Request - Not enough data for a new resource")
      @engine.http_status = 400
      bad_request = true
    end
  end
  input.each do |key, value|
    # Check if we have it on the structure too
    unless jss.has_key? key
      resp = MIDB::Interface::Server.json_error(400, "Bad Request - Wrong argument #{key}")
      @engine.http_status = 400
      bad_request = true
    end
  end
  

  # Insert the values if we have a good request
  unless bad_request
    fields = Hash.new
    inserts = Hash.new
    main_table = self.get_structure.values[0].split('/')[0]
    input.each do |key, value|
      struct = jss[key]
      table = struct.split("/")[0]
      inserts[table] ||= []
      fields[table] ||= []
      inserts[table].push "\"" + value + "\""
      fields[table].push struct.split("/")[1]
      if struct.split("/").length > 2
        match = struct.split("/")[2]
        matching_field = match.split("->")[0]
        row_field = match.split("->")[1]
        fields[table].push matching_field
        if @engine.config["dbengine"] == :mysql
          inserts[table].push "(SELECT #{row_field} FROM #{main_table} WHERE id=(SELECT LAST_INSERT_ID()))"
        else
          inserts[table].push "(SELECT #{row_field} FROM #{main_table} WHERE id=(last_insert_rowid()))"
        end
      end
    end
    queries = []      
    inserts.each do |table, values|
      queries.push "INSERT INTO #{table}(#{fields[table].join(',')}) VALUES (#{inserts[table].join(',')});"
    end
    # Connect to the database
    dbe = MIDB::API::Dbengine.new(@engine.config, @db)
    dblink = dbe.connect()
    results = []
    rid = nil
    # Find the ID to return in the response (only for the first query)
    queries.each do |q|
      results.push dbe.query(dblink, q)
      if @engine.config["dbengine"] == :mysql
        rid ||= dbe.extract(dbe.query(dblink, "SELECT id FROM #{main_table} WHERE id=(SELECT LAST_INSERT_ID());"), "id")
      else
        rid ||= dbe.extract(dbe.query(dblink, "SELECT id FROM #{main_table} WHERE id=(last_insert_rowid());"), "id")
      end
    end
    @engine.http_status = "201 Created"
    resp = {status: "201 created", id: rid}
  end
  return resp
end

#put(id, data) ⇒ Object

Update an already existing resource



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/midb/server_model.rb', line 120

def put(id, data)
  jss = self.get_structure() # For referencing purposes

  input = self.query_to_hash(data)
  bad_request = false
  resp = nil
  input.each do |key, value|
    # Check if we have it on the structure too
    unless jss.has_key? key
      resp = MIDB::Interface::Server.json_error(400, "Bad Request - Wrong argument #{key}")
      @engine.http_status = 400
      bad_request = true
    end
  end

  # Check if the ID exists
  db = MIDB::API::Dbengine.new(@engine.config, @db)
  dbc = db.connect()
  dbq = db.query(dbc, "SELECT * FROM #{self.get_structure.values[0].split('/')[0]} WHERE id=#{id};")
  unless db.length(dbq) > 0
    resp = MIDB::Interface::Server.json_error(404, "ID not found")
    @engine.http_status = 404
    bad_request = true
  end
  
  # Update the values if we have a good request
  unless bad_request
    fields = Hash.new
    inserts = Hash.new
    where_clause = Hash.new
    main_table = self.get_structure.values[0].split('/')[0]
    where_clause[main_table] = "id=#{id}"
    input.each do |key, value|
      struct = jss[key]
      table = struct.split("/")[0]
      inserts[table] ||= []
      fields[table] ||= []
      inserts[table].push "\"" + value + "\""
      fields[table].push struct.split("/")[1]
      if struct.split("/").length > 2
        match = struct.split("/")[2]
        matching_field = match.split("->")[0]
        row_field = match.split("->")[1]
        where_clause[table] = "#{matching_field}=(SELECT #{row_field} FROM #{main_table} WHERE #{where_clause[main_table]});"
      end
    end
    queries = []
    updates = Hash.new
    # Turn it into a hash
    inserts.each do |table, values|
      updates[table] ||= Hash.new
      updates[table] = Hash[fields[table].zip(inserts[table])]
      query = "UPDATE #{table} SET "
      updates[table].each do |f, v|
        query = query + "#{f}=#{v} "
      end
      queries.push query + "WHERE #{where_clause[table]};"
    end
    # Run the queries
    results = []
    queries.each do |q|
      results.push db.query(dbc, q)
    end
    @engine.http_status = "200 OK"
    resp = {status: "200 OK"}
  end
  return resp
end

#query_to_hash(query) ⇒ Object

Convert a HTTP query string to a JSONable hash



37
38
39
# File 'lib/midb/server_model.rb', line 37

def query_to_hash(query)
  Hash[CGI.parse(query).map {|key,values| [key, values[0]||true]}]
end