queryclerk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 37c5d9054037429ba702cd9b58f252b1f70a856500792c9c0e00286645ed14ed
4
+ data.tar.gz: e7435f1befc595e251582630c6417e6a0e34c7aaac62fab8a296174613f424b7
5
+ SHA512:
6
+ metadata.gz: 1dce555e3f4566a8766e70f65122d923e46f50dacb2670d4c4911a3c055b8063e8d68214e307865f0fab23e93e81de9f0b336f18ee9088b265b3eb4687901a78
7
+ data.tar.gz: 8e5e74e706f5dbe502603d4896877f0d8629906bc6709f1e096f3c5722cd7c18bb28c34137e91ebda7ec40317a1619cf0ea9716cc88328478ea9912284303c31
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --require spec_helper
2
+ --format documentation
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2026-12-04
4
+
5
+ - Initial release
@@ -0,0 +1,10 @@
1
+ # Code of Conduct
2
+
3
+ "queryclerk" follows [The Ruby Community Conduct Guideline](https://www.ruby-lang.org/en/conduct) in all "collaborative space", which is defined as community communications channels (such as mailing lists, submitted patches, commit comments, etc.):
4
+
5
+ * Participants will be tolerant of opposing views.
6
+ * Participants must ensure that their language and actions are free of personal attacks and disparaging personal remarks.
7
+ * When interpreting the words and actions of others, participants should always assume good intentions.
8
+ * Behaviour which can be reasonably considered harassment will not be tolerated.
9
+
10
+ If you have any concerns about behaviour within this project, please contact us at ["bosejijo@gmail.com"](mailto:"bosejijo@gmail.com").
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jijo Bose
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,153 @@
1
+ # Queryclerk
2
+
3
+ `queryclerk` converts natural language prompts into safe `ActiveRecord::Relation` objects.
4
+
5
+ It is designed for B2B Rails applications that need strict query safety, tenant boundaries, and model-level authorization.
6
+
7
+ Documentation: https://jijobose.com/libraries/queryclerk
8
+
9
+ ## Installation
10
+
11
+ Add to your Gemfile:
12
+
13
+ ```ruby
14
+ gem "queryclerk"
15
+ ```
16
+
17
+ Then run:
18
+
19
+ ```bash
20
+ bundle install
21
+ ```
22
+
23
+ ## Configuration
24
+
25
+ Add an initializer at `config/initializers/queryclerk.rb`:
26
+
27
+ ```ruby
28
+ Queryclerk.configure do |config|
29
+ config.api_key = ENV.fetch("OPENAI_API_KEY")
30
+ config.model_name = "gpt-4o-mini"
31
+ config.max_limit = 100
32
+ config.allowed_models = [Invoice, User]
33
+
34
+ # Optional: allow controlled joins by model.
35
+ config.allowed_associations = {
36
+ "Invoice" => ["user"]
37
+ }
38
+ end
39
+ ```
40
+
41
+ ## Providers
42
+
43
+ `queryclerk` ships with native adapters for two providers. Select one
44
+ with `config.provider` (default: `:openai`).
45
+
46
+ ### OpenAI (default)
47
+
48
+ ```ruby
49
+ Queryclerk.configure do |config|
50
+ config.provider = :openai
51
+ config.api_key = ENV.fetch("OPENAI_API_KEY")
52
+ # config.model_name defaults to "gpt-4o-mini"
53
+ end
54
+ ```
55
+
56
+ This also covers any OpenAI-compatible endpoint (Azure OpenAI, OpenRouter,
57
+ LiteLLM, Ollama, vLLM, ...) — point `api_base_url` at the gateway:
58
+
59
+ ```ruby
60
+ config.api_base_url = "https://openrouter.ai/api/v1"
61
+ ```
62
+
63
+ ### Anthropic (native Messages API)
64
+
65
+ The Anthropic adapter talks to the native `/v1/messages` API (`x-api-key`
66
+ auth, `anthropic-version` header, top-level `system` prompt, `content`-block
67
+ responses) — not the OpenAI-compatibility shim.
68
+
69
+ ```ruby
70
+ Queryclerk.configure do |config|
71
+ config.provider = :anthropic
72
+ config.api_key = ENV.fetch("ANTHROPIC_API_KEY")
73
+ config.model_name = "claude-sonnet-4-6" # default; override for your account access
74
+
75
+ # Anthropic-specific knobs:
76
+ config.max_tokens = 1024 # required by the Messages API; default 1024
77
+ config.anthropic_version = "2023-06-01" # default
78
+ end
79
+ ```
80
+
81
+ When `provider` is set, `model_name` and `api_base_url` resolve to that
82
+ provider's defaults unless you assign them explicitly.
83
+
84
+ ## Usage
85
+
86
+ ```ruby
87
+ relation = Queryclerk.query(
88
+ prompt: "Unpaid invoices above 50000 from last quarter",
89
+ model: Invoice
90
+ )
91
+
92
+ # Always ActiveRecord::Relation
93
+ relation.limit(10).pluck(:id)
94
+ ```
95
+
96
+ For associated-table constraints, reference fields as `association.column` in natural language intent (for example: "invoices where `user.email` contains `@acme.com`"). The gem will auto-join needed associations, but they must still be whitelisted in `allowed_associations`.
97
+
98
+ ## Security Model
99
+
100
+ `queryclerk` is fail-closed and built to avoid LLM-to-SQL injection:
101
+
102
+ - AI is forced to return JSON DSL only (no SQL allowed).
103
+ - AI output is sanitized (markdown/code fences stripped) and JSON-parsed safely.
104
+ - Unknown keys/operators/fields are rejected.
105
+ - Fields are validated against model schema introspection.
106
+ - `limit` is strictly validated and hard-capped by configuration.
107
+ - Models must be explicitly whitelisted in `allowed_models`.
108
+ - Optional joins are blocked unless explicitly whitelisted in `allowed_associations`.
109
+ - If model defines `current_tenant_scope`, it is always merged.
110
+ - No `eval`, no destructive operations, no raw SQL execution from AI output.
111
+
112
+ ## Architecture Overview
113
+
114
+ Core components:
115
+
116
+ - `Queryclerk::Configuration`: runtime safety, provider, and API settings.
117
+ - `Queryclerk::SchemaIntrospector`: model table/column/association/enum summary.
118
+ - `Queryclerk::PromptBuilder`: strict system prompt with schema and DSL contract.
119
+ - `Queryclerk::Providers`: provider registry and per-vendor transports
120
+ (`Providers::OpenAI`, `Providers::Anthropic`) built on a shared
121
+ `Providers::Base` (Faraday).
122
+ - `Queryclerk::Client`: transport facade that selects and delegates to the
123
+ configured provider.
124
+ - `Queryclerk::AIAdapter`: AI response extraction and JSON parsing.
125
+ - `Queryclerk::DSLParser`: validates DSL structure and values.
126
+ - `Queryclerk::SafetyGuard`: model authorization, limit policies, join policies, tenant scope.
127
+ - `Queryclerk::QueryBuilder`: converts validated DSL into `ActiveRecord::Relation`.
128
+ - `Queryclerk::Railtie`: auto-load support in Rails.
129
+
130
+ ## Error Types
131
+
132
+ - `Queryclerk::InvalidModelError`
133
+ - `Queryclerk::InvalidDSL`
134
+ - `Queryclerk::AIResponseError`
135
+ - `Queryclerk::UnauthorizedModel`
136
+ - `Queryclerk::ConfigurationError` (missing API key, unknown provider)
137
+
138
+ ## Testing
139
+
140
+ Run:
141
+
142
+ ```bash
143
+ bundle exec rspec
144
+ ```
145
+
146
+ Included tests cover:
147
+
148
+ - Valid query generation
149
+ - Invalid field rejection
150
+ - Limit overflow
151
+ - Unknown operator
152
+ - Unauthorized model
153
+ - JSON injection attempt
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rubocop/rake_task"
5
+
6
+ RuboCop::RakeTask.new
7
+
8
+ task default: :rubocop
@@ -0,0 +1,144 @@
1
+ # Developer Guide (Basic)
2
+
3
+ This guide explains how to use `queryclerk` in a Rails app.
4
+
5
+ ## 1. Install
6
+
7
+ Add the gem:
8
+
9
+ ```ruby
10
+ # Gemfile
11
+ gem "queryclerk"
12
+ ```
13
+
14
+ Install dependencies:
15
+
16
+ ```bash
17
+ bundle install
18
+ ```
19
+
20
+ ## 2. Configure
21
+
22
+ Create an initializer:
23
+
24
+ ```ruby
25
+ # config/initializers/queryclerk.rb
26
+ Queryclerk.configure do |config|
27
+ config.api_key = ENV.fetch("OPENAI_API_KEY")
28
+ config.model_name = "gpt-4o-mini"
29
+ config.max_limit = 100
30
+
31
+ # Only models in this list can be queried.
32
+ config.allowed_models = [Invoice, User]
33
+
34
+ # Optional: allow specific joins per model.
35
+ config.allowed_associations = {
36
+ "Invoice" => ["user"]
37
+ }
38
+ end
39
+ ```
40
+
41
+ ## 3. Run a Query
42
+
43
+ Use natural language + model:
44
+
45
+ ```ruby
46
+ relation = Queryclerk.query(
47
+ prompt: "Unpaid invoices above 50000 from last quarter",
48
+ model: Invoice
49
+ )
50
+ ```
51
+
52
+ For associated-table constraints, use `association.column` semantics in the request intent, such as: "unpaid invoices where `user.email` contains `@acme.com`". The gem will auto-join associations used by these fields, but they must still be whitelisted in `allowed_associations`.
53
+
54
+ The return value is always an `ActiveRecord::Relation`, so you can chain it:
55
+
56
+ ```ruby
57
+ relation.limit(20).pluck(:id)
58
+ ```
59
+
60
+ ## 4. What Happens Internally
61
+
62
+ 1. The model is checked against `allowed_models`.
63
+ 2. The model schema (columns, associations, enums) is introspected.
64
+ 3. A strict AI prompt is built that allows only JSON DSL.
65
+ 4. AI output is cleaned and JSON-parsed.
66
+ 5. DSL is validated (fields, operators, sort, limit, keys).
67
+ 6. A safe ActiveRecord relation is built and returned.
68
+
69
+ ## 5. DSL Constraints (Important)
70
+
71
+ The AI can only use these operators:
72
+
73
+ - `eq`
74
+ - `gt`
75
+ - `lt`
76
+ - `gte`
77
+ - `lte`
78
+ - `between`
79
+ - `in`
80
+ - `like`
81
+
82
+ Safety rules:
83
+
84
+ - Unknown fields are rejected.
85
+ - Unknown operators are rejected.
86
+ - Unknown JSON keys are rejected.
87
+ - `limit` must be `<= config.max_limit`.
88
+ - Joins are blocked unless explicitly allowed.
89
+
90
+ ## 6. Tenant Safety Hook
91
+
92
+ If your model defines `current_tenant_scope`, it is automatically merged:
93
+
94
+ ```ruby
95
+ class Invoice < ApplicationRecord
96
+ def self.current_tenant_scope
97
+ where(account_id: Current.account_id)
98
+ end
99
+ end
100
+ ```
101
+
102
+ This helps enforce tenant boundaries by default.
103
+
104
+ ## 7. Common Errors
105
+
106
+ - `Queryclerk::UnauthorizedModel`
107
+ : model is not in `allowed_models`.
108
+ - `Queryclerk::InvalidModelError`
109
+ : model is not an ActiveRecord model.
110
+ - `Queryclerk::InvalidDSL`
111
+ : AI returned unsupported fields/operators/keys/limit.
112
+ - `Queryclerk::AIResponseError`
113
+ : AI response was invalid or API call failed.
114
+
115
+ ## 8. Basic Controller Example
116
+
117
+ ```ruby
118
+ class InvoicesController < ApplicationController
119
+ def search
120
+ relation = Queryclerk.query(
121
+ prompt: params[:q],
122
+ model: Invoice
123
+ )
124
+
125
+ @invoices = relation.limit(50)
126
+ rescue Queryclerk::Error => e
127
+ render json: { error: e.message }, status: :unprocessable_entity
128
+ end
129
+ end
130
+ ```
131
+
132
+ ## 9. Testing Your Integration
133
+
134
+ Run library tests:
135
+
136
+ ```bash
137
+ bundle exec rspec
138
+ ```
139
+
140
+ For app-level tests, mock `Queryclerk.query` in controller/service specs and assert:
141
+
142
+ - It returns a relation.
143
+ - Unauthorized models are rejected.
144
+ - Tenant constraints remain applied.
data/docs/HOME.md ADDED
@@ -0,0 +1,13 @@
1
+ # Queryclerk Documentation
2
+
3
+ Documentation page: https://jijobose.com/libraries/queryclerk
4
+
5
+ ## Start Here
6
+
7
+ - Developer guide: `docs/DEVELOPER_GUIDE.md`
8
+ - Package overview: `README.md`
9
+ - Release history: `CHANGELOG.md`
10
+
11
+ ## Scope
12
+
13
+ The current docs cover installation, configuration, query safety model, and Rails integration patterns.
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Queryclerk
6
+ # Converts natural language + schema prompt into parsed DSL JSON.
7
+ class AIAdapter
8
+ def initialize(client:)
9
+ @client = client
10
+ end
11
+
12
+ def call(system_prompt:, user_prompt:)
13
+ raw_content = @client.chat_completion(system_prompt: system_prompt, user_prompt: user_prompt)
14
+ parse_json(extract_json(raw_content))
15
+ rescue AIResponseError
16
+ raise
17
+ rescue StandardError => e
18
+ raise AIResponseError, "Failed to parse AI response: #{e.message}"
19
+ end
20
+
21
+ private
22
+
23
+ def extract_json(raw_content)
24
+ content = raw_content.to_s.strip
25
+
26
+ if content.start_with?("```")
27
+ content = content.gsub(/\A```(?:json)?\s*/i, "").gsub(/\s*```\z/, "")
28
+ end
29
+
30
+ first_brace = content.index("{")
31
+ last_brace = content.rindex("}")
32
+ raise AIResponseError, "No JSON object found in AI response" unless first_brace && last_brace
33
+
34
+ content[first_brace..last_brace]
35
+ end
36
+
37
+ def parse_json(json_string)
38
+ parsed = JSON.parse(json_string)
39
+ raise AIResponseError, "AI response must be a JSON object" unless parsed.is_a?(Hash)
40
+
41
+ parsed
42
+ rescue JSON::ParserError
43
+ raise AIResponseError, "AI returned invalid JSON"
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "providers"
4
+
5
+ module Queryclerk
6
+ # Transport facade. Selects the provider configured via
7
+ # `configuration.provider` and delegates chat completion to it.
8
+ #
9
+ # Kept as a stable entry point so callers (and AIAdapter) depend on a single
10
+ # `#chat_completion(system_prompt:, user_prompt:)` interface regardless of
11
+ # whether the backing provider is OpenAI, Anthropic, or another vendor.
12
+ class Client
13
+ def initialize(configuration:, connection: nil)
14
+ @provider = Providers.build(configuration: configuration, connection: connection)
15
+ end
16
+
17
+ def chat_completion(system_prompt:, user_prompt:)
18
+ @provider.chat_completion(system_prompt: system_prompt, user_prompt: user_prompt)
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Queryclerk
4
+ # Runtime configuration for Queryclerk.
5
+ class Configuration
6
+ DEFAULT_PROVIDER = :openai
7
+ DEFAULT_MAX_LIMIT = 100
8
+ DEFAULT_TIMEOUT = 15
9
+ DEFAULT_MAX_TOKENS = 1024
10
+ DEFAULT_ANTHROPIC_VERSION = "2023-06-01"
11
+
12
+ # Per-provider defaults for endpoint and model. Used only when the
13
+ # corresponding setting is not explicitly assigned.
14
+ PROVIDER_DEFAULTS = {
15
+ openai: {
16
+ api_base_url: "https://api.openai.com/v1",
17
+ model_name: "gpt-4o-mini"
18
+ },
19
+ anthropic: {
20
+ api_base_url: "https://api.anthropic.com/v1",
21
+ model_name: "claude-sonnet-4-6"
22
+ }
23
+ }.freeze
24
+
25
+ # Backwards-compatible constants (OpenAI defaults).
26
+ DEFAULT_MODEL_NAME = PROVIDER_DEFAULTS[:openai][:model_name]
27
+ DEFAULT_API_BASE_URL = PROVIDER_DEFAULTS[:openai][:api_base_url]
28
+
29
+ # `max_tokens` and `anthropic_version` are consumed only by the Anthropic
30
+ # adapter; the OpenAI adapter ignores them.
31
+ attr_accessor :api_key, :max_limit, :allowed_models, :request_timeout,
32
+ :temperature, :allowed_associations, :max_tokens,
33
+ :anthropic_version
34
+ attr_writer :provider, :model_name, :api_base_url
35
+
36
+ def initialize
37
+ @api_key = @model_name = @api_base_url = nil
38
+ @provider = DEFAULT_PROVIDER
39
+ @max_limit = DEFAULT_MAX_LIMIT
40
+ @allowed_models = []
41
+ @request_timeout = DEFAULT_TIMEOUT
42
+ @temperature = 0.0
43
+ @allowed_associations = {}
44
+ @max_tokens = DEFAULT_MAX_TOKENS
45
+ @anthropic_version = DEFAULT_ANTHROPIC_VERSION
46
+ end
47
+
48
+ # Normalized provider symbol (e.g. :openai, :anthropic).
49
+ def provider
50
+ @provider.to_s.strip.downcase.to_sym
51
+ end
52
+
53
+ # Explicit model name, or the provider default when unset.
54
+ def model_name
55
+ @model_name || provider_default(:model_name)
56
+ end
57
+
58
+ # Explicit base URL, or the provider default when unset.
59
+ def api_base_url
60
+ @api_base_url || provider_default(:api_base_url)
61
+ end
62
+
63
+ private
64
+
65
+ def provider_default(key)
66
+ defaults = PROVIDER_DEFAULTS[provider] || PROVIDER_DEFAULTS[DEFAULT_PROVIDER]
67
+ defaults.fetch(key)
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,158 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Queryclerk
4
+ # Validates and normalizes the AI-generated query DSL.
5
+ class DSLParser
6
+ ALLOWED_TOP_LEVEL_KEYS = %w[filters limit sort joins].freeze
7
+ ALLOWED_OPERATORS = %w[eq gt lt gte lte between in like].freeze
8
+ ALLOWED_SORT_DIRECTIONS = %w[asc desc].freeze
9
+
10
+ def initialize(model:, schema:, dsl:, max_limit:)
11
+ @model = model
12
+ @schema = schema
13
+ @dsl = dsl
14
+ @max_limit = max_limit
15
+ @columns = @schema.fetch(:columns).keys
16
+ @associations = @schema.fetch(:associations).keys
17
+ @association_columns = @schema.fetch(:association_columns, {})
18
+ end
19
+
20
+ def call
21
+ raise InvalidDSL, "DSL must be a JSON object" unless @dsl.is_a?(Hash)
22
+
23
+ dsl = deep_stringify_keys(@dsl)
24
+ validate_top_level_keys!(dsl)
25
+
26
+ filters = validate_filters!(dsl.fetch("filters", []))
27
+ limit = validate_limit!(dsl.fetch("limit", @max_limit))
28
+ sort = validate_sort!(dsl["sort"])
29
+ joins = validate_joins!(dsl.fetch("joins", []))
30
+
31
+ {
32
+ "filters" => filters,
33
+ "limit" => limit,
34
+ "sort" => sort,
35
+ "joins" => joins
36
+ }
37
+ end
38
+
39
+ private
40
+
41
+ def deep_stringify_keys(value)
42
+ case value
43
+ when Hash
44
+ value.each_with_object({}) do |(key, val), memo|
45
+ memo[key.to_s] = deep_stringify_keys(val)
46
+ end
47
+ when Array
48
+ value.map { |val| deep_stringify_keys(val) }
49
+ else
50
+ value
51
+ end
52
+ end
53
+
54
+ def validate_top_level_keys!(dsl)
55
+ unknown = dsl.keys - ALLOWED_TOP_LEVEL_KEYS
56
+ raise InvalidDSL, "Unknown DSL keys: #{unknown.join(', ')}" if unknown.any?
57
+ end
58
+
59
+ def validate_filters!(filters)
60
+ raise InvalidDSL, "filters must be an array" unless filters.is_a?(Array)
61
+
62
+ filters.map do |filter|
63
+ raise InvalidDSL, "each filter must be an object" unless filter.is_a?(Hash)
64
+
65
+ keys = filter.keys
66
+ unknown = keys - %w[field operator value]
67
+ raise InvalidDSL, "Unknown filter keys: #{unknown.join(', ')}" if unknown.any?
68
+
69
+ field = filter["field"].to_s
70
+ operator = filter["operator"].to_s
71
+ value = filter["value"]
72
+
73
+ validate_field!(field)
74
+ validate_operator!(operator)
75
+ validate_operator_value!(operator, value)
76
+
77
+ { "field" => field, "operator" => operator, "value" => value }
78
+ end
79
+ end
80
+
81
+ def validate_limit!(limit)
82
+ raise InvalidDSL, "limit must be an integer" unless limit.is_a?(Integer)
83
+
84
+ SafetyGuard.enforce_limit!(limit: limit, max_limit: @max_limit)
85
+ limit
86
+ end
87
+
88
+ def validate_sort!(sort)
89
+ return nil if sort.nil?
90
+ raise InvalidDSL, "sort must be an object" unless sort.is_a?(Hash)
91
+
92
+ unknown = sort.keys - %w[field direction]
93
+ raise InvalidDSL, "Unknown sort keys: #{unknown.join(', ')}" if unknown.any?
94
+
95
+ field = sort.fetch("field").to_s
96
+ direction = sort.fetch("direction").to_s.downcase
97
+
98
+ validate_field!(field)
99
+ unless ALLOWED_SORT_DIRECTIONS.include?(direction)
100
+ raise InvalidDSL, "sort direction must be asc or desc"
101
+ end
102
+
103
+ { "field" => field, "direction" => direction }
104
+ end
105
+
106
+ def validate_joins!(joins)
107
+ raise InvalidDSL, "joins must be an array" unless joins.is_a?(Array)
108
+
109
+ joins.map do |association|
110
+ name = association.to_s
111
+ unless @associations.include?(name)
112
+ raise InvalidDSL, "Unknown association join: #{name}"
113
+ end
114
+
115
+ name
116
+ end
117
+ end
118
+
119
+ def validate_field!(field)
120
+ return if @columns.include?(field)
121
+ return if valid_association_field?(field)
122
+
123
+ raise InvalidDSL, "Unknown field: #{field}"
124
+ end
125
+
126
+ def valid_association_field?(field)
127
+ association_name, column_name = field.split(".", 2)
128
+ return false if association_name.to_s.empty? || column_name.to_s.empty?
129
+
130
+ return false unless @associations.include?(association_name)
131
+
132
+ association_columns = @association_columns.fetch(association_name, {}).fetch(:columns, nil) ||
133
+ @association_columns.fetch(association_name, {}).fetch("columns", nil)
134
+ return false unless association_columns
135
+
136
+ association_columns.keys.map(&:to_s).include?(column_name)
137
+ end
138
+
139
+ def validate_operator!(operator)
140
+ return if ALLOWED_OPERATORS.include?(operator)
141
+
142
+ raise InvalidDSL, "Unknown operator: #{operator}"
143
+ end
144
+
145
+ def validate_operator_value!(operator, value)
146
+ case operator
147
+ when "between"
148
+ unless value.is_a?(Array) && value.length == 2
149
+ raise InvalidDSL, "between operator requires exactly two values"
150
+ end
151
+ when "in"
152
+ raise InvalidDSL, "in operator requires an array" unless value.is_a?(Array)
153
+ when "like"
154
+ raise InvalidDSL, "like operator requires a scalar value" if value.is_a?(Array) || value.is_a?(Hash)
155
+ end
156
+ end
157
+ end
158
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Queryclerk
4
+ # Base error class for all gem-specific failures.
5
+ class Error < StandardError; end
6
+
7
+ # Raised when the given model is not an ActiveRecord model.
8
+ class InvalidModelError < Error; end
9
+
10
+ # Raised when AI output does not conform to the expected DSL.
11
+ class InvalidDSL < Error; end
12
+
13
+ # Raised when AI API responses are malformed or unusable.
14
+ class AIResponseError < Error; end
15
+
16
+ # Raised when a model is not explicitly whitelisted.
17
+ class UnauthorizedModel < Error; end
18
+
19
+ # Raised when the gem is misconfigured (missing API key, unknown provider, ...).
20
+ class ConfigurationError < Error; end
21
+ end