Method: MIDB::API::Model#delete
- Defined in:
- lib/midb/server_model.rb
#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 |