@spine-event-engine/storage-mysql 2.0.0-snapshot.13

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 (53) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +243 -0
  3. package/REFERENCE.md +140 -0
  4. package/dist/index.d.ts +3 -0
  5. package/dist/index.d.ts.map +1 -0
  6. package/dist/index.js +15 -0
  7. package/dist/index.js.map +1 -0
  8. package/dist/mysql/column-mapping.d.ts +27 -0
  9. package/dist/mysql/column-mapping.d.ts.map +1 -0
  10. package/dist/mysql/column-mapping.js +94 -0
  11. package/dist/mysql/column-mapping.js.map +1 -0
  12. package/dist/mysql/delivery-cleanup.d.ts +37 -0
  13. package/dist/mysql/delivery-cleanup.d.ts.map +1 -0
  14. package/dist/mysql/delivery-cleanup.js +108 -0
  15. package/dist/mysql/delivery-cleanup.js.map +1 -0
  16. package/dist/mysql/entity-commit.d.ts +79 -0
  17. package/dist/mysql/entity-commit.d.ts.map +1 -0
  18. package/dist/mysql/entity-commit.js +123 -0
  19. package/dist/mysql/entity-commit.js.map +1 -0
  20. package/dist/mysql/entity-history.d.ts +123 -0
  21. package/dist/mysql/entity-history.d.ts.map +1 -0
  22. package/dist/mysql/entity-history.js +347 -0
  23. package/dist/mysql/entity-history.js.map +1 -0
  24. package/dist/mysql/errors.d.ts +25 -0
  25. package/dist/mysql/errors.d.ts.map +1 -0
  26. package/dist/mysql/errors.js +44 -0
  27. package/dist/mysql/errors.js.map +1 -0
  28. package/dist/mysql/id-column.d.ts +36 -0
  29. package/dist/mysql/id-column.d.ts.map +1 -0
  30. package/dist/mysql/id-column.js +113 -0
  31. package/dist/mysql/id-column.js.map +1 -0
  32. package/dist/mysql/record-storage.d.ts +379 -0
  33. package/dist/mysql/record-storage.d.ts.map +1 -0
  34. package/dist/mysql/record-storage.js +941 -0
  35. package/dist/mysql/record-storage.js.map +1 -0
  36. package/dist/mysql/storage-factory.d.ts +218 -0
  37. package/dist/mysql/storage-factory.d.ts.map +1 -0
  38. package/dist/mysql/storage-factory.js +477 -0
  39. package/dist/mysql/storage-factory.js.map +1 -0
  40. package/dist/mysql/table-resolver.d.ts +34 -0
  41. package/dist/mysql/table-resolver.d.ts.map +1 -0
  42. package/dist/mysql/table-resolver.js +87 -0
  43. package/dist/mysql/table-resolver.js.map +1 -0
  44. package/dist/mysql/table-spec.d.ts +88 -0
  45. package/dist/mysql/table-spec.d.ts.map +1 -0
  46. package/dist/mysql/table-spec.js +105 -0
  47. package/dist/mysql/table-spec.js.map +1 -0
  48. package/dist/mysql/testing.d.ts +47 -0
  49. package/dist/mysql/testing.d.ts.map +1 -0
  50. package/dist/mysql/testing.js +111 -0
  51. package/dist/mysql/testing.js.map +1 -0
  52. package/dist/tsconfig.tsbuildinfo +1 -0
  53. package/package.json +38 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,243 @@
1
+ # MySQL storage for Spine TS
2
+
3
+ `@spine-event-engine/storage-mysql` stores Spine TS records in MySQL. It is a
4
+ durable implementation of `@spine-event-engine/storage` and manages the mysql2
5
+ connection pool and its private tables. PostgreSQL is not supported by this
6
+ package.
7
+
8
+ This is an experimental snapshot package. Use Node 24 or newer, generated
9
+ record schemas, and a reachable MySQL database.
10
+
11
+ For database requirements, query limits, lifecycle, and error details, see
12
+ [REFERENCE documentation for agents](REFERENCE.md).
13
+
14
+ ## 💡 Why use it?
15
+
16
+ - ✅ Stores Spine records durably in a MySQL database.
17
+ - ✅ Manages a bounded `mysql2` connection pool; InnoDB writes are transactional.
18
+ - ✅ Supports declared-column filters, sorting, offsets, limits, and
19
+ continuations.
20
+ - ✅ Keeps adapter tables private behind the common `RecordStorage` API.
21
+
22
+ ## 🚀 First snapshot success
23
+
24
+ ```sh
25
+ mkdir spine-mysql-app && cd spine-mysql-app
26
+ pnpm init
27
+ pnpm add @spine-event-engine/storage-mysql@snapshot @spine-event-engine/storage@snapshot @bufbuild/protobuf
28
+ ```
29
+
30
+ Create an empty MySQL database, set an application-owned connection URL, and
31
+ run the factory example below with Node 24 or newer. A successful read of
32
+ `task-42` proves the installed snapshot can open its factory and store a record.
33
+ The snapshot tag can change before a stable release.
34
+
35
+ ## 🔌 Create and close a MySQL factory
36
+
37
+ Provide a MySQL URL that includes a database name. Building the factory opens
38
+ its pool only; each record family creates and verifies its private table lazily
39
+ on first use.
40
+
41
+ <!-- docs-snippet-path: packages/storage-mysql/src/index.ts -->
42
+
43
+ ```ts
44
+ import { create, ScalarType } from "@bufbuild/protobuf";
45
+ import { StringValueSchema, type StringValue } from "@bufbuild/protobuf/wkt";
46
+ import { ColumnTypes, RecordColumn, RecordSpec } from "@spine-event-engine/storage";
47
+ import { MysqlStorageFactory } from "@spine-event-engine/storage-mysql";
48
+
49
+ const factory = await MysqlStorageFactory.newBuilder()
50
+ .setOptions({
51
+ url: "mysql://user:password@127.0.0.1:3306/spine_app",
52
+ connectionLimit: 8,
53
+ })
54
+ .build();
55
+ const records = factory.createRecordStorage(
56
+ { name: "Tasks", multitenant: false },
57
+ new RecordSpec<string, StringValue>({
58
+ recordType: StringValueSchema,
59
+ idKind: "string",
60
+ extractId: (record) => record.value,
61
+ columns: [
62
+ new RecordColumn("value", ColumnTypes.scalar(ScalarType.STRING), (record) => record.value),
63
+ ],
64
+ }),
65
+ );
66
+
67
+ try {
68
+ await records.write(create(StringValueSchema, { value: "task-42" }));
69
+ const stored = await records.read("task-42");
70
+ if (stored?.value !== "task-42") throw new Error("The record was not stored.");
71
+ } finally {
72
+ await records.close();
73
+ factory.close();
74
+ }
75
+ ```
76
+
77
+ This local loopback example intentionally uses MySQL without TLS. In production,
78
+ require TLS and provide the issuing CA explicitly; do not enable certificate
79
+ verification without the CA material needed by your managed MySQL endpoint.
80
+
81
+ For a multitenant application, assign each complete generated `TenantId` to a
82
+ different database. The factory creates one pool per configured tenant and
83
+ selects that pool before it opens a table or starts a transaction:
84
+
85
+ ```ts
86
+ import { create } from "@bufbuild/protobuf";
87
+ import { TenantIdSchema } from "@spine-event-engine/proto";
88
+ import { MysqlStorageFactory } from "@spine-event-engine/storage-mysql";
89
+
90
+ const acme = create(TenantIdSchema, { kind: { case: "value", value: "acme" } });
91
+ const globex = create(TenantIdSchema, { kind: { case: "value", value: "globex" } });
92
+
93
+ const factory = await MysqlStorageFactory.newBuilder()
94
+ .setTenantOptions([
95
+ { tenantId: acme, options: { url: "mysql://user:password@db/acme" } },
96
+ { tenantId: globex, options: { url: "mysql://user:password@db/globex" } },
97
+ ])
98
+ .build();
99
+ ```
100
+
101
+ Use a dedicated database account. The account must be able to create and
102
+ inspect the adapter tables and perform normal reads and writes. Do not commit
103
+ connection URLs or credentials.
104
+
105
+ ## Build it in this workspace
106
+
107
+ Contributors changing this repository can run the workspace-wide build from its
108
+ root:
109
+
110
+ ```sh
111
+ pnpm typecheck:build
112
+ ```
113
+
114
+ ## ✨ Supported records and queries
115
+
116
+ The adapter performs record CRUD, payload-based compare-and-set, named-column
117
+ queries, sort order, offsets, limits, and keyset continuations. InnoDB makes
118
+ `writeAll` and Entity commits transactional. MyISAM and Aria instead use
119
+ deterministic ordered writes with immutable-prefix retry semantics; a failed
120
+ write may require an identical retry. It supports primitive and structured
121
+ storage IDs. Declared columns support strings, booleans, integral Protobuf
122
+ numbers, enums, bytes, messages, `Timestamp`, and `Version`. Spine JVM JDBC
123
+ does not support `float` or `double` record columns, so this adapter rejects
124
+ them too.
125
+
126
+ MyISAM and Aria limit the byte length of an indexed key. Their `VARCHAR(512)`
127
+ ID column therefore needs a one-byte binary collation, such as `latin1_bin`,
128
+ and every ID must be representable in that character set. The normal InnoDB
129
+ table can keep the database's Unicode character set.
130
+
131
+ Each record source uses a separate private table. An ungrouped family defaults to
132
+ its Proto full name with dots replaced by underscores. A grouped family uses
133
+ the group name with dots replaced by underscores, followed by the record type's
134
+ short name. Tables include native declared columns, but the adapter never adds
135
+ user-column indexes automatically.
136
+
137
+ The table contains exactly `ID`, the serialized `bytes`, the framework columns
138
+ for that record family, and fields explicitly marked `(column)` in the Proto
139
+ model. It does not get a separate SQL column for every Proto field. `ID` is the
140
+ primary key. A Bounded Context name is useful in diagnostics, but it is never
141
+ stored in a row and never changes a table name.
142
+
143
+ For generated records, start by marking the few Proto fields that a query needs
144
+ with `(column)`. Those declarations, not a field-name convention, select the
145
+ native MySQL columns. `Identifiers` determine the storage ID, and `Stringifiers`
146
+ turn message-valued IDs and declared message columns into the same stable text
147
+ for a write, lookup, filter, sort continuation, and read. `RecordQuery<I>`
148
+ statically types IDs only: MySQL validates filter names and values at runtime
149
+ against the record descriptor and its declared column mappings.
150
+
151
+ ## 🧭 See a Proto model become a table
152
+
153
+ Suppose an application declares this Projection state:
154
+
155
+ ```proto
156
+ package spine.examples.messageboard;
157
+
158
+ message MessageView {
159
+ MessageId id = 1 [(required) = true, (set_once) = true];
160
+ BoardId board = 2 [(column) = true];
161
+ UserId author = 3 [(column) = true];
162
+ string text = 4;
163
+ }
164
+ ```
165
+
166
+ The default current-state table is conceptually:
167
+
168
+ ```sql
169
+ CREATE TABLE spine_examples_messageboard_MessageView (
170
+ ID VARCHAR(512) NOT NULL,
171
+ bytes BLOB NOT NULL,
172
+ archived BOOLEAN NOT NULL DEFAULT false,
173
+ deleted BOOLEAN NOT NULL DEFAULT false,
174
+ version INT NOT NULL DEFAULT 0,
175
+ board TEXT NULL,
176
+ author TEXT NULL,
177
+ PRIMARY KEY (ID)
178
+ );
179
+ ```
180
+
181
+ `ID` stores `MessageId` as compact Proto JSON, such as
182
+ `{"value":"message-42"}`. `bytes` contains the authoritative generated
183
+ `EntityRecord`, including the complete `MessageView` state. `archived`,
184
+ `deleted`, and `version` are Entity lifecycle/version facts, not a provider
185
+ revision. The `board` and `author` columns exist only because those Proto fields
186
+ use `(column)`; `text` stays inside `bytes` because it is not a query column.
187
+
188
+ For `board == BoardId("board-7")`, Spine uses the same reversible stringifier
189
+ as the write and sends parameterized SQL equivalent to:
190
+
191
+ ```sql
192
+ SELECT ID, bytes
193
+ FROM spine_examples_messageboard_MessageView
194
+ WHERE board = ?
195
+ ORDER BY ID ASC;
196
+ -- bound value: {"value":"board-7"}
197
+ ```
198
+
199
+ MySQL compares the materialized column, then Spine decodes each matching
200
+ authoritative `bytes` payload. The adapter does not create an index for
201
+ `board`; add application indexes for production query patterns.
202
+
203
+ ## 🧪 Verify with a disposable database
204
+
205
+ Run the opt-in integration suite against a disposable MySQL database:
206
+
207
+ ```sh
208
+ SPINE_TS_MYSQL_URL='mysql://user:password@127.0.0.1:3306/spine_test' \
209
+ pnpm --filter @spine-event-engine/storage-mysql test:mysql
210
+ ```
211
+
212
+ The test creates temporary adapter tables and removes them afterward. It is not a
213
+ substitute for an application's backup, monitoring, permissions, or database
214
+ operations plan.
215
+
216
+ ## ⚠️ Before production
217
+
218
+ Use a dedicated database and account, protect the connection URL, configure
219
+ TLS, and plan backups, monitoring, and migrations. Indexed `bigint` values must
220
+ fit the exact signed 64-bit MySQL range. PostgreSQL is provided separately by
221
+ [`@spine-event-engine/storage-postgres`](https://github.com/SpineEventEngine/spine-ts/blob/master/packages/storage-postgres/README.md).
222
+
223
+ Before starting this corrected layout against an existing database, run the
224
+ legacy-layout inventory for every configured tenant database:
225
+
226
+ ```sh
227
+ pnpm --dir packages/storage-mysql inventory:legacy -- \
228
+ --url 'mysql://user:password@127.0.0.1:3306/tenant_a' \
229
+ --url 'mysql://user:password@127.0.0.1:3306/tenant_b'
230
+ ```
231
+
232
+ The command exits nonzero if a database is unreachable or contains the old
233
+ `_scope`, `_revision`, or compound scope key. Do not start the corrected
234
+ runtime until it passes. The factory repeats this check for every configured
235
+ database before it becomes usable. The runtime does not read both layouts or choose
236
+ between rows that old Bounded Context partitions would collapse onto the same
237
+ new `ID`; migrate those rows offline and stop on every conflict.
238
+
239
+ ## 🔗 Learn more
240
+
241
+ - [Storage API](https://github.com/SpineEventEngine/spine-ts/blob/master/packages/storage/README.md)
242
+ - [End-user storage guide](https://github.com/SpineEventEngine/spine-ts/blob/master/docs/USER_GUIDE.md#6-persist-application-data)
243
+ - [Reference for coding agents](REFERENCE.md)
package/REFERENCE.md ADDED
@@ -0,0 +1,140 @@
1
+ # @spine-event-engine/storage-mysql reference
2
+
3
+ This reference is for agents configuring the supported MySQL storage adapter.
4
+
5
+ ## Public entry point
6
+
7
+ Import `MysqlStorageFactory`, `MysqlStorageOptions`, `MysqlTenantStorageOptions`,
8
+ `MysqlEntityStorageHandle`, `MysqlStorageFactoryBuilder`,
9
+ `MysqlCreateOperation`, `CreateOperationFactory`, `MysqlTableSpec`,
10
+ `MysqlColumnSpec`, `MysqlStorageConfigurationError`,
11
+ `MysqlStorageConnectionError`, `MysqlStorageSchemaError`,
12
+ `MysqlStorageDataError`, and `MysqlStorageOperationError` from
13
+ `@spine-event-engine/storage-mysql`.
14
+
15
+ ## Connection and schema
16
+
17
+ `MysqlStorageFactory.newBuilder().setOptions(options).build()` configures one
18
+ single-tenant database. `setTenantOptions(entries)` configures one distinct
19
+ database and pool per complete generated `TenantId`. The factory selects
20
+ the matching pool before table, query, transaction, or lock work.
21
+ `setStringifierRegistry(registry)` configures reversible mappings for
22
+ message-valued IDs and ordinary message columns; the builder snapshots the
23
+ registry so later caller changes do not alter stored or queried values.
24
+ `Identifiers` choose the storage ID representation; the configured
25
+ `StringifierRegistry` supplies the matching reversible representation for
26
+ message-valued IDs and declared message columns. `RecordQuery<I>` statically
27
+ types IDs only. Filter names and values are runtime inputs: MySQL checks the
28
+ name against the declared columns and maps each value through the corresponding
29
+ descriptor/column mapping, rather than accepting an application-constructed
30
+ provider string.
31
+ Per-family tables are created and verified lazily on first use. Options support
32
+ `connectionLimit`, `connectTimeoutMs`, and TLS material. Failure to validate
33
+ configuration throws `MysqlStorageConfigurationError`; inaccessible connections
34
+ are reported as `MysqlStorageConnectionError`; an
35
+ incompatible private table shape throws `MysqlStorageSchemaError`.
36
+
37
+ The adapter supports MySQL and MariaDB InnoDB, MyISAM, and Aria family tables.
38
+ It creates and verifies a family table lazily. An account therefore needs DDL
39
+ permission, metadata reads, and DML. Existing tables are inspected and never
40
+ altered.
41
+
42
+ MyISAM and Aria impose a smaller primary-key byte limit than InnoDB. A family
43
+ using the canonical `VARCHAR(512)` ID must therefore be provisioned with a
44
+ one-byte binary collation, such as `latin1_bin`, and can store only IDs
45
+ representable in that character set. An `utf8mb4` ID of that declared width
46
+ cannot be converted to MyISAM.
47
+
48
+ Before deployment, run `pnpm --dir packages/storage-mysql inventory:legacy --
49
+ --url <database-url>` once for every configured tenant database. The command
50
+ fails closed on connection errors, `_scope`, `_revision`, or an old primary key
51
+ containing `_scope`. Passing this inventory is a startup prerequisite for an
52
+ upgraded application. Factory build repeats the inspection for every configured
53
+ database; the runtime has no dual-layout reader or automatic
54
+ conflict winner.
55
+
56
+ ## Lifecycle and tenancy
57
+
58
+ `close(): void` marks the factory and its live handles closed and starts pool
59
+ draining. Callers do not await it. A record handle closes independently. A
60
+ single-tenant factory has one database. A multitenant factory requires a
61
+ complete generated `TenantId` on each operation and routes it to its configured
62
+ database. Bounded Context names are diagnostic only and never partition rows,
63
+ tables, locks, or queries.
64
+
65
+ Each Entity source and history family has an independent table. Errors do not
66
+ include connection URLs, credentials, or provider details.
67
+
68
+ ## Records and queries
69
+
70
+ CRUD operations use normal statements. Payload-based compare-and-set uses an
71
+ InnoDB transaction or a keyed `GET_LOCK` on MyISAM and Aria. On InnoDB,
72
+ `writeAll` encodes the input first, applies entries in input order, and commits
73
+ all rows or none. On MyISAM and Aria, `writeAll` has deterministic input-order
74
+ semantics but is not transactional; a failed Entity prefix requires an
75
+ identical retry. Repeated storage slots in a batch leave the last entry as the
76
+ stored value. IDs are declared as generated message IDs or the supported
77
+ primitive `string`, `int32`, and `int64` kinds. Primitive IDs use native MySQL
78
+ values; message IDs use their reversible stringifier, compact Proto JSON by
79
+ default.
80
+
81
+ Every family table has `ID`, serialized `bytes`, and only the columns declared
82
+ by its framework record and Proto model, with primary key `(ID)`. Current Entity
83
+ tables declare `archived`, `deleted`, and Entity `version` in addition to model
84
+ `(column)` fields. Those three framework columns are non-null and default to
85
+ `false`, `false`, and `0`, respectively; Entity `version` is not a provider
86
+ revision. Proto fields without `(column)` exist only inside the authoritative
87
+ `bytes` record and never become SQL columns. Existing layouts are inspected and
88
+ never altered. A mismatched type, nullability, primary key, unique constraint,
89
+ or extra column is rejected. Ordinary message columns use the same configured
90
+ reversible stringifier for writes and query operands. `Timestamp` uses epoch
91
+ nanoseconds and `Version` uses its number. Floating-point record columns are
92
+ not supported by Spine JVM JDBC and are rejected here.
93
+
94
+ Queries execute ID filters, ANDed column filters, materialized-column sorts,
95
+ keyset continuations, offsets, and limits in MySQL. Before executing, MySQL
96
+ validates each ID encoding, requires every filter and sort name to be `ID` or a
97
+ declared materialized column, and maps each filter/continuation value through
98
+ that column's descriptor. Missing materialized columns do not match; dotted
99
+ payload paths are rejected. Large offsets can be expensive.
100
+
101
+ Normalized projection plans compile IDs, equality, all five comparisons, nested
102
+ `all` / `either`, ordering, limits, and masks to one parameterized SQL statement.
103
+ A mask is applied only after an otherwise fully bounded complete-record fetch.
104
+ Normalized plans have no offset; `RecordQuery.offset` remains separate. The selected
105
+ tenant pool is acquired before the resolved family table is accessed; only that
106
+ validated table and declared columns are interpolated, while IDs, operands, and
107
+ limits are bound. Ordering ends with `ID` for a stable tie-break. An omitted
108
+ query budget accepts at most 10,000 rows; an explicit value cannot exceed
109
+ 10,000. The provider fetches only the
110
+ smaller safe bound from the exact limit and query budget plus one, so it may
111
+ read one overflow-lookahead row (10,001 raw rows at the default) before
112
+ rejecting an oversized result. The primary
113
+ key serves ID queries; operators must add indexes for workload equality, range,
114
+ and composite filter/order patterns. Without them MySQL may scan or sort despite
115
+ the runtime materialization bound. To keep one normalized statement finite,
116
+ MySQL accepts at most 1,000 bound parameters including its provider limit;
117
+ oversized ID sets or composite predicate bind work reject before a connection is
118
+ acquired.
119
+
120
+ ## Entity history seam
121
+
122
+ The provider/framework Entity handle returns current records plus immutable
123
+ state and event history. It is not a remote application history API. State append and retention for one entity use a MySQL server lock;
124
+ this coordination applies to one MySQL server only. Trim and truncate use
125
+ fixed-size chunks. A failed chunk can leave earlier chunks durable, so callers
126
+ retry maintenance. Current-record and history actions are separate calls, not
127
+ one cross-storage transaction.
128
+
129
+ The internal atomic Entity commit port writes current state, configured history,
130
+ and framework delivery events. InnoDB uses one connection transaction;
131
+ nontransactional engines use a deterministic immutable-history prefix and may
132
+ require an identical retry after a storage failure. Standalone history
133
+ operations remain separate.
134
+
135
+ `MysqlStorageSchemaError` reports incompatible layouts,
136
+ `MysqlStorageDataError` reports stored bytes that cannot be decoded, and
137
+ `MysqlStorageOperationError` reports sanitized bounds, query, collision, and
138
+ driver-operation failures. Custom creation uses `useOperationFactory()`; its
139
+ resolved `MysqlTableSpec` has the same native column types and naming precedence
140
+ as default DDL (explicit grouped name, explicit record name, then default).
@@ -0,0 +1,3 @@
1
+ export { MysqlStorageConfigurationError, MysqlStorageConnectionError, MysqlStorageDataError, MysqlStorageFactory, MysqlStorageOperationError, MysqlStorageSchemaError, type CreateOperationFactory, type MysqlColumnSpec, type MysqlCreateOperation, type MysqlStorageFactoryBuilder, type MysqlStorageOptions, type MysqlTenantStorageOptions, type MysqlTableSpec, } from "./mysql/storage-factory.js";
2
+ export type { MysqlEntityStorageHandle } from "./mysql/entity-history.js";
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAcA,OAAO,EACL,8BAA8B,EAC9B,2BAA2B,EAC3B,qBAAqB,EACrB,mBAAmB,EACnB,0BAA0B,EAC1B,uBAAuB,EACvB,KAAK,sBAAsB,EAC3B,KAAK,eAAe,EACpB,KAAK,oBAAoB,EACzB,KAAK,0BAA0B,EAC/B,KAAK,mBAAmB,EACxB,KAAK,yBAAyB,EAC9B,KAAK,cAAc,GACpB,MAAM,4BAA4B,CAAC;AACpC,YAAY,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,15 @@
1
+ /*
2
+ * Copyright 2026, CodeMatters. All rights reserved.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5
+ * in compliance with the License. You may obtain a copy of the License at
6
+ *
7
+ * https://www.apache.org/licenses/LICENSE-2.0
8
+ *
9
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
10
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11
+ * or implied. See the License for the specific language governing permissions and limitations under
12
+ * the License.
13
+ */
14
+ export { MysqlStorageConfigurationError, MysqlStorageConnectionError, MysqlStorageDataError, MysqlStorageFactory, MysqlStorageOperationError, MysqlStorageSchemaError, } from "./mysql/storage-factory.js";
15
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EACL,8BAA8B,EAC9B,2BAA2B,EAC3B,qBAAqB,EACrB,mBAAmB,EACnB,0BAA0B,EAC1B,uBAAuB,GAQxB,MAAM,4BAA4B,CAAC"}
@@ -0,0 +1,27 @@
1
+ import { StringifierRegistry } from "@spine-event-engine/core";
2
+ import type { ColumnMapping, ColumnTypeMapping, RecordColumnType } from "@spine-event-engine/storage";
3
+ /**
4
+ * Converts typed Protobuf column values to Spine JVM JDBC values.
5
+ */
6
+ export declare class MysqlColumnMapping implements ColumnMapping<unknown> {
7
+ #private;
8
+ /**
9
+ * Creates a JVM-compatible MySQL column mapping.
10
+ *
11
+ * @param stringifiers The schema-bound message stringifiers.
12
+ */
13
+ constructor(stringifiers?: StringifierRegistry);
14
+ /**
15
+ * Returns the conversion for one generated column type.
16
+ *
17
+ * @param type The generated Protobuf column type.
18
+ * @returns The JVM-compatible MySQL parameter conversion.
19
+ */
20
+ of<V>(type: RecordColumnType<V>): ColumnTypeMapping<V, unknown>;
21
+ /**
22
+ * Returns SQL null unchanged.
23
+ * @returns The null conversion.
24
+ */
25
+ ofNull(): ColumnTypeMapping<null, unknown>;
26
+ }
27
+ //# sourceMappingURL=column-mapping.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"column-mapping.d.ts","sourceRoot":"","sources":["../../src/mysql/column-mapping.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,KAAK,EACV,aAAa,EACb,iBAAiB,EACjB,gBAAgB,EACjB,MAAM,6BAA6B,CAAC;AAKrC;;GAEG;AACH,qBAAa,kBAAmB,YAAW,aAAa,CAAC,OAAO,CAAC;;IAG/D;;;;OAIG;gBACS,YAAY,GAAE,mBAA+C;IAMzE;;;;;OAKG;IACH,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,gBAAgB,CAAC,CAAC,CAAC,GAAG,iBAAiB,CAAC,CAAC,EAAE,OAAO,CAAC;IAoB/D;;;OAGG;IACH,MAAM,IAAI,iBAAiB,CAAC,IAAI,EAAE,OAAO,CAAC;CAG3C"}