noiseless 0.9.0 → 0.10.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 195219b6de1210cb1f888a5a322e41c624403b7cab4f07cbd700ca9f5f573196
4
- data.tar.gz: b92048b781e491ae6c8f0d9114dbf4a4094ba04b7e06bf8394c3a6164e18521a
3
+ metadata.gz: 65b1aaff083bb9898dcb69d01d412205018f0904db09fdbb5d0b261e46989ab4
4
+ data.tar.gz: ae6508227db074ed28daf2266a11e4d6784cf1e38c37719715c3f5cf7e01480e
5
5
  SHA512:
6
- metadata.gz: afc592e3f9e505ff2272845eb4b8cddaae23543400fe83b1c11c70895fd0b8a537e670c1cc78103df93999f72f51cc0cdb8c008772a59e1e881df024e5a9cf24
7
- data.tar.gz: 7b4a4113ea30314fbed156161dfa031344881ba17f422ac233cd5a92b91f2b63ff4f7e07282e3a993e98bf42d48d87813b8c4e3aea23ece3365695a1779b382e
6
+ metadata.gz: 37e2de88e1ee52917997fee2fb0c1c60f8beab3a3b4a3ad9b8696f288aef62a8b767e50a3cd288051ccc47f6f23a0d9f79072c0598b835fcfba8c190767094a2
7
+ data.tar.gz: a43a00aecff40deec1614468083ebe9bcb1af2d52da2b9b3d8812195a10e500bf71841811182ad8a6d5a92a60d203ba82af6d693bbe33497d43a11f44d8129c9
data/README.md CHANGED
@@ -186,6 +186,37 @@ class CompaniesController < ApplicationController
186
186
  end
187
187
  ```
188
188
 
189
+ ### Text Matching on a Relation (PostgreSQL)
190
+
191
+ `Noiseless::TextMatch` applies the PostgreSQL adapter's match SQL to a relation you already
192
+ have, so scoping, joins and ordering stay yours:
193
+
194
+ ```ruby
195
+ scope = Company.where(owner: current_user).joins(:country)
196
+
197
+ Noiseless::TextMatch.apply(scope, params[:q], folded: %w[name countries.name], contains: :vat_number)
198
+ ```
199
+
200
+ A row matches when any listed field does.
201
+
202
+ - `contains:` matches substrings ignoring case. Use it for identifiers and codes.
203
+ - `folded:` matches substrings ignoring case and accents (`unaccent`). Use it for names in
204
+ a filter: `muller` finds `Müller`.
205
+ - `fuzzy:` is `folded:` plus `pg_trgm` similarity, which also finds misspellings (and
206
+ look-alikes: `Australia` finds `Austria`). Use it for ranked search.
207
+ - `%`, `_` and `\` in the query are literal. A blank query returns the relation unchanged.
208
+ - Fields are column names, left unqualified as in hand-written SQL, or `table.column` /
209
+ `schema.table.column` for joined tables. Unknown qualified columns raise `ArgumentError`.
210
+
211
+ `unaccent()` is not immutable, so PostgreSQL cannot index it. Define the wrapper once
212
+ (e.g. in a migration) and `folded:`/`fuzzy:` use it, which makes them indexable:
213
+
214
+ ```ruby
215
+ execute Noiseless::TextMatch::UNACCENT_FUNCTION_SQL
216
+ add_index :companies, "noiseless_unaccent(name::text) gin_trgm_ops", using: :gin
217
+ add_index :orders, "(reference::text) gin_trgm_ops", using: :gin # for contains:
218
+ ```
219
+
189
220
  ## Testing
190
221
 
191
222
  Add to `test/test_helper.rb`:
@@ -46,53 +46,23 @@ module Noiseless
46
46
  end
47
47
 
48
48
  def apply_match(scope, node, model)
49
- field = node.field.to_s
50
- value = node.value.to_s
51
-
52
- # Mapping-only fields (denormalized into a search index, not columns)
53
- # cannot be satisfied here; fail closed rather than matching everything.
54
- return scope.none unless column?(model, field)
55
-
56
- # Use pg_trgm similarity for fuzzy matching, accent-insensitive when
57
- # the unaccent extension is present.
58
- if trgm_available? && text_column?(model, field)
59
- scope.where(
60
- "#{fuzzy_column(field)} % #{fuzzy_param} OR " \
61
- "#{fuzzy_column(field)} ILIKE #{fuzzy_param}",
62
- value,
63
- "%#{sanitize_like(value)}%"
64
- )
65
- else
66
- # Fallback to ILIKE
67
- scope.where("#{quoted_column(field)} ILIKE ?", "%#{sanitize_like(value)}%")
68
- end
49
+ text_match(scope, node.value, [node.field], model)
69
50
  end
70
51
 
71
52
  def apply_multi_match(scope, node, model)
72
- query = node.query.to_s
73
- # Drop mapping-only fields; if none of the requested fields are real
74
- # columns the query cannot be satisfied — fail closed.
75
- fields = node.fields.map(&:to_s).select { |field| column?(model, field) }
76
- return scope.none if fields.empty?
77
-
78
- conditions = fields.map do |field|
79
- if trgm_available? && text_column?(model, field)
80
- "(#{fuzzy_column(field)} % #{fuzzy_param} OR " \
81
- "#{fuzzy_column(field)} ILIKE #{fuzzy_param})"
82
- else
83
- "#{quoted_column(field)} ILIKE ?"
84
- end
85
- end
53
+ text_match(scope, node.query, node.fields, model)
54
+ end
86
55
 
87
- params = fields.flat_map do |field|
88
- if trgm_available? && text_column?(model, field)
89
- [query, "%#{sanitize_like(query)}%"]
90
- else
91
- ["%#{sanitize_like(query)}%"]
92
- end
93
- end
56
+ # Mapping-only fields (denormalized into a search index, not columns)
57
+ # cannot be satisfied here; fail closed rather than matching everything.
58
+ # Text columns match fuzzily; other columns as case-insensitive substrings.
59
+ def text_match(scope, query, fields, model)
60
+ fields = fields.map(&:to_s).select { |field| column?(model, field) }
61
+ return scope.none if fields.empty?
94
62
 
95
- scope.where(conditions.join(" OR "), *params)
63
+ table = model.table_name
64
+ text, other = fields.partition { |field| text_column?(model, field) }.map { |group| group.map { "#{table}.#{it}" } }
65
+ TextMatch.apply(scope, query, fuzzy: text, contains: other)
96
66
  end
97
67
 
98
68
  def apply_wildcard(scope, node, model = nil)
@@ -121,7 +91,7 @@ module Noiseless
121
91
  def apply_prefix(scope, node, model = nil)
122
92
  return scope.none if model && !column?(model, node.field.to_s)
123
93
 
124
- scope.where("#{quoted_column(node.field.to_s)} ILIKE ?", "#{sanitize_like(node.value)}%")
94
+ scope.where("#{quoted_column(node.field.to_s)} ILIKE ?", "#{TextMatch.escape_like(node.value)}%")
125
95
  end
126
96
 
127
97
  def apply_filter_clauses(scope, filter_nodes, model = nil)
@@ -207,14 +177,6 @@ module Noiseless
207
177
  scope.limit(per_page).offset(offset)
208
178
  end
209
179
 
210
- def trgm_available?
211
- @trgm_available ||= available_extensions.include?("pg_trgm")
212
- end
213
-
214
- def unaccent_available?
215
- @unaccent_available ||= available_extensions.include?("unaccent")
216
- end
217
-
218
180
  def column?(model, field)
219
181
  model.columns_hash.key?(field.to_s)
220
182
  end
@@ -233,23 +195,10 @@ module Noiseless
233
195
  value.is_a?(Hash) && value.any? && (value.keys.map(&:to_sym) - Noiseless::Adapter::RANGE_OPERATORS).empty?
234
196
  end
235
197
 
236
- def fuzzy_column(field)
237
- unaccent_available? ? "unaccent(#{quoted_column(field)})" : quoted_column(field)
238
- end
239
-
240
- def fuzzy_param
241
- unaccent_available? ? "unaccent(?)" : "?"
242
- end
243
-
244
198
  def quoted_column(field)
245
199
  ActiveRecord::Base.connection.quote_column_name(field)
246
200
  end
247
201
 
248
- def sanitize_like(value)
249
- # Escape special LIKE characters
250
- value.to_s.gsub(/[%_\\]/) { |x| "\\#{x}" }
251
- end
252
-
253
202
  def parse_distance(distance)
254
203
  # Parse OpenSearch distance format (e.g., "10km", "5mi")
255
204
  case distance.to_s
@@ -0,0 +1,120 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "concurrent/map"
4
+
5
+ module Noiseless
6
+ # Case-insensitive text matching on an existing ActiveRecord relation, compiled
7
+ # to the same SQL the PostgreSQL adapter uses for match queries.
8
+ #
9
+ # Noiseless::TextMatch.apply(Company.where(owner: user), "miauwer", folded: %w[name countries.name])
10
+ # Noiseless::TextMatch.apply(Variant.all, "TC-2041", folded: :name, contains: %i[sku gtin])
11
+ #
12
+ # - contains: substring, ignoring case. For identifiers and codes.
13
+ # - folded: substring, ignoring case and accents. For names in a filter.
14
+ # - fuzzy: folded, plus pg_trgm similarity for misspellings. For ranked search.
15
+ #
16
+ # A row matches when any listed field does.
17
+ # Fields are column names, or "table.column" / "schema.table.column" for joined tables
18
+ # (checked against the schema).
19
+ # Columns are cast to text, so the matching trigram indexes are
20
+ # `gin ((column::text) gin_trgm_ops)` for contains and
21
+ # `gin (noiseless_unaccent(column::text) gin_trgm_ops)` for folded and fuzzy.
22
+ # `unaccent()` is not immutable and cannot be indexed; when the database defines
23
+ # UNACCENT_FUNCTION_SQL, folded and fuzzy call that wrapper instead.
24
+ module TextMatch
25
+ UNACCENT_FUNCTION = "noiseless_unaccent"
26
+
27
+ UNACCENT_FUNCTION_SQL = <<~SQL
28
+ CREATE OR REPLACE FUNCTION noiseless_unaccent(text) RETURNS text
29
+ LANGUAGE sql IMMUTABLE PARALLEL SAFE STRICT
30
+ RETURN unaccent('unaccent'::regdictionary, $1);
31
+ SQL
32
+
33
+ Capabilities = Data.define(:trgm, :unaccent, :unaccent_function)
34
+
35
+ @capabilities = Concurrent::Map.new
36
+
37
+ class << self
38
+ def apply(relation, query, **fields)
39
+ sql, *binds = condition(relation, query, **fields)
40
+ sql ? relation.where(sql, *binds) : relation
41
+ end
42
+
43
+ # [sql, *binds] for one OR-joined condition over the fields; [] for a blank query.
44
+ def condition(relation, query, contains: [], folded: [], fuzzy: [])
45
+ fields = { contains:, folded:, fuzzy: }.flat_map { |mode, names| Array(names).map { [it, mode] } }
46
+ raise ArgumentError, "text match needs at least one field" if fields.empty?
47
+
48
+ columns = fields.map { |field, mode| [column_sql(relation, field.to_s), mode] }
49
+ query = query.to_s.strip
50
+ return [] if query.empty?
51
+
52
+ connection = relation.connection
53
+ pattern = "%#{escape_like(query)}%"
54
+ clauses, binds = columns.map { |column, mode| clause(connection, column, query, pattern, mode) }.transpose
55
+
56
+ [clauses.join(" OR "), *binds.flatten(1)]
57
+ end
58
+
59
+ def escape_like(value)
60
+ value.to_s.gsub(/[%_\\]/) { "\\#{it}" }
61
+ end
62
+
63
+ def capabilities(connection)
64
+ @capabilities.compute_if_absent(connection.pool.db_config) { detect(connection) }
65
+ end
66
+
67
+ def reset_capabilities!
68
+ @capabilities.clear
69
+ end
70
+
71
+ private
72
+
73
+ def clause(connection, column, query, pattern, mode)
74
+ return ["#{column} ILIKE ?", [pattern]] if mode == :contains
75
+
76
+ caps = capabilities(connection)
77
+ normalize = unaccent_sql(caps)
78
+ target = normalize.call(column)
79
+ like = "#{target} ILIKE #{normalize.call('?')}"
80
+ return ["(#{like})", [pattern]] unless mode == :fuzzy && caps.trgm
81
+
82
+ ["(#{target} % #{normalize.call('?')} OR #{like})", [query, pattern]]
83
+ end
84
+
85
+ def unaccent_sql(caps)
86
+ if caps.unaccent_function then ->(sql) { "#{UNACCENT_FUNCTION}(#{sql})" }
87
+ elsif caps.unaccent then ->(sql) { "unaccent(#{sql})" }
88
+ else ->(sql) { sql }
89
+ end
90
+ end
91
+
92
+ # Bare fields stay unqualified, resolved by PostgreSQL like hand-written SQL
93
+ # (against the relation's table or whatever it joins); "table.column" fields
94
+ # are checked against the schema.
95
+ def column_sql(relation, field)
96
+ connection = relation.connection
97
+ return "#{connection.quote_column_name(field)}::text" unless field.include?(".")
98
+
99
+ table, _, column = field.rpartition(".")
100
+ schema_cache = connection.schema_cache
101
+ unless schema_cache.data_source_exists?(table) && schema_cache.columns_hash(table).key?(column)
102
+ raise ArgumentError, "unknown column #{table}.#{column}"
103
+ end
104
+
105
+ "#{connection.quote_table_name(table)}.#{connection.quote_column_name(column)}::text"
106
+ end
107
+
108
+ def detect(connection)
109
+ row = connection.select_one(<<~SQL.squish)
110
+ SELECT
111
+ EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_trgm') AS trgm,
112
+ EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'unaccent') AS unaccent,
113
+ to_regprocedure('#{UNACCENT_FUNCTION}(text)') IS NOT NULL AS unaccent_function
114
+ SQL
115
+
116
+ Capabilities.new(trgm: row["trgm"], unaccent: row["unaccent"], unaccent_function: row["unaccent_function"])
117
+ end
118
+ end
119
+ end
120
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Noiseless
4
- VERSION = "0.9.0"
4
+ VERSION = "0.10.0"
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: noiseless
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.9.0
4
+ version: 0.10.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Abdelkader Boudih
@@ -305,6 +305,7 @@ files:
305
305
  - lib/noiseless/search_index_update_job.rb
306
306
  - lib/noiseless/test_case.rb
307
307
  - lib/noiseless/test_helper.rb
308
+ - lib/noiseless/text_match.rb
308
309
  - lib/noiseless/version.rb
309
310
  - lib/tasks/release.rake
310
311
  - lib/tasks/test.rake