Class: RailsMcp::Database::QueryBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_mcp/database/query_builder.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

ALLOWED_ORDER_DIRECTIONS =
%w[ASC DESC].freeze
SCALAR_TYPES =
[String, Integer, Float, TrueClass, FalseClass, NilClass].freeze

Instance Method Summary collapse

Constructor Details

#initialize(klass, conditions: {}, fields: [], limit: nil, offset: 0, order: nil) ⇒ QueryBuilder

Returns a new instance of QueryBuilder.



11
12
13
14
15
16
17
18
# File 'lib/rails_mcp/database/query_builder.rb', line 11

def initialize(klass, conditions: {}, fields: [], limit: nil, offset: 0, order: nil)
  @klass      = klass
  @conditions = conditions.transform_keys(&:to_s)
  @fields     = Array(fields).map(&:to_s)
  @limit      = clamp_limit(limit)
  @offset     = [offset.to_i, 0].max
  @order      = order
end

Instance Method Details

#executeObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/rails_mcp/database/query_builder.rb', line 20

def execute
  validate_conditions!
  validate_fields!
  validate_order!
  validate_offset!

  scope = @klass.where(@conditions)
  scope = scope.select(resolved_fields.map { |f| @klass.arel_table[f] })
  scope = scope.limit(@limit)
  scope = scope.offset(@offset) if @offset.positive?
  scope = scope.order(safe_order_clause) if @order

  scope.map { |record| serialize(record) }
end