instant_record 0.1.0 → 0.3.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.
Files changed (198) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +58 -0
  3. data/README.md +267 -61
  4. data/app/controllers/instant_record/bootstraps_controller.rb +39 -12
  5. data/app/controllers/instant_record/events_controller.rb +58 -6
  6. data/app/controllers/instant_record/files_controller.rb +116 -0
  7. data/app/controllers/instant_record/mutations_controller.rb +84 -5
  8. data/app/controllers/instant_record/native_screens_controller.rb +60 -0
  9. data/app/controllers/instant_record/records_controller.rb +86 -8
  10. data/app/controllers/instant_record/shells_controller.rb +64 -0
  11. data/app/controllers/instant_record/sync_notices_controller.rb +81 -0
  12. data/app/helpers/instant_record/sync_notices_helper.rb +41 -0
  13. data/app/jobs/instant_record/shell_build_job.rb +16 -0
  14. data/app/models/instant_record/change.rb +36 -3
  15. data/app/models/instant_record/mutation_applier.rb +633 -50
  16. data/app/views/instant_record/sync_notices/_notices.html.erb +63 -0
  17. data/compiled/README.md +272 -0
  18. data/compiled/pipeline/browser_migrations.rb +18 -0
  19. data/compiled/pipeline/build.rb +13 -0
  20. data/compiled/pipeline/build_native.rb +14 -0
  21. data/compiled/pipeline/native/host.c +78 -0
  22. data/compiled/pipeline/native/instant_record_native.h +57 -0
  23. data/compiled/pipeline/native_shim.c +149 -0
  24. data/compiled/pipeline/reactor_shim.c +66 -0
  25. data/compiled/pipeline/sqlite/rh_shim.c +5 -0
  26. data/compiled/pipeline/sqlite_release.rb +43 -0
  27. data/compiled/toolchain.env.example +22 -0
  28. data/compiled/web/index.html +20 -0
  29. data/compiled/web/package-lock.json +884 -0
  30. data/compiled/web/package.json +17 -0
  31. data/compiled/web/src/app-host-core.js +556 -0
  32. data/compiled/web/src/app-host.js +16 -0
  33. data/compiled/web/src/branch-manager.js +140 -0
  34. data/compiled/web/src/branch-preview.js +397 -0
  35. data/compiled/web/src/changes.js +191 -0
  36. data/compiled/web/src/faults.js +172 -0
  37. data/compiled/web/src/flight-recorder.js +347 -0
  38. data/compiled/web/src/history-fill.js +68 -0
  39. data/compiled/web/src/http-headers.js +100 -0
  40. data/compiled/web/src/leader-election.js +705 -0
  41. data/compiled/web/src/main.js +608 -0
  42. data/compiled/web/src/manifest.js +112 -0
  43. data/compiled/web/src/opfs-wasi-core.js +109 -0
  44. data/compiled/web/src/opfs-wasi-file.js +8 -0
  45. data/compiled/web/src/reactor-runtime.js +1692 -0
  46. data/compiled/web/src/redactor.js +518 -0
  47. data/compiled/web/src/release-updates.js +48 -0
  48. data/compiled/web/src/replay.js +338 -0
  49. data/compiled/web/src/schema-recovery.js +204 -0
  50. data/compiled/web/src/server-request.js +68 -0
  51. data/compiled/web/src/sha256.js +98 -0
  52. data/compiled/web/src/shell.js +52 -0
  53. data/compiled/web/src/snapshot-store.js +38 -0
  54. data/compiled/web/src/sqlite-redactor.js +111 -0
  55. data/compiled/web/src/storage-backend.js +159 -0
  56. data/compiled/web/src/stream-leader.js +675 -0
  57. data/compiled/web/src/sync-context.js +91 -0
  58. data/compiled/web/src/sync-drain.js +104 -0
  59. data/compiled/web/src/sync-schedule.js +9 -0
  60. data/compiled/web/src/wasi-minimal.js +275 -0
  61. data/compiled/web/src/worker.js +39 -0
  62. data/compiled/web/vite.config.js +27 -0
  63. data/config/routes.rb +25 -0
  64. data/db/migrate/20261119000201_add_scope_to_instant_record_changes.rb +7 -0
  65. data/db/migrate/20261121000001_create_instant_record_sync_notices.rb +21 -0
  66. data/db/migrate/20261121000101_add_partition_to_instant_record_changes.rb +8 -0
  67. data/db/migrate/20261121230300_add_delay_line_to_instant_record_outbox.rb +10 -0
  68. data/exe/instant_record_mcp +6 -0
  69. data/frontend/LiveList.js +67 -0
  70. data/frontend/chord.js +79 -0
  71. data/frontend/file.js +65 -0
  72. data/frontend/files.js +738 -0
  73. data/frontend/focus.js +10 -0
  74. data/frontend/held.js +192 -0
  75. data/frontend/http.js +76 -0
  76. data/frontend/index.js +53 -0
  77. data/frontend/keyboard.js +56 -0
  78. data/frontend/live.js +298 -0
  79. data/frontend/notices.js +118 -0
  80. data/frontend/package.json +15 -0
  81. data/frontend/range.js +10 -0
  82. data/frontend/selection.js +47 -0
  83. data/frontend/shortcuts.js +25 -0
  84. data/frontend/sync-notices.js +130 -0
  85. data/frontend/undo.js +48 -0
  86. data/frontend/window.js +181 -0
  87. data/lib/generators/instant_record/install/install_generator.rb +18 -30
  88. data/lib/generators/instant_record/install/templates/instant_record.rb +34 -0
  89. data/lib/generators/instant_record/ios/ios_generator.rb +71 -0
  90. data/lib/generators/instant_record/ios/templates/App.swift.tt +35 -0
  91. data/lib/generators/instant_record/ios/templates/Info.plist +11 -0
  92. data/lib/generators/instant_record/ios/templates/LibraryEngine.swift +30 -0
  93. data/lib/instant_record/branch/sqlite_store.rb +142 -0
  94. data/lib/instant_record/branch.rb +388 -0
  95. data/lib/instant_record/client/notifier.rb +8 -12
  96. data/lib/instant_record/client/rebaser.rb +565 -0
  97. data/lib/instant_record/client/transport.rb +64 -42
  98. data/lib/instant_record/client.rb +1600 -169
  99. data/lib/instant_record/compiled_site.rb +85 -0
  100. data/lib/instant_record/compiler/app_stage.rb +212 -0
  101. data/lib/instant_record/compiler/ast_lowerer.rb +659 -0
  102. data/lib/instant_record/compiler/browser_migrations.rb +161 -0
  103. data/lib/instant_record/compiler/entry_builder.rb +832 -0
  104. data/lib/instant_record/compiler/fts5_smoke.rb +205 -0
  105. data/lib/instant_record/compiler/gem_vendor.rb +194 -0
  106. data/lib/instant_record/compiler/host_adapters.rb +506 -0
  107. data/lib/instant_record/compiler/kotlin_codegen.rb +209 -0
  108. data/lib/instant_record/compiler/manifest.rb +178 -0
  109. data/lib/instant_record/compiler/native_build.rb +586 -0
  110. data/lib/instant_record/compiler/native_contracts.rb +338 -0
  111. data/lib/instant_record/compiler/path_scrubber.rb +31 -0
  112. data/lib/instant_record/compiler/reachability_tracer.rb +1188 -0
  113. data/lib/instant_record/compiler/route_analyzer.rb +623 -0
  114. data/lib/instant_record/compiler/runner.rb +42 -0
  115. data/lib/instant_record/compiler/schema_lock.rb +606 -0
  116. data/lib/instant_record/compiler/source_pages.rb +77 -0
  117. data/lib/instant_record/compiler/static_linter.rb +770 -0
  118. data/lib/instant_record/compiler/swift_codegen.rb +341 -0
  119. data/lib/instant_record/compiler/toolchain.rb +219 -0
  120. data/lib/instant_record/compiler/wasm_build.rb +704 -0
  121. data/lib/instant_record/compiler/wasm_tree.rb +518 -0
  122. data/lib/instant_record/compiler.rb +277 -0
  123. data/lib/instant_record/configuration.rb +104 -0
  124. data/lib/instant_record/engine.rb +68 -18
  125. data/lib/instant_record/file_store.rb +162 -0
  126. data/lib/instant_record/files.rb +92 -0
  127. data/lib/instant_record/hlc.rb +387 -0
  128. data/lib/instant_record/host.rb +66 -0
  129. data/lib/instant_record/inertia/renderer.rb +52 -0
  130. data/lib/instant_record/inertia.rb +222 -0
  131. data/lib/instant_record/mcp/cli.rb +319 -0
  132. data/lib/instant_record/mcp/host_process.rb +229 -0
  133. data/lib/instant_record/mcp/http_exchange.rb +233 -0
  134. data/lib/instant_record/mcp/replica.rb +556 -0
  135. data/lib/instant_record/mcp/runtime.rb +406 -0
  136. data/lib/instant_record/mcp/server.rb +429 -0
  137. data/lib/instant_record/mcp.rb +47 -0
  138. data/lib/instant_record/native/contract.rb +367 -0
  139. data/lib/instant_record/native/node.rb +125 -0
  140. data/lib/instant_record/native/screen.rb +366 -0
  141. data/lib/instant_record/native/xcode_project.rb +344 -0
  142. data/lib/instant_record/native.rb +41 -0
  143. data/lib/instant_record/outbox_mutation.rb +81 -9
  144. data/lib/instant_record/outbox_upcaster.rb +161 -0
  145. data/lib/instant_record/read_tracker.rb +610 -0
  146. data/lib/instant_record/routing.rb +33 -0
  147. data/lib/instant_record/runtime_scoped.rb +4 -0
  148. data/lib/instant_record/shell.rb +486 -0
  149. data/lib/instant_record/sync_actions.rb +800 -0
  150. data/lib/instant_record/sync_metadata.rb +17 -2
  151. data/lib/instant_record/sync_notice.rb +234 -0
  152. data/lib/instant_record/sync_partition.rb +63 -0
  153. data/lib/instant_record/sync_scope.rb +300 -0
  154. data/lib/instant_record/sync_shape.rb +102 -0
  155. data/lib/instant_record/sync_window.rb +92 -15
  156. data/lib/instant_record/syncable.rb +313 -17
  157. data/lib/instant_record/testing/authoritative_server.rb +547 -0
  158. data/lib/instant_record/testing/chaos_simulator.rb +429 -0
  159. data/lib/instant_record/testing/cruby_host_bridge.rb +370 -0
  160. data/lib/instant_record/testing/fault_network.rb +140 -0
  161. data/lib/instant_record/testing/parity_suite.rb +435 -0
  162. data/lib/instant_record/testing/runtimes/base.rb +184 -0
  163. data/lib/instant_record/testing/runtimes/cruby_runtime.rb +255 -0
  164. data/lib/instant_record/testing/runtimes/native_runtime.rb +346 -0
  165. data/lib/instant_record/testing/runtimes/wasm_runtime.rb +371 -0
  166. data/lib/instant_record/testing/wasm_host_bridge.mjs +240 -0
  167. data/lib/instant_record/testing.rb +333 -0
  168. data/lib/instant_record/trace/redactor.rb +278 -0
  169. data/lib/instant_record/trace/replayer.rb +126 -0
  170. data/lib/instant_record/trace/schema_extractor.rb +37 -0
  171. data/lib/instant_record/trace.rb +22 -0
  172. data/lib/instant_record/version.rb +1 -1
  173. data/lib/instant_record.rb +107 -37
  174. data/lib/tasks/instant_record.rake +299 -47
  175. data/native/ios/InstantRecordNative/Package.swift +12 -0
  176. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/AppHost.swift +706 -0
  177. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Engine.swift +64 -0
  178. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/FileStore.swift +1048 -0
  179. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/HTTPEngine.swift +36 -0
  180. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Icons.swift +19 -0
  181. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Node.swift +64 -0
  182. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/ScreenView.swift +481 -0
  183. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Screens.swift +94 -0
  184. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/StreamClient.swift +74 -0
  185. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncNotice.swift +282 -0
  186. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncSchedule.swift +153 -0
  187. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Theme.swift +140 -0
  188. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Transport.swift +108 -0
  189. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/TypedContracts.swift +237 -0
  190. data/native/ios/README.md +341 -0
  191. data/sig/instant_record/inertia.rbs +47 -0
  192. data/sig/instant_record/native.rbs +38 -0
  193. metadata +194 -18
  194. data/lib/generators/instant_record/install/templates/database.js +0 -32
  195. data/lib/generators/instant_record/install/templates/index.html +0 -69
  196. data/lib/generators/instant_record/install/templates/rails.sw.js +0 -750
  197. data/lib/instant_record/local_schema.rb +0 -75
  198. data/lib/instant_record/pglite_compat.rb +0 -40
@@ -0,0 +1,556 @@
1
+ require "json"
2
+ require "sqlite3"
3
+
4
+ module InstantRecord
5
+ module Mcp
6
+ # Sub-millisecond (<1ms) read-only query and search interface over the
7
+ # native host's local SQLite replica.
8
+ #
9
+ # Never mutates SQLite directly — all writes go through the compiled native
10
+ # host so validations and outbox mutation recording run atomically.
11
+ class Replica
12
+ INTERNAL_TABLE_PREFIXES = %w[sqlite_ instant_record_].freeze
13
+ INTERNAL_TABLES = %w[ar_internal_metadata schema_migrations].freeze
14
+ BOOKKEEPING_COLUMNS = %w[server_version sync_state].freeze
15
+ DEFAULT_LIMIT = 50
16
+ MAX_LIMIT = 500
17
+ OPERATORS = %w[eq ne gt gte lt lte like in is_null not_null].freeze
18
+
19
+ ModelInfo = Struct.new(:name, :table, :columns, :primary_key, keyword_init: true)
20
+
21
+ attr_reader :database_path
22
+
23
+ def initialize(database_path:, models: nil)
24
+ @database_path = File.expand_path(database_path.to_s)
25
+ @explicit_models = normalize_model_list(models)
26
+ @db = nil
27
+ @model_index = nil
28
+ end
29
+
30
+ def reopen(new_path = @database_path)
31
+ close
32
+ @database_path = File.expand_path(new_path.to_s)
33
+ @model_index = nil
34
+ self
35
+ end
36
+
37
+ def refresh_schema!
38
+ @model_index = nil
39
+ end
40
+
41
+ def close
42
+ @db&.close unless @db&.closed?
43
+ @db = nil
44
+ @model_index = nil
45
+ end
46
+
47
+ def models
48
+ started = monotonic_now
49
+ list = resolved_models.values.map do |info|
50
+ quoted = quote_ident(info.table)
51
+ count = connection.get_first_value("SELECT COUNT(*) FROM #{quoted}").to_i
52
+ pending =
53
+ if info.columns.any? { |c| c[:name] == "sync_state" }
54
+ connection.get_first_value("SELECT COUNT(*) FROM #{quoted} WHERE \"sync_state\" = ?", ["pending"]).to_i
55
+ else
56
+ 0
57
+ end
58
+ {
59
+ "name" => info.name,
60
+ "table" => info.table,
61
+ "primary_key" => info.primary_key,
62
+ "count" => count,
63
+ "pending_count" => pending,
64
+ "columns" => info.columns.map { |col| stringify_hash(col) }
65
+ }
66
+ end
67
+ { "models" => list, "elapsed_ms" => elapsed_ms(started) }
68
+ end
69
+
70
+ def query(model:, where: {}, order: nil, limit: DEFAULT_LIMIT, offset: 0, columns: nil)
71
+ started = monotonic_now
72
+ info = resolve_model!(model)
73
+ valid_cols = info.columns.map { |c| c[:name] }
74
+
75
+ selected = select_columns(columns, valid_cols)
76
+ where_sql, binds = build_where(where, valid_cols)
77
+ order_sql = build_order(order, valid_cols)
78
+ clamped_limit = clamp_limit(limit)
79
+ clamped_offset = [offset.to_i, 0].max
80
+
81
+ table_sql = quote_ident(info.table)
82
+ total = connection.get_first_value("SELECT COUNT(*) FROM #{table_sql}#{where_sql}", binds).to_i
83
+
84
+ sql = "SELECT #{selected} FROM #{table_sql}#{where_sql}#{order_sql} LIMIT ? OFFSET ?"
85
+ rows = connection.execute(sql, binds + [clamped_limit, clamped_offset]).map { |row| normalize_row(row) }
86
+
87
+ {
88
+ "model" => info.name,
89
+ "table" => info.table,
90
+ "count" => rows.size,
91
+ "total" => total,
92
+ "limit" => clamped_limit,
93
+ "offset" => clamped_offset,
94
+ "rows" => rows,
95
+ "elapsed_ms" => elapsed_ms(started)
96
+ }
97
+ end
98
+
99
+ def find(model:, id:)
100
+ started = monotonic_now
101
+ info = resolve_model!(model)
102
+ pk = info.primary_key || "id"
103
+ sql = "SELECT * FROM #{quote_ident(info.table)} WHERE #{quote_ident(pk)} = ? LIMIT 1"
104
+ row = connection.get_first_row(sql, [bind_value(id)])
105
+
106
+ {
107
+ "model" => info.name,
108
+ "table" => info.table,
109
+ "id" => id,
110
+ "record" => row ? normalize_row(row) : nil,
111
+ "elapsed_ms" => elapsed_ms(started)
112
+ }
113
+ end
114
+
115
+ def search(query:, models: nil, columns: nil, limit: DEFAULT_LIMIT)
116
+ started = monotonic_now
117
+ text = query.to_s.strip
118
+ clamped_limit = clamp_limit(limit)
119
+ tokens = text.split(/\s+/).reject(&:empty?)
120
+
121
+ if tokens.empty?
122
+ return { "query" => text, "count" => 0, "matches" => [], "elapsed_ms" => elapsed_ms(started) }
123
+ end
124
+
125
+ target_models =
126
+ if models && !Array(models).empty?
127
+ Array(models).map { |name| resolve_model!(name) }
128
+ else
129
+ resolved_models.values
130
+ end
131
+
132
+ requested_cols = columns ? Array(columns).map(&:to_s) : nil
133
+ patterns = tokens.map { |token| "%#{escape_like(token.downcase)}%" }
134
+ lowered_tokens = tokens.map(&:downcase)
135
+
136
+ matches = []
137
+ target_models.each do |info|
138
+ break if matches.size >= clamped_limit
139
+
140
+ searchable = searchable_columns(info, requested_cols)
141
+ next if searchable.empty?
142
+
143
+ remaining = clamped_limit - matches.size
144
+ clauses = []
145
+ binds = []
146
+ patterns.each do |pattern|
147
+ per_col = searchable.map do |col|
148
+ binds << pattern
149
+ "LOWER(CAST(#{quote_ident(col)} AS TEXT)) LIKE ? ESCAPE '\\'"
150
+ end
151
+ clauses << "(#{per_col.join(' OR ')})"
152
+ end
153
+
154
+ order_clause =
155
+ if info.columns.any? { |c| c[:name] == "updated_at" }
156
+ " ORDER BY \"updated_at\" DESC"
157
+ elsif info.columns.any? { |c| c[:name] == "created_at" }
158
+ " ORDER BY \"created_at\" DESC"
159
+ else
160
+ ""
161
+ end
162
+
163
+ sql = "SELECT * FROM #{quote_ident(info.table)} WHERE #{clauses.join(' AND ')}#{order_clause} LIMIT ?"
164
+ rows = connection.execute(sql, binds + [remaining])
165
+ pk = info.primary_key || "id"
166
+
167
+ rows.each do |raw|
168
+ row = normalize_row(raw)
169
+ matched_cols = searchable.select do |col|
170
+ val = row[col]
171
+ next false if val.nil?
172
+
173
+ down = val.to_s.downcase
174
+ lowered_tokens.any? { |tok| down.include?(tok) }
175
+ end
176
+ matches << {
177
+ "model" => info.name,
178
+ "table" => info.table,
179
+ "id" => row[pk],
180
+ "matched_columns" => matched_cols,
181
+ "record" => row
182
+ }
183
+ end
184
+ end
185
+
186
+ {
187
+ "query" => text,
188
+ "count" => matches.size,
189
+ "matches" => matches,
190
+ "elapsed_ms" => elapsed_ms(started)
191
+ }
192
+ end
193
+
194
+ def outbox(limit: 100)
195
+ started = monotonic_now
196
+ clamped = clamp_limit(limit)
197
+ unless table_exists?("instant_record_outbox")
198
+ return { "count" => 0, "mutations" => [], "elapsed_ms" => elapsed_ms(started) }
199
+ end
200
+
201
+ total = connection.get_first_value("SELECT COUNT(*) FROM \"instant_record_outbox\"").to_i
202
+ rows = connection.execute(
203
+ "SELECT * FROM \"instant_record_outbox\" ORDER BY \"created_at\" ASC, \"id\" ASC LIMIT ?",
204
+ [clamped]
205
+ ).map do |raw|
206
+ row = normalize_row(raw)
207
+ if row["changes_payload"].is_a?(String) && !row["changes_payload"].empty?
208
+ row["changes"] = JSON.parse(row["changes_payload"]) rescue row["changes_payload"]
209
+ end
210
+ row
211
+ end
212
+
213
+ { "count" => total, "mutations" => rows, "elapsed_ms" => elapsed_ms(started) }
214
+ end
215
+
216
+ def metadata
217
+ return {} unless table_exists?("instant_record_sync_metadata")
218
+
219
+ connection.execute("SELECT \"key\", \"value\" FROM \"instant_record_sync_metadata\"").each_with_object({}) do |row, acc|
220
+ acc[row["key"].to_s] = row["value"]
221
+ end
222
+ end
223
+
224
+ private
225
+
226
+ def connection
227
+ if @db.nil? || @db.closed?
228
+ raise Error, "Local SQLite replica does not exist yet: #{@database_path}" unless File.file?(@database_path)
229
+
230
+ @db = SQLite3::Database.new(@database_path, readonly: true)
231
+ @db.results_as_hash = true
232
+ @db.busy_timeout = 5000
233
+ end
234
+ @db
235
+ end
236
+
237
+ def table_exists?(name)
238
+ !connection.get_first_value(
239
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?",
240
+ [name.to_s]
241
+ ).nil?
242
+ end
243
+
244
+ def all_user_tables
245
+ connection.execute("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").filter_map do |row|
246
+ name = row["name"].to_s
247
+ next if INTERNAL_TABLES.include?(name)
248
+ next if INTERNAL_TABLE_PREFIXES.any? { |prefix| name.start_with?(prefix) }
249
+
250
+ name
251
+ end
252
+ end
253
+
254
+ def resolved_models
255
+ return @model_index if @model_index
256
+
257
+ tables = all_user_tables
258
+ compiled = metadata["compiled_models"].to_s.split(",").map(&:strip).reject(&:empty?)
259
+ declared = @explicit_models && !@explicit_models.empty? ? @explicit_models : compiled
260
+
261
+ index = {}
262
+ if declared.any?
263
+ declared.each do |model_name|
264
+ table = match_table_for_model(model_name, tables)
265
+ next unless table
266
+
267
+ index[model_name] = build_model_info(model_name, table)
268
+ end
269
+ end
270
+
271
+ if index.empty?
272
+ tables.each do |table|
273
+ model_name = classify_table(table)
274
+ index[model_name] = build_model_info(model_name, table)
275
+ end
276
+ end
277
+
278
+ @model_index = index
279
+ end
280
+
281
+ def build_model_info(name, table)
282
+ cols = connection.execute("PRAGMA table_info(#{quote_ident(table)})").map do |col|
283
+ {
284
+ name: col["name"].to_s,
285
+ type: col["type"].to_s,
286
+ notnull: col["notnull"].to_i == 1,
287
+ primary_key: col["pk"].to_i > 0
288
+ }
289
+ end
290
+ pk = cols.find { |c| c[:primary_key] }&.dig(:name) || "id"
291
+ ModelInfo.new(name: name, table: table, columns: cols, primary_key: pk)
292
+ end
293
+
294
+ def resolve_model!(name)
295
+ key = name.to_s.strip
296
+ raise ArgumentError, "Model name is required" if key.empty?
297
+
298
+ models_map = resolved_models
299
+ return models_map[key] if models_map.key?(key)
300
+
301
+ down = key.downcase
302
+ found = models_map.values.find do |info|
303
+ info.name.downcase == down || info.table.downcase == down || underscore(info.name) == down
304
+ end
305
+ return found if found
306
+
307
+ available = models_map.keys.join(", ")
308
+ raise ArgumentError, "Unknown synced model #{key.inspect}. Available models: #{available}"
309
+ end
310
+
311
+ def select_columns(columns, valid_cols)
312
+ return "*" if columns.nil? || Array(columns).empty?
313
+
314
+ Array(columns).map do |col|
315
+ name = col.to_s
316
+ validate_column!(name, valid_cols)
317
+ quote_ident(name)
318
+ end.join(", ")
319
+ end
320
+
321
+ def build_where(where, valid_cols)
322
+ return ["", []] if where.nil? || (where.is_a?(Hash) && where.empty?)
323
+ raise ArgumentError, "where must be an object/hash" unless where.is_a?(Hash)
324
+
325
+ clauses = []
326
+ binds = []
327
+
328
+ where.each do |raw_col, condition|
329
+ col = raw_col.to_s
330
+ validate_column!(col, valid_cols)
331
+ col_sql = quote_ident(col)
332
+
333
+ case condition
334
+ when nil
335
+ clauses << "#{col_sql} IS NULL"
336
+ when Array
337
+ if condition.empty?
338
+ clauses << "1 = 0"
339
+ else
340
+ placeholders = condition.map { "?" }.join(", ")
341
+ clauses << "#{col_sql} IN (#{placeholders})"
342
+ condition.each { |item| binds << bind_value(item) }
343
+ end
344
+ when Hash
345
+ condition.each do |raw_op, value|
346
+ op = raw_op.to_s
347
+ unless OPERATORS.include?(op)
348
+ raise ArgumentError, "Unsupported filter operator #{op.inspect} for column #{col}. Allowed: #{OPERATORS.join(', ')}"
349
+ end
350
+
351
+ case op
352
+ when "eq"
353
+ if value.nil?
354
+ clauses << "#{col_sql} IS NULL"
355
+ else
356
+ clauses << "#{col_sql} = ?"
357
+ binds << bind_value(value)
358
+ end
359
+ when "ne"
360
+ if value.nil?
361
+ clauses << "#{col_sql} IS NOT NULL"
362
+ else
363
+ clauses << "#{col_sql} != ?"
364
+ binds << bind_value(value)
365
+ end
366
+ when "gt"
367
+ clauses << "#{col_sql} > ?"
368
+ binds << bind_value(value)
369
+ when "gte"
370
+ clauses << "#{col_sql} >= ?"
371
+ binds << bind_value(value)
372
+ when "lt"
373
+ clauses << "#{col_sql} < ?"
374
+ binds << bind_value(value)
375
+ when "lte"
376
+ clauses << "#{col_sql} <= ?"
377
+ binds << bind_value(value)
378
+ when "like"
379
+ clauses << "LOWER(CAST(#{col_sql} AS TEXT)) LIKE ? ESCAPE '\\'"
380
+ binds << "%#{escape_like(value.to_s.downcase)}%"
381
+ when "in"
382
+ list = Array(value)
383
+ if list.empty?
384
+ clauses << "1 = 0"
385
+ else
386
+ clauses << "#{col_sql} IN (#{list.map { '?' }.join(', ')})"
387
+ list.each { |item| binds << bind_value(item) }
388
+ end
389
+ when "is_null"
390
+ clauses << (value ? "#{col_sql} IS NULL" : "#{col_sql} IS NOT NULL")
391
+ when "not_null"
392
+ clauses << (value ? "#{col_sql} IS NOT NULL" : "#{col_sql} IS NULL")
393
+ end
394
+ end
395
+ else
396
+ clauses << "#{col_sql} = ?"
397
+ binds << bind_value(condition)
398
+ end
399
+ end
400
+
401
+ return ["", []] if clauses.empty?
402
+
403
+ [" WHERE #{clauses.join(' AND ')}", binds]
404
+ end
405
+
406
+ def build_order(order, valid_cols)
407
+ return "" if order.nil?
408
+
409
+ specs =
410
+ case order
411
+ when String
412
+ order.split(",").map(&:strip).reject(&:empty?)
413
+ when Array
414
+ order.map(&:to_s).map(&:strip).reject(&:empty?)
415
+ when Hash
416
+ order.map { |col, dir| "#{col} #{dir}" }
417
+ else
418
+ raise ArgumentError, "Invalid order specification: #{order.inspect}"
419
+ end
420
+
421
+ return "" if specs.empty?
422
+
423
+ parts = specs.map do |spec|
424
+ col, dir = spec.split(/\s+/, 2)
425
+ validate_column!(col.to_s, valid_cols)
426
+ direction = dir.nil? || dir.empty? ? "ASC" : dir.upcase
427
+ unless direction == "ASC" || direction == "DESC"
428
+ raise ArgumentError, "Invalid sort direction #{dir.inspect}; expected ASC or DESC"
429
+ end
430
+
431
+ "#{quote_ident(col)} #{direction}"
432
+ end
433
+
434
+ " ORDER BY #{parts.join(', ')}"
435
+ end
436
+
437
+ def searchable_columns(info, requested_cols)
438
+ valid_cols = info.columns.map { |c| c[:name] }
439
+ if requested_cols && !requested_cols.empty?
440
+ requested_cols.each { |col| validate_column!(col, valid_cols) }
441
+ return requested_cols
442
+ end
443
+
444
+ text_cols = info.columns.filter_map do |col|
445
+ next if BOOKKEEPING_COLUMNS.include?(col[:name])
446
+
447
+ type = col[:type].upcase
448
+ next if type.include?("BLOB")
449
+
450
+ if type.empty? || type.include?("CHAR") || type.include?("TEXT") || type.include?("CLOB") || type.include?("STRING")
451
+ col[:name]
452
+ end
453
+ end
454
+
455
+ text_cols.empty? ? valid_cols - BOOKKEEPING_COLUMNS : text_cols
456
+ end
457
+
458
+ def validate_column!(name, valid_cols)
459
+ return if valid_cols.include?(name)
460
+
461
+ raise ArgumentError, "Unknown column #{name.inspect}. Available columns: #{valid_cols.join(', ')}"
462
+ end
463
+
464
+ def quote_ident(ident)
465
+ %("#{ident.to_s.gsub('"', '""')}")
466
+ end
467
+
468
+ def escape_like(str)
469
+ str.gsub(/[\\%_]/) { |ch| "\\#{ch}" }
470
+ end
471
+
472
+ def bind_value(value)
473
+ case value
474
+ when true then 1
475
+ when false then 0
476
+ else value
477
+ end
478
+ end
479
+
480
+ def normalize_row(row)
481
+ row.each_with_object({}) do |(key, value), acc|
482
+ next if key.is_a?(Integer)
483
+
484
+ acc[key.to_s] = value
485
+ end
486
+ end
487
+
488
+ def stringify_hash(hash)
489
+ hash.transform_keys(&:to_s)
490
+ end
491
+
492
+ def clamp_limit(limit)
493
+ value = limit.nil? ? DEFAULT_LIMIT : limit.to_i
494
+ value = DEFAULT_LIMIT if value <= 0
495
+ [value, MAX_LIMIT].min
496
+ end
497
+
498
+ def normalize_model_list(models)
499
+ return nil if models.nil?
500
+
501
+ Array(models).map(&:to_s).map(&:strip).reject(&:empty?)
502
+ end
503
+
504
+ def match_table_for_model(model_name, tables)
505
+ candidate = tableize(model_name)
506
+ return candidate if tables.include?(candidate)
507
+
508
+ short = tableize(model_name.split("::").last)
509
+ return short if tables.include?(short)
510
+
511
+ tables.find { |t| t.downcase == candidate.downcase || t.downcase == short.downcase }
512
+ end
513
+
514
+ def tableize(model_name)
515
+ if defined?(ActiveSupport::Inflector)
516
+ ActiveSupport::Inflector.tableize(model_name)
517
+ else
518
+ pluralize(underscore(model_name.tr("::", "_")))
519
+ end
520
+ end
521
+
522
+ def classify_table(table)
523
+ if defined?(ActiveSupport::Inflector)
524
+ ActiveSupport::Inflector.classify(table)
525
+ else
526
+ singular = table.sub(/ies\z/, "y").sub(/(?:es|s)\z/, "")
527
+ singular.split("_").map(&:capitalize).join
528
+ end
529
+ end
530
+
531
+ def underscore(name)
532
+ name.to_s
533
+ .gsub("::", "/")
534
+ .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
535
+ .gsub(/([a-z\d])([A-Z])/, '\1_\2')
536
+ .tr("-", "_")
537
+ .downcase
538
+ end
539
+
540
+ def pluralize(word)
541
+ return "#{word[0..-2]}ies" if word.end_with?("y") && !word.end_with?("ay", "ey", "iy", "oy", "uy")
542
+ return "#{word}es" if word.end_with?("s", "x", "z", "ch", "sh")
543
+
544
+ "#{word}s"
545
+ end
546
+
547
+ def monotonic_now
548
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
549
+ end
550
+
551
+ def elapsed_ms(started)
552
+ ((monotonic_now - started) * 1000.0).round(3)
553
+ end
554
+ end
555
+ end
556
+ end