Method: MIDB::ServerModel.delete

Defined in:
lib/midb/server_model.rb

.delete(db, jsf, id) ⇒ Object



172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
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
# File 'lib/midb/server_model.rb', line 172

def self.delete(db, jsf, id)
  # Check if the ID exists
  db = MIDB::DbengineModel.new
  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::ServerView.json_error(404, "ID not found").to_json
    MIDB::ServerController.http_status = 404
    bad_request = true
  else
    # ID Found, so let's delete it. (including linked resources!)
    @jsf = jsf
    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
    MIDB::ServerController.http_status = "200 OK"
    resp = {"status": "200 OK"}
  end
  return resp
end