Skip to content

Instantly share code, notes, and snippets.

@alvintamie
Last active March 10, 2024 13:19
Show Gist options
  • Save alvintamie/2f8b48a87b2d55bda8e497128bc4089a to your computer and use it in GitHub Desktop.
Save alvintamie/2f8b48a87b2d55bda8e497128bc4089a to your computer and use it in GitHub Desktop.
parser-to-query.rb
class Parser
def self.run
dataset = DB[Sequel[payload[:TenantID].to_sym][payload[:Entity].to_sym]]
dataset = dataset.order(Sequel.send(payload[:sortDirection].to_sym, payload[:sortBy].to_sym) ) if payload[:sortBy].present?
dataset = dataset.limit(payload[:PageSize]) if payload[:PageSize].present?
offset = payload[:PageSize] * (payload[:Page] - 1)
offset = 0 if offset < 0
dataset = dataset.offset(offset) if payload[:Page].present?
payload[:displayColumns].each do |displayColumn|
if displayColumn.include?(".")
fields = displayColumn.split(".")
table_name = fields[0]
field_name = fields[1]
dataset = dataset.left_join(Sequel[payload[:TenantID].to_sym][table_name.to_sym], "#{payload[:Entity]}_id".to_sym => :id)
end
end
dataset = dataset.select(*payload[:displayColumns].map {|displayColumn| displayColumn.include?(".") ? Sequel[displayColumn.split(".").first.to_sym][displayColumn.split(".").last.to_sym] : displayColumn.to_sym})
sequel_object = build_filter( payload[:filter])
dataset = dataset.where{Sequel.&(*sequel_object)}
puts dataset.sql
dataset.all
end
def self.build_filter(filters)
buffers = []
puts "before loop"
puts filters.inspect
filters.each do |filter|
case
when filter[:or].present?
buffers.append(Sequel.|(*build_filter(filter[:or])))
when filter[:and].present?
buffers.append(Sequel.&(*build_filter(filter[:and])))
else
# debugger
key = filter[:column]
value = filter[:operands]
case filter[:operator].to_s
when 'equal'
buffers.append({key.to_sym => value})
when 'start_with'
buffers.append(Sequel.ilike(key.to_sym, "#{value}%"))
end
end
end
buffers
end
def self.payload
{
"TenantID": "michat",
"Entity": "employee",
"displayColumns": [
"name",
"email",
"submission.submission_type",
"attendance.attendance_type"
],
"filter":
[
{
"column": "name",
"operator": "start_with",
"operands": "isnan"
},
{
"or": [
{
"column": "name",
"operator": "equal",
"operands": [
"isnan"
]
},
{
"column": "name",
"operator": "start_with",
"operands": "alvin"
}
]
}
],
"PageSize": 10,
"Page": 1,
"sortBy": "name",
"sortDirection": "asc"
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment