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

Parameters:

  • jsf (String)

    JSON file with the schema

  • db (String)

    Database to operate on.

  • engine (Object)

    Reference to the API engine.



20
21
22
23
24
# File 'lib/midb/server_model.rb', line 20

def initialize(jsf, db, engine)
  @jsf = jsf
  @db = db
  @engine = engine
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

#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

Parameters:

  • id (Fixnum)

    ID to delete



189
190
191
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
# File 'lib/midb/server_model.rb', line 189

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



276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/midb/server_model.rb', line 276

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]};")

  # Iterate over all rows of this table
  rows.each do |row|
    # Replace the "id" in the given JSON with the actual ID and expand it with the fields
    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
      jso[row["id"]][name] = dbe.length(query) > 0 ? dbe.extract(query,field) : "unknown"
    end
  end
  MIDB::API::Hooks.after_get_all_entries()
  return jso
end

#get_entries(id) ⇒ Object

Get an entry with a given id.

Parameters:

  • id (Fixnum)

    ID of the entry



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

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 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
        jso[row["id"]][name] = dbe.length(query) > 0 ? dbe.extract(query,field) : "unknown"
      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_structureObject

Safely get the structure



27
28
29
# File 'lib/midb/server_model.rb', line 27

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

#post(data) ⇒ Object

Act on POST requests - create a new resource

Parameters:

  • data (String)

    The HTTP query string containing what to POST.



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

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

Parameters:

  • id (Fixnum)

    ID to alter

  • data (String)

    HTTP query string



117
118
119
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
# File 'lib/midb/server_model.rb', line 117

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

Parameters:

  • query (String)

    HTTP query string



34
35
36
# File 'lib/midb/server_model.rb', line 34

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