relq 1.0.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 (305) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +862 -0
  3. package/dist/addons/buffer.js +1869 -0
  4. package/dist/addons/pg-cursor.js +1425 -0
  5. package/dist/addons/pg-format.js +2248 -0
  6. package/dist/addons/pg.js +4790 -0
  7. package/dist/bin/relq.js +2 -0
  8. package/dist/cjs/cache/index.cjs +9 -0
  9. package/dist/cjs/cache/query-cache.cjs +311 -0
  10. package/dist/cjs/cli/commands/add.cjs +82 -0
  11. package/dist/cjs/cli/commands/commit.cjs +145 -0
  12. package/dist/cjs/cli/commands/diff.cjs +84 -0
  13. package/dist/cjs/cli/commands/export.cjs +333 -0
  14. package/dist/cjs/cli/commands/fetch.cjs +59 -0
  15. package/dist/cjs/cli/commands/generate.cjs +242 -0
  16. package/dist/cjs/cli/commands/history.cjs +165 -0
  17. package/dist/cjs/cli/commands/import.cjs +524 -0
  18. package/dist/cjs/cli/commands/init.cjs +437 -0
  19. package/dist/cjs/cli/commands/introspect.cjs +142 -0
  20. package/dist/cjs/cli/commands/log.cjs +62 -0
  21. package/dist/cjs/cli/commands/migrate.cjs +167 -0
  22. package/dist/cjs/cli/commands/pull.cjs +410 -0
  23. package/dist/cjs/cli/commands/push.cjs +165 -0
  24. package/dist/cjs/cli/commands/rollback.cjs +169 -0
  25. package/dist/cjs/cli/commands/status.cjs +110 -0
  26. package/dist/cjs/cli/commands/sync.cjs +79 -0
  27. package/dist/cjs/cli/index.cjs +275 -0
  28. package/dist/cjs/cli/utils/change-tracker.cjs +446 -0
  29. package/dist/cjs/cli/utils/commit-manager.cjs +239 -0
  30. package/dist/cjs/cli/utils/config-loader.cjs +127 -0
  31. package/dist/cjs/cli/utils/env-loader.cjs +62 -0
  32. package/dist/cjs/cli/utils/fast-introspect.cjs +398 -0
  33. package/dist/cjs/cli/utils/git-utils.cjs +404 -0
  34. package/dist/cjs/cli/utils/migration-generator.cjs +269 -0
  35. package/dist/cjs/cli/utils/relqignore.cjs +114 -0
  36. package/dist/cjs/cli/utils/repo-manager.cjs +515 -0
  37. package/dist/cjs/cli/utils/schema-comparator.cjs +313 -0
  38. package/dist/cjs/cli/utils/schema-diff.cjs +284 -0
  39. package/dist/cjs/cli/utils/schema-hash.cjs +108 -0
  40. package/dist/cjs/cli/utils/schema-introspect.cjs +455 -0
  41. package/dist/cjs/cli/utils/snapshot-manager.cjs +223 -0
  42. package/dist/cjs/cli/utils/spinner.cjs +108 -0
  43. package/dist/cjs/cli/utils/sql-generator.cjs +520 -0
  44. package/dist/cjs/cli/utils/sql-parser.cjs +999 -0
  45. package/dist/cjs/cli/utils/type-generator.cjs +2061 -0
  46. package/dist/cjs/condition/array-condition-builder.cjs +503 -0
  47. package/dist/cjs/condition/array-numeric-condition-builder.cjs +186 -0
  48. package/dist/cjs/condition/array-specialized-condition-builder.cjs +206 -0
  49. package/dist/cjs/condition/array-string-condition-builder.cjs +146 -0
  50. package/dist/cjs/condition/base-condition-builder.cjs +2 -0
  51. package/dist/cjs/condition/condition-collector.cjs +284 -0
  52. package/dist/cjs/condition/fulltext-condition-builder.cjs +61 -0
  53. package/dist/cjs/condition/geometric-condition-builder.cjs +208 -0
  54. package/dist/cjs/condition/index.cjs +25 -0
  55. package/dist/cjs/condition/jsonb-condition-builder.cjs +160 -0
  56. package/dist/cjs/condition/network-condition-builder.cjs +230 -0
  57. package/dist/cjs/condition/range-condition-builder.cjs +82 -0
  58. package/dist/cjs/config/config.cjs +190 -0
  59. package/dist/cjs/config/index.cjs +9 -0
  60. package/dist/cjs/constants/pg-values.cjs +68 -0
  61. package/dist/cjs/copy/copy-builder.cjs +316 -0
  62. package/dist/cjs/copy/index.cjs +6 -0
  63. package/dist/cjs/core/query-builder.cjs +440 -0
  64. package/dist/cjs/core/relq-client.cjs +1831 -0
  65. package/dist/cjs/core/typed-kuery-client.cjs +2 -0
  66. package/dist/cjs/count/count-builder.cjs +88 -0
  67. package/dist/cjs/count/index.cjs +5 -0
  68. package/dist/cjs/cte/cte-builder.cjs +89 -0
  69. package/dist/cjs/cte/index.cjs +5 -0
  70. package/dist/cjs/ddl/function.cjs +48 -0
  71. package/dist/cjs/ddl/index.cjs +7 -0
  72. package/dist/cjs/ddl/sql.cjs +54 -0
  73. package/dist/cjs/delete/delete-builder.cjs +135 -0
  74. package/dist/cjs/delete/index.cjs +5 -0
  75. package/dist/cjs/errors/relq-errors.cjs +329 -0
  76. package/dist/cjs/examples/fulltext-search-test.cjs +122 -0
  77. package/dist/cjs/explain/explain-builder.cjs +99 -0
  78. package/dist/cjs/explain/index.cjs +5 -0
  79. package/dist/cjs/function/create-function-builder.cjs +196 -0
  80. package/dist/cjs/function/index.cjs +6 -0
  81. package/dist/cjs/functions/advanced-functions.cjs +241 -0
  82. package/dist/cjs/functions/case-builder.cjs +66 -0
  83. package/dist/cjs/functions/geometric-functions.cjs +104 -0
  84. package/dist/cjs/functions/index.cjs +184 -0
  85. package/dist/cjs/functions/network-functions.cjs +86 -0
  86. package/dist/cjs/functions/sql-functions.cjs +431 -0
  87. package/dist/cjs/index.cjs +164 -0
  88. package/dist/cjs/indexing/create-index-builder.cjs +187 -0
  89. package/dist/cjs/indexing/drop-index-builder.cjs +89 -0
  90. package/dist/cjs/indexing/index-types.cjs +2 -0
  91. package/dist/cjs/indexing/index.cjs +8 -0
  92. package/dist/cjs/insert/conflict-builder.cjs +173 -0
  93. package/dist/cjs/insert/index.cjs +5 -0
  94. package/dist/cjs/insert/insert-builder.cjs +254 -0
  95. package/dist/cjs/introspect/index.cjs +229 -0
  96. package/dist/cjs/maintenance/index.cjs +6 -0
  97. package/dist/cjs/maintenance/vacuum-builder.cjs +166 -0
  98. package/dist/cjs/pubsub/index.cjs +7 -0
  99. package/dist/cjs/pubsub/listen-notify-builder.cjs +57 -0
  100. package/dist/cjs/pubsub/listener-connection.cjs +180 -0
  101. package/dist/cjs/raw/index.cjs +5 -0
  102. package/dist/cjs/raw/raw-query-builder.cjs +27 -0
  103. package/dist/cjs/schema/index.cjs +15 -0
  104. package/dist/cjs/schema/schema-builder.cjs +1167 -0
  105. package/dist/cjs/schema-builder.cjs +21 -0
  106. package/dist/cjs/schema-definition/column-types.cjs +829 -0
  107. package/dist/cjs/schema-definition/index.cjs +62 -0
  108. package/dist/cjs/schema-definition/introspection.cjs +620 -0
  109. package/dist/cjs/schema-definition/partitions.cjs +129 -0
  110. package/dist/cjs/schema-definition/pg-enum.cjs +76 -0
  111. package/dist/cjs/schema-definition/pg-function.cjs +91 -0
  112. package/dist/cjs/schema-definition/pg-sequence.cjs +56 -0
  113. package/dist/cjs/schema-definition/pg-trigger.cjs +108 -0
  114. package/dist/cjs/schema-definition/relations.cjs +98 -0
  115. package/dist/cjs/schema-definition/sql-expressions.cjs +202 -0
  116. package/dist/cjs/schema-definition/table-definition.cjs +636 -0
  117. package/dist/cjs/select/aggregate-builder.cjs +179 -0
  118. package/dist/cjs/select/index.cjs +5 -0
  119. package/dist/cjs/select/select-builder.cjs +233 -0
  120. package/dist/cjs/sequence/index.cjs +7 -0
  121. package/dist/cjs/sequence/sequence-builder.cjs +264 -0
  122. package/dist/cjs/table/alter-table-builder.cjs +146 -0
  123. package/dist/cjs/table/constraint-builder.cjs +102 -0
  124. package/dist/cjs/table/create-table-builder.cjs +248 -0
  125. package/dist/cjs/table/index.cjs +17 -0
  126. package/dist/cjs/table/partition-builder.cjs +131 -0
  127. package/dist/cjs/table/truncate-builder.cjs +70 -0
  128. package/dist/cjs/transaction/index.cjs +6 -0
  129. package/dist/cjs/transaction/transaction-builder.cjs +78 -0
  130. package/dist/cjs/trigger/create-trigger-builder.cjs +174 -0
  131. package/dist/cjs/trigger/index.cjs +6 -0
  132. package/dist/cjs/types/aggregate-types.cjs +2 -0
  133. package/dist/cjs/types/config-types.cjs +40 -0
  134. package/dist/cjs/types/inference-types.cjs +18 -0
  135. package/dist/cjs/types/pagination-types.cjs +7 -0
  136. package/dist/cjs/types/result-types.cjs +2 -0
  137. package/dist/cjs/types/schema-types.cjs +2 -0
  138. package/dist/cjs/types/subscription-types.cjs +2 -0
  139. package/dist/cjs/types.cjs +2 -0
  140. package/dist/cjs/update/array-update-builder.cjs +205 -0
  141. package/dist/cjs/update/index.cjs +13 -0
  142. package/dist/cjs/update/update-builder.cjs +195 -0
  143. package/dist/cjs/utils/case-converter.cjs +58 -0
  144. package/dist/cjs/utils/environment-detection.cjs +120 -0
  145. package/dist/cjs/utils/index.cjs +10 -0
  146. package/dist/cjs/utils/pool-defaults.cjs +106 -0
  147. package/dist/cjs/utils/type-coercion.cjs +118 -0
  148. package/dist/cjs/view/create-view-builder.cjs +180 -0
  149. package/dist/cjs/view/index.cjs +7 -0
  150. package/dist/cjs/window/index.cjs +5 -0
  151. package/dist/cjs/window/window-builder.cjs +80 -0
  152. package/dist/config.cjs +1 -0
  153. package/dist/config.d.ts +655 -0
  154. package/dist/config.js +1 -0
  155. package/dist/esm/cache/index.js +1 -0
  156. package/dist/esm/cache/query-cache.js +303 -0
  157. package/dist/esm/cli/commands/add.js +78 -0
  158. package/dist/esm/cli/commands/commit.js +109 -0
  159. package/dist/esm/cli/commands/diff.js +81 -0
  160. package/dist/esm/cli/commands/export.js +297 -0
  161. package/dist/esm/cli/commands/fetch.js +56 -0
  162. package/dist/esm/cli/commands/generate.js +206 -0
  163. package/dist/esm/cli/commands/history.js +129 -0
  164. package/dist/esm/cli/commands/import.js +488 -0
  165. package/dist/esm/cli/commands/init.js +401 -0
  166. package/dist/esm/cli/commands/introspect.js +106 -0
  167. package/dist/esm/cli/commands/log.js +59 -0
  168. package/dist/esm/cli/commands/migrate.js +131 -0
  169. package/dist/esm/cli/commands/pull.js +374 -0
  170. package/dist/esm/cli/commands/push.js +129 -0
  171. package/dist/esm/cli/commands/rollback.js +133 -0
  172. package/dist/esm/cli/commands/status.js +107 -0
  173. package/dist/esm/cli/commands/sync.js +76 -0
  174. package/dist/esm/cli/index.js +240 -0
  175. package/dist/esm/cli/utils/change-tracker.js +405 -0
  176. package/dist/esm/cli/utils/commit-manager.js +191 -0
  177. package/dist/esm/cli/utils/config-loader.js +86 -0
  178. package/dist/esm/cli/utils/env-loader.js +57 -0
  179. package/dist/esm/cli/utils/fast-introspect.js +362 -0
  180. package/dist/esm/cli/utils/git-utils.js +347 -0
  181. package/dist/esm/cli/utils/migration-generator.js +263 -0
  182. package/dist/esm/cli/utils/relqignore.js +74 -0
  183. package/dist/esm/cli/utils/repo-manager.js +444 -0
  184. package/dist/esm/cli/utils/schema-comparator.js +307 -0
  185. package/dist/esm/cli/utils/schema-diff.js +276 -0
  186. package/dist/esm/cli/utils/schema-hash.js +69 -0
  187. package/dist/esm/cli/utils/schema-introspect.js +418 -0
  188. package/dist/esm/cli/utils/snapshot-manager.js +179 -0
  189. package/dist/esm/cli/utils/spinner.js +101 -0
  190. package/dist/esm/cli/utils/sql-generator.js +504 -0
  191. package/dist/esm/cli/utils/sql-parser.js +992 -0
  192. package/dist/esm/cli/utils/type-generator.js +2058 -0
  193. package/dist/esm/condition/array-condition-builder.js +495 -0
  194. package/dist/esm/condition/array-numeric-condition-builder.js +182 -0
  195. package/dist/esm/condition/array-specialized-condition-builder.js +200 -0
  196. package/dist/esm/condition/array-string-condition-builder.js +142 -0
  197. package/dist/esm/condition/base-condition-builder.js +1 -0
  198. package/dist/esm/condition/condition-collector.js +275 -0
  199. package/dist/esm/condition/fulltext-condition-builder.js +53 -0
  200. package/dist/esm/condition/geometric-condition-builder.js +200 -0
  201. package/dist/esm/condition/index.js +7 -0
  202. package/dist/esm/condition/jsonb-condition-builder.js +152 -0
  203. package/dist/esm/condition/network-condition-builder.js +222 -0
  204. package/dist/esm/condition/range-condition-builder.js +74 -0
  205. package/dist/esm/config/config.js +150 -0
  206. package/dist/esm/config/index.js +1 -0
  207. package/dist/esm/constants/pg-values.js +63 -0
  208. package/dist/esm/copy/copy-builder.js +308 -0
  209. package/dist/esm/copy/index.js +1 -0
  210. package/dist/esm/core/query-builder.js +426 -0
  211. package/dist/esm/core/relq-client.js +1791 -0
  212. package/dist/esm/core/typed-kuery-client.js +1 -0
  213. package/dist/esm/count/count-builder.js +81 -0
  214. package/dist/esm/count/index.js +1 -0
  215. package/dist/esm/cte/cte-builder.js +82 -0
  216. package/dist/esm/cte/index.js +1 -0
  217. package/dist/esm/ddl/function.js +45 -0
  218. package/dist/esm/ddl/index.js +2 -0
  219. package/dist/esm/ddl/sql.js +51 -0
  220. package/dist/esm/delete/delete-builder.js +128 -0
  221. package/dist/esm/delete/index.js +1 -0
  222. package/dist/esm/errors/relq-errors.js +310 -0
  223. package/dist/esm/examples/fulltext-search-test.js +117 -0
  224. package/dist/esm/explain/explain-builder.js +95 -0
  225. package/dist/esm/explain/index.js +1 -0
  226. package/dist/esm/function/create-function-builder.js +188 -0
  227. package/dist/esm/function/index.js +1 -0
  228. package/dist/esm/functions/advanced-functions.js +231 -0
  229. package/dist/esm/functions/case-builder.js +58 -0
  230. package/dist/esm/functions/geometric-functions.js +97 -0
  231. package/dist/esm/functions/index.js +171 -0
  232. package/dist/esm/functions/network-functions.js +79 -0
  233. package/dist/esm/functions/sql-functions.js +421 -0
  234. package/dist/esm/index.js +34 -0
  235. package/dist/esm/indexing/create-index-builder.js +180 -0
  236. package/dist/esm/indexing/drop-index-builder.js +81 -0
  237. package/dist/esm/indexing/index-types.js +1 -0
  238. package/dist/esm/indexing/index.js +2 -0
  239. package/dist/esm/insert/conflict-builder.js +162 -0
  240. package/dist/esm/insert/index.js +1 -0
  241. package/dist/esm/insert/insert-builder.js +247 -0
  242. package/dist/esm/introspect/index.js +224 -0
  243. package/dist/esm/maintenance/index.js +1 -0
  244. package/dist/esm/maintenance/vacuum-builder.js +158 -0
  245. package/dist/esm/pubsub/index.js +1 -0
  246. package/dist/esm/pubsub/listen-notify-builder.js +48 -0
  247. package/dist/esm/pubsub/listener-connection.js +173 -0
  248. package/dist/esm/raw/index.js +1 -0
  249. package/dist/esm/raw/raw-query-builder.js +20 -0
  250. package/dist/esm/schema/index.js +1 -0
  251. package/dist/esm/schema/schema-builder.js +1150 -0
  252. package/dist/esm/schema-builder.js +2 -0
  253. package/dist/esm/schema-definition/column-types.js +738 -0
  254. package/dist/esm/schema-definition/index.js +10 -0
  255. package/dist/esm/schema-definition/introspection.js +614 -0
  256. package/dist/esm/schema-definition/partitions.js +123 -0
  257. package/dist/esm/schema-definition/pg-enum.js +70 -0
  258. package/dist/esm/schema-definition/pg-function.js +85 -0
  259. package/dist/esm/schema-definition/pg-sequence.js +50 -0
  260. package/dist/esm/schema-definition/pg-trigger.js +102 -0
  261. package/dist/esm/schema-definition/relations.js +90 -0
  262. package/dist/esm/schema-definition/sql-expressions.js +193 -0
  263. package/dist/esm/schema-definition/table-definition.js +630 -0
  264. package/dist/esm/select/aggregate-builder.js +172 -0
  265. package/dist/esm/select/index.js +1 -0
  266. package/dist/esm/select/select-builder.js +226 -0
  267. package/dist/esm/sequence/index.js +1 -0
  268. package/dist/esm/sequence/sequence-builder.js +255 -0
  269. package/dist/esm/table/alter-table-builder.js +138 -0
  270. package/dist/esm/table/constraint-builder.js +95 -0
  271. package/dist/esm/table/create-table-builder.js +241 -0
  272. package/dist/esm/table/index.js +5 -0
  273. package/dist/esm/table/partition-builder.js +121 -0
  274. package/dist/esm/table/truncate-builder.js +63 -0
  275. package/dist/esm/transaction/index.js +1 -0
  276. package/dist/esm/transaction/transaction-builder.js +70 -0
  277. package/dist/esm/trigger/create-trigger-builder.js +166 -0
  278. package/dist/esm/trigger/index.js +1 -0
  279. package/dist/esm/types/aggregate-types.js +1 -0
  280. package/dist/esm/types/config-types.js +36 -0
  281. package/dist/esm/types/inference-types.js +12 -0
  282. package/dist/esm/types/pagination-types.js +4 -0
  283. package/dist/esm/types/result-types.js +1 -0
  284. package/dist/esm/types/schema-types.js +1 -0
  285. package/dist/esm/types/subscription-types.js +1 -0
  286. package/dist/esm/types.js +1 -0
  287. package/dist/esm/update/array-update-builder.js +192 -0
  288. package/dist/esm/update/index.js +2 -0
  289. package/dist/esm/update/update-builder.js +188 -0
  290. package/dist/esm/utils/case-converter.js +55 -0
  291. package/dist/esm/utils/environment-detection.js +113 -0
  292. package/dist/esm/utils/index.js +2 -0
  293. package/dist/esm/utils/pool-defaults.js +100 -0
  294. package/dist/esm/utils/type-coercion.js +110 -0
  295. package/dist/esm/view/create-view-builder.js +171 -0
  296. package/dist/esm/view/index.js +1 -0
  297. package/dist/esm/window/index.js +1 -0
  298. package/dist/esm/window/window-builder.js +73 -0
  299. package/dist/index.cjs +1 -0
  300. package/dist/index.d.ts +10341 -0
  301. package/dist/index.js +1 -0
  302. package/dist/schema-builder.cjs +1 -0
  303. package/dist/schema-builder.d.ts +2272 -0
  304. package/dist/schema-builder.js +1 -0
  305. package/package.json +55 -0
@@ -0,0 +1,303 @@
1
+ export class QueryCache {
2
+ cache = new Map();
3
+ options;
4
+ stats = { hits: 0, misses: 0, evictions: 0 };
5
+ constructor(options = {}) {
6
+ this.options = {
7
+ strategy: options.strategy ?? 'lru',
8
+ maxSize: options.maxSize ?? 100 * 1024 * 1024,
9
+ maxItems: options.maxItems ?? 1000,
10
+ ttl: options.ttl ?? 60000,
11
+ onEvict: options.onEvict ?? (() => { }),
12
+ keyGenerator: options.keyGenerator ?? this.defaultKeyGenerator
13
+ };
14
+ }
15
+ defaultKeyGenerator(query, params) {
16
+ const normalized = query.replace(/\s+/g, ' ').trim().toLowerCase();
17
+ const paramStr = params ? JSON.stringify(params) : '';
18
+ return `${normalized}::${paramStr}`;
19
+ }
20
+ generateKey(query, params) {
21
+ return this.options.keyGenerator(query, params);
22
+ }
23
+ get(key) {
24
+ const entry = this.cache.get(key);
25
+ if (!entry) {
26
+ this.stats.misses++;
27
+ return undefined;
28
+ }
29
+ if (this.options.strategy === 'ttl' || this.options.strategy === 'lru') {
30
+ const now = Date.now();
31
+ if (this.options.ttl > 0 && now - entry.createdAt > this.options.ttl) {
32
+ this.delete(key);
33
+ this.stats.misses++;
34
+ return undefined;
35
+ }
36
+ }
37
+ entry.accessedAt = Date.now();
38
+ entry.accessCount++;
39
+ this.stats.hits++;
40
+ if (this.options.strategy === 'lru') {
41
+ this.cache.delete(key);
42
+ this.cache.set(key, entry);
43
+ }
44
+ return entry.value;
45
+ }
46
+ set(key, value) {
47
+ const size = this.estimateSize(value);
48
+ this.evictIfNeeded(size);
49
+ const entry = {
50
+ value,
51
+ createdAt: Date.now(),
52
+ accessedAt: Date.now(),
53
+ accessCount: 1,
54
+ size
55
+ };
56
+ this.cache.set(key, entry);
57
+ }
58
+ has(key) {
59
+ const entry = this.cache.get(key);
60
+ if (!entry)
61
+ return false;
62
+ if (this.options.strategy === 'ttl' || this.options.strategy === 'lru') {
63
+ const now = Date.now();
64
+ if (this.options.ttl > 0 && now - entry.createdAt > this.options.ttl) {
65
+ this.delete(key);
66
+ return false;
67
+ }
68
+ }
69
+ return true;
70
+ }
71
+ delete(key) {
72
+ const entry = this.cache.get(key);
73
+ if (entry) {
74
+ this.options.onEvict(key, entry);
75
+ this.stats.evictions++;
76
+ return this.cache.delete(key);
77
+ }
78
+ return false;
79
+ }
80
+ clear() {
81
+ this.cache.forEach((entry, key) => {
82
+ this.options.onEvict(key, entry);
83
+ });
84
+ this.cache.clear();
85
+ this.stats.evictions = 0;
86
+ }
87
+ invalidateByPattern(pattern) {
88
+ let count = 0;
89
+ const keysToDelete = [];
90
+ this.cache.forEach((_, key) => {
91
+ if (pattern.test(key)) {
92
+ keysToDelete.push(key);
93
+ }
94
+ });
95
+ keysToDelete.forEach(key => {
96
+ this.delete(key);
97
+ count++;
98
+ });
99
+ return count;
100
+ }
101
+ invalidateByTable(tableName) {
102
+ const pattern = new RegExp(`\\b${tableName.toLowerCase()}\\b`, 'i');
103
+ return this.invalidateByPattern(pattern);
104
+ }
105
+ getStats() {
106
+ const totalSize = Array.from(this.cache.values()).reduce((sum, e) => sum + e.size, 0);
107
+ const total = this.stats.hits + this.stats.misses;
108
+ return {
109
+ hits: this.stats.hits,
110
+ misses: this.stats.misses,
111
+ evictions: this.stats.evictions,
112
+ size: totalSize,
113
+ itemCount: this.cache.size,
114
+ hitRate: total > 0 ? this.stats.hits / total : 0
115
+ };
116
+ }
117
+ resetStats() {
118
+ this.stats = { hits: 0, misses: 0, evictions: 0 };
119
+ }
120
+ keys() {
121
+ return Array.from(this.cache.keys());
122
+ }
123
+ values() {
124
+ return Array.from(this.cache.values()).map(e => e.value);
125
+ }
126
+ entries() {
127
+ return Array.from(this.cache.entries());
128
+ }
129
+ evictIfNeeded(incomingSize) {
130
+ if (this.options.strategy === 'none')
131
+ return;
132
+ while (this.cache.size >= this.options.maxItems) {
133
+ this.evictOne();
134
+ }
135
+ if (this.options.strategy === 'size') {
136
+ const currentSize = Array.from(this.cache.values()).reduce((sum, e) => sum + e.size, 0);
137
+ while (currentSize + incomingSize > this.options.maxSize && this.cache.size > 0) {
138
+ this.evictOne();
139
+ }
140
+ }
141
+ }
142
+ evictOne() {
143
+ if (this.cache.size === 0)
144
+ return;
145
+ let keyToEvict;
146
+ let entryToEvict;
147
+ switch (this.options.strategy) {
148
+ case 'lru':
149
+ keyToEvict = this.cache.keys().next().value;
150
+ break;
151
+ case 'ttl':
152
+ let oldestTime = Infinity;
153
+ this.cache.forEach((entry, key) => {
154
+ if (entry.createdAt < oldestTime) {
155
+ oldestTime = entry.createdAt;
156
+ keyToEvict = key;
157
+ entryToEvict = entry;
158
+ }
159
+ });
160
+ break;
161
+ case 'size':
162
+ let largestSize = -1;
163
+ this.cache.forEach((entry, key) => {
164
+ if (entry.size > largestSize) {
165
+ largestSize = entry.size;
166
+ keyToEvict = key;
167
+ entryToEvict = entry;
168
+ }
169
+ });
170
+ break;
171
+ default:
172
+ keyToEvict = this.cache.keys().next().value;
173
+ }
174
+ if (keyToEvict) {
175
+ this.delete(keyToEvict);
176
+ }
177
+ }
178
+ estimateSize(value) {
179
+ if (value === null || value === undefined)
180
+ return 8;
181
+ if (typeof value === 'boolean')
182
+ return 4;
183
+ if (typeof value === 'number')
184
+ return 8;
185
+ if (typeof value === 'string')
186
+ return value.length * 2;
187
+ if (Array.isArray(value)) {
188
+ return value.reduce((sum, item) => sum + this.estimateSize(item), 16);
189
+ }
190
+ if (typeof value === 'object') {
191
+ return JSON.stringify(value).length * 2;
192
+ }
193
+ return 64;
194
+ }
195
+ }
196
+ export class CacheKeyBuilder {
197
+ parts = [];
198
+ table(name) {
199
+ this.parts.push(`t:${name}`);
200
+ return this;
201
+ }
202
+ operation(op) {
203
+ this.parts.push(`o:${op}`);
204
+ return this;
205
+ }
206
+ columns(...cols) {
207
+ if (cols.length > 0) {
208
+ this.parts.push(`c:${cols.sort().join(',')}`);
209
+ }
210
+ return this;
211
+ }
212
+ where(condition) {
213
+ this.parts.push(`w:${condition}`);
214
+ return this;
215
+ }
216
+ orderBy(order) {
217
+ this.parts.push(`ob:${order}`);
218
+ return this;
219
+ }
220
+ limit(n) {
221
+ this.parts.push(`l:${n}`);
222
+ return this;
223
+ }
224
+ offset(n) {
225
+ this.parts.push(`of:${n}`);
226
+ return this;
227
+ }
228
+ params(...values) {
229
+ if (values.length > 0) {
230
+ this.parts.push(`p:${JSON.stringify(values)}`);
231
+ }
232
+ return this;
233
+ }
234
+ custom(key, value) {
235
+ this.parts.push(`${key}:${value}`);
236
+ return this;
237
+ }
238
+ build() {
239
+ return this.parts.join('|');
240
+ }
241
+ static from(query, params) {
242
+ const normalized = query.replace(/\s+/g, ' ').trim();
243
+ const hash = this.simpleHash(normalized + (params ? JSON.stringify(params) : ''));
244
+ return `q:${hash}`;
245
+ }
246
+ static simpleHash(str) {
247
+ let hash = 0;
248
+ for (let i = 0; i < str.length; i++) {
249
+ const char = str.charCodeAt(i);
250
+ hash = ((hash << 5) - hash) + char;
251
+ hash = hash & hash;
252
+ }
253
+ return Math.abs(hash).toString(36);
254
+ }
255
+ }
256
+ export function createQueryCacheMiddleware(options) {
257
+ const { cache, keyPrefix = '', invalidateOn = [] } = options;
258
+ return {
259
+ beforeQuery: (query, params) => {
260
+ const key = keyPrefix + CacheKeyBuilder.from(query, params);
261
+ const cached = cache.get(key);
262
+ if (cached !== undefined) {
263
+ return { cached: true, value: cached, key };
264
+ }
265
+ return { cached: false, key };
266
+ },
267
+ afterQuery: (key, result) => {
268
+ cache.set(key, result);
269
+ },
270
+ afterMutation: (tableName) => {
271
+ cache.invalidateByTable(tableName);
272
+ invalidateOn.forEach(pattern => {
273
+ if (pattern.includes(tableName)) {
274
+ cache.invalidateByPattern(new RegExp(pattern, 'i'));
275
+ }
276
+ });
277
+ }
278
+ };
279
+ }
280
+ export function withCache(cache, key, fn, ttl) {
281
+ const cached = cache.get(key);
282
+ if (cached !== undefined) {
283
+ return cached;
284
+ }
285
+ const result = fn();
286
+ if (result instanceof Promise) {
287
+ return result.then(value => {
288
+ cache.set(key, value);
289
+ return value;
290
+ });
291
+ }
292
+ cache.set(key, result);
293
+ return result;
294
+ }
295
+ export function createTableCache(tableName, options = {}) {
296
+ const cache = new QueryCache({
297
+ ...options,
298
+ keyGenerator: (query, params) => {
299
+ return `${tableName}::${query.replace(/\s+/g, ' ').trim()}::${params ? JSON.stringify(params) : ''}`;
300
+ }
301
+ });
302
+ return Object.assign(cache, { table: tableName });
303
+ }
@@ -0,0 +1,78 @@
1
+ import { colors } from "../utils/spinner.js";
2
+ import { isInitialized, getUnstagedChanges, getStagedChanges, stageChanges, } from "../utils/repo-manager.js";
3
+ import { getChangeDisplayName } from "../utils/change-tracker.js";
4
+ export async function addCommand(context) {
5
+ const { args } = context;
6
+ const projectRoot = process.cwd();
7
+ console.log('');
8
+ if (!isInitialized(projectRoot)) {
9
+ console.log(`${colors.red('error:')} relq not initialized`);
10
+ console.log('');
11
+ console.log(`${colors.muted('Run')} ${colors.cyan('relq init')} ${colors.muted('first.')}`);
12
+ return;
13
+ }
14
+ const unstaged = getUnstagedChanges(projectRoot);
15
+ const staged = getStagedChanges(projectRoot);
16
+ if (unstaged.length === 0) {
17
+ if (staged.length > 0) {
18
+ console.log(`${colors.green('✓')} All changes are already staged`);
19
+ console.log(`${colors.muted(`${staged.length} change(s) ready to commit`)}`);
20
+ console.log('');
21
+ console.log(`${colors.muted('Run')} ${colors.cyan('relq commit -m "message"')} ${colors.muted('to commit.')}`);
22
+ }
23
+ else {
24
+ console.log(`${colors.green('✓')} No changes to stage`);
25
+ console.log(`${colors.muted('Run')} ${colors.cyan('relq pull')} ${colors.muted('or')} ${colors.cyan('relq import')} ${colors.muted('to detect changes.')}`);
26
+ }
27
+ console.log('');
28
+ return;
29
+ }
30
+ const patterns = args.length > 0 ? args : ['.'];
31
+ const addAll = patterns.includes('.') || patterns.includes('*');
32
+ console.log(`${colors.cyan('Unstaged changes:')} ${unstaged.length}`);
33
+ console.log('');
34
+ for (const change of unstaged) {
35
+ const display = getChangeDisplayName(change);
36
+ const color = change.type === 'CREATE' ? colors.green :
37
+ change.type === 'DROP' ? colors.red :
38
+ colors.yellow;
39
+ console.log(` ${color(display)}`);
40
+ }
41
+ console.log('');
42
+ const stagedNow = stageChanges(patterns, projectRoot);
43
+ if (stagedNow.length === 0) {
44
+ console.log(`${colors.yellow('⚠')} No changes matched the pattern(s): ${patterns.join(', ')}`);
45
+ console.log('');
46
+ return;
47
+ }
48
+ console.log(`${colors.green('✓')} Staged ${stagedNow.length} change(s):`);
49
+ console.log('');
50
+ for (const change of stagedNow) {
51
+ const display = getChangeDisplayName(change);
52
+ const color = change.type === 'CREATE' ? colors.green :
53
+ change.type === 'DROP' ? colors.red :
54
+ colors.yellow;
55
+ console.log(` ${color(display)}`);
56
+ }
57
+ console.log('');
58
+ const remainingUnstaged = getUnstagedChanges(projectRoot);
59
+ if (remainingUnstaged.length > 0) {
60
+ console.log(`${colors.muted(`${remainingUnstaged.length} change(s) still unstaged`)}`);
61
+ console.log('');
62
+ }
63
+ console.log(`${colors.muted('Run')} ${colors.cyan('relq commit -m "message"')} ${colors.muted('to commit.')}`);
64
+ console.log('');
65
+ }
66
+ export function getRelatedChanges(tableName, changes) {
67
+ return changes.filter(c => {
68
+ if (c.objectName === tableName)
69
+ return true;
70
+ if (c.parentName === tableName)
71
+ return true;
72
+ const data = c.after;
73
+ if (data?.tableName === tableName)
74
+ return true;
75
+ return false;
76
+ });
77
+ }
78
+ export default addCommand;
@@ -0,0 +1,109 @@
1
+ import * as crypto from 'crypto';
2
+ import { colors } from "../utils/spinner.js";
3
+ import { isInitialized, getHead, getStagedChanges, getUnstagedChanges, shortHash, } from "../utils/repo-manager.js";
4
+ import { sortChangesByDependency, generateCombinedSQL, } from "../utils/change-tracker.js";
5
+ import * as fs from 'fs';
6
+ import * as path from 'path';
7
+ export async function commitCommand(context) {
8
+ const { config, flags, args } = context;
9
+ const projectRoot = process.cwd();
10
+ const author = config?.author || 'Developer <dev@example.com>';
11
+ console.log('');
12
+ if (!isInitialized(projectRoot)) {
13
+ console.log(`${colors.red('error:')} relq not initialized`);
14
+ console.log('');
15
+ console.log(`${colors.muted('Run')} ${colors.cyan('relq init')} ${colors.muted('first.')}`);
16
+ return;
17
+ }
18
+ const staged = getStagedChanges(projectRoot);
19
+ if (staged.length === 0) {
20
+ console.log(`${colors.yellow('Nothing to commit')}`);
21
+ console.log('');
22
+ const unstaged = getUnstagedChanges(projectRoot);
23
+ if (unstaged.length > 0) {
24
+ console.log(`${colors.muted(`${unstaged.length} unstaged change(s).`)}`);
25
+ console.log(`${colors.muted('Use')} ${colors.cyan('relq add .')} ${colors.muted('to stage all changes.')}`);
26
+ }
27
+ else {
28
+ console.log(`${colors.muted('Use')} ${colors.cyan('relq add <table>')} ${colors.muted('to stage changes.')}`);
29
+ }
30
+ return;
31
+ }
32
+ let message = flags['m'] || flags['message'];
33
+ if (!message) {
34
+ if (args.length > 0) {
35
+ message = args.join(' ');
36
+ }
37
+ else {
38
+ console.log(`${colors.red('error:')} commit message required`);
39
+ console.log('');
40
+ console.log(`${colors.muted('Usage:')} relq commit -m "message"`);
41
+ return;
42
+ }
43
+ }
44
+ const sortedChanges = sortChangesByDependency(staged);
45
+ const sql = generateCombinedSQL(sortedChanges);
46
+ const creates = staged.filter(c => c.type === 'CREATE').length;
47
+ const alters = staged.filter(c => c.type === 'ALTER').length;
48
+ const drops = staged.filter(c => c.type === 'DROP').length;
49
+ const parentHash = getHead(projectRoot);
50
+ const hashInput = JSON.stringify({
51
+ changes: staged.map(c => c.id),
52
+ message,
53
+ timestamp: new Date().toISOString(),
54
+ parent: parentHash,
55
+ });
56
+ const hash = crypto.createHash('sha1').update(hashInput).digest('hex');
57
+ const commit = {
58
+ hash,
59
+ parentHash,
60
+ author,
61
+ message,
62
+ timestamp: new Date().toISOString(),
63
+ changes: sortedChanges,
64
+ sql,
65
+ snapshotHash: hash.substring(0, 12),
66
+ stats: {
67
+ creates,
68
+ alters,
69
+ drops,
70
+ total: staged.length,
71
+ },
72
+ };
73
+ const commitsDir = path.join(projectRoot, '.relq', 'commits');
74
+ if (!fs.existsSync(commitsDir)) {
75
+ fs.mkdirSync(commitsDir, { recursive: true });
76
+ }
77
+ fs.writeFileSync(path.join(commitsDir, `${hash}.json`), JSON.stringify(commit, null, 2), 'utf-8');
78
+ fs.writeFileSync(path.join(projectRoot, '.relq', 'HEAD'), hash, 'utf-8');
79
+ const workingPath = path.join(projectRoot, '.relq', 'working.json');
80
+ const unstaged = getUnstagedChanges(projectRoot);
81
+ if (unstaged.length > 0) {
82
+ fs.writeFileSync(workingPath, JSON.stringify({
83
+ timestamp: new Date().toISOString(),
84
+ staged: [],
85
+ unstaged,
86
+ }, null, 2), 'utf-8');
87
+ }
88
+ else {
89
+ if (fs.existsSync(workingPath)) {
90
+ fs.unlinkSync(workingPath);
91
+ }
92
+ }
93
+ console.log(`${colors.yellow(`[${shortHash(hash)}]`)} ${message}`);
94
+ console.log('');
95
+ if (creates > 0) {
96
+ console.log(` ${colors.green(`${creates} created`)}`);
97
+ }
98
+ if (alters > 0) {
99
+ console.log(` ${colors.yellow(`${alters} altered`)}`);
100
+ }
101
+ if (drops > 0) {
102
+ console.log(` ${colors.red(`${drops} dropped`)}`);
103
+ }
104
+ console.log('');
105
+ console.log(`${colors.muted('Run')} ${colors.cyan('relq push')} ${colors.muted('to apply changes to database.')}`);
106
+ console.log(`${colors.muted('Run')} ${colors.cyan('relq export')} ${colors.muted('to export as SQL file.')}`);
107
+ console.log('');
108
+ }
109
+ export default commitCommand;
@@ -0,0 +1,81 @@
1
+ import { requireValidConfig } from "../utils/config-loader.js";
2
+ import { introspectDatabase } from "../utils/schema-introspect.js";
3
+ import { loadSnapshot, snapshotToDatabaseSchema } from "../utils/snapshot-manager.js";
4
+ import { formatDiff } from "../utils/schema-diff.js";
5
+ import { normalizeSchema } from "../utils/schema-hash.js";
6
+ import { diffSchemas } from "../utils/schema-diff.js";
7
+ import { generateMigration } from "../utils/migration-generator.js";
8
+ import { getConnectionDescription } from "../utils/env-loader.js";
9
+ const colors = {
10
+ reset: '\x1b[0m',
11
+ bold: '\x1b[1m',
12
+ dim: '\x1b[2m',
13
+ red: '\x1b[31m',
14
+ green: '\x1b[32m',
15
+ yellow: '\x1b[33m',
16
+ blue: '\x1b[34m',
17
+ cyan: '\x1b[36m',
18
+ magenta: '\x1b[35m',
19
+ };
20
+ function filterDiff(diff, ignorePatterns) {
21
+ const patterns = ignorePatterns.map(p => {
22
+ const regexStr = p.replace(/\*/g, '.*').replace(/\?/g, '.');
23
+ return new RegExp(`^${regexStr}$`, 'i');
24
+ });
25
+ const matchesPattern = (name) => patterns.some(p => p.test(name));
26
+ const tables = diff.tables.filter(t => !matchesPattern(t.name));
27
+ const hasChanges = tables.length > 0 || diff.extensions.length > 0;
28
+ return {
29
+ ...diff,
30
+ tables,
31
+ hasChanges,
32
+ };
33
+ }
34
+ export async function diffCommand(context) {
35
+ const { config, flags } = context;
36
+ if (!config) {
37
+ console.error('Error: No configuration found.');
38
+ process.exit(1);
39
+ }
40
+ requireValidConfig(config);
41
+ const connection = config.connection;
42
+ const snapshotPath = config.sync?.snapshot || '.relq/snapshot.json';
43
+ const ignorePatterns = config.sync?.ignore || ['_relq_*'];
44
+ const showSQL = flags['sql'] === true;
45
+ console.log(`${colors.bold}Comparing:${colors.reset} local snapshot ↔ ${getConnectionDescription(connection)}`);
46
+ console.log('');
47
+ try {
48
+ const dbSchema = await introspectDatabase(connection);
49
+ const snapshot = loadSnapshot(snapshotPath);
50
+ if (!snapshot) {
51
+ console.log(`${colors.yellow}No snapshot found.${colors.reset}`);
52
+ console.log(`Run "${colors.cyan}relq pull${colors.reset}" to create initial snapshot.`);
53
+ return;
54
+ }
55
+ const localSchema = snapshotToDatabaseSchema(snapshot);
56
+ const normalizedLocal = normalizeSchema(localSchema);
57
+ const normalizedDb = normalizeSchema(dbSchema);
58
+ const diff = diffSchemas(normalizedLocal, normalizedDb);
59
+ const filteredDiff = filterDiff(diff, ignorePatterns);
60
+ if (!filteredDiff.hasChanges) {
61
+ console.log(`${colors.green}No differences.${colors.reset}`);
62
+ return;
63
+ }
64
+ console.log(formatDiff(filteredDiff));
65
+ if (showSQL) {
66
+ console.log('');
67
+ console.log(`${colors.bold}Generated SQL:${colors.reset}`);
68
+ console.log('');
69
+ const { up } = generateMigration(filteredDiff, { includeDown: false });
70
+ for (const sql of up) {
71
+ console.log(`${colors.cyan}${sql}${colors.reset}`);
72
+ }
73
+ }
74
+ console.log('');
75
+ console.log(`${colors.dim}Use "relq diff --sql" to see generated SQL statements.${colors.reset}`);
76
+ }
77
+ catch (error) {
78
+ console.error('Error:', error instanceof Error ? error.message : error);
79
+ process.exit(1);
80
+ }
81
+ }