1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
//! Runtime-agnostic procedural macros for the wasm-dbms DBMS engine.
//!
//! This crate provides procedural macros to automatically implement traits
//! required by the `wasm-dbms` engine.
//!
//! ## Provided Derive Macros
//!
//! - `Encode`: Automatically implements the `Encode` trait for structs.
//! - `Table`: Automatically implements the `TableSchema` trait and associated types.
//! - `DatabaseSchema`: Generates `DatabaseSchema<M>` trait dispatch and `register_tables`.
//! - `CustomDataType`: Bridge user-defined types into the `Value` system.
use TokenStream;
use ;
/// Automatically implements the `Encode` trait for a struct.
///
/// This derive macro generates two methods required by the `Encode` trait:
///
/// - `fn data_size() -> DataSize`
/// Computes the static size of the encoded type.
/// If all fields implement `Encode::data_size()` returning
/// `DataSize::Fixed(n)`, then the type is also considered fixed-size.
/// Otherwise, the type is `DataSize::Dynamic`.
///
/// - `fn size(&self) -> MSize`
/// Computes the runtime-encoding size of the value by summing the
/// sizes of all fields.
///
/// # What the macro generates
///
/// Given a struct like:
///
/// ```rust,ignore
/// #[derive(Encode)]
/// struct User {
/// id: Uint32,
/// name: Text,
/// }
/// ```
///
/// The macro expands into:
///
/// ```rust,ignore
/// impl Encode for User {
/// const DATA_SIZE: DataSize = DataSize::Dynamic; // or DataSize::Fixed(n) if applicable
///
/// fn size(&self) -> MSize {
/// self.id.size() + self.name.size()
/// }
///
/// fn encode(&'_ self) -> std::borrow::Cow<'_, [u8]> {
/// let mut encoded = Vec::with_capacity(self.size() as usize);
/// encoded.extend_from_slice(&self.id.encode());
/// encoded.extend_from_slice(&self.name.encode());
/// std::borrow::Cow::Owned(encoded)
/// }
///
/// fn decode(data: std::borrow::Cow<[u8]>) -> ::wasm_dbms_api::prelude::MemoryResult<Self> {
/// let mut offset = 0;
/// let id = Uint32::decode(std::borrow::Borrowed(&data[offset..]))?;
/// offset += id.size() as usize;
/// let name = Text::decode(std::borrow::Borrowed(&data[offset..]))?;
/// offset += name.size() as usize;
/// Ok(Self { id, name })
/// }
/// }
/// ```
/// # Requirements
///
/// - Each field type must implement `Encode`.
/// - Only works on `struct`s; enums and unions are not supported.
/// - All field identifiers must be valid Rust identifiers (no tuple structs).
///
/// # Notes
///
/// - It is intended for internal use within the `wasm-dbms` DBMS memory
/// system.
///
/// # Errors
///
/// The macro will fail to expand if:
///
/// - The struct has unnamed fields (tuple struct)
/// - A field type does not implement `Encode`
/// - The macro is applied to a non-struct item.
///
/// # Example
///
/// ```rust,ignore
/// #[derive(Encode, Debug, PartialEq, Eq)]
/// struct Position {
/// x: Int32,
/// y: Int32,
/// }
///
/// let pos = Position { x: 10.into(), y: 20.into() };
/// assert_eq!(Position::data_size(), DataSize::Fixed(8));
/// assert_eq!(pos.size(), 8);
/// let encoded = pos.encode();
/// let decoded = Position::decode(encoded).unwrap();
/// assert_eq!(pos, decoded);
/// ```
/// Given a struct representing a database table, automatically implements
/// the `TableSchema` trait with all the necessary types to work with the wasm-dbms engine.
/// So given this struct:
///
/// ```rust,ignore
/// #[derive(Table, Encode)]
/// #[table = "posts"]
/// struct Post {
/// #[primary_key]
/// id: Uint32,
/// title: Text,
/// content: Text,
/// #[foreign_key(entity = "User", table = "users", column = "id")]
/// author_id: Uint32,
/// }
/// ```
///
/// What we expect as output is:
///
/// - To implement the `TableSchema` trait for the struct as follows:
///
/// ```rust,ignore
/// impl TableSchema for Post {
/// type Insert = PostInsertRequest;
/// type Record = PostRecord;
/// type Update = PostUpdateRequest;
/// type ForeignFetcher = PostForeignFetcher;
///
/// fn columns() -> &'static [ColumnDef] {
/// &[
/// ColumnDef {
/// name: "id",
/// data_type: DataTypeKind::Uint32,
/// auto_increment: false,
/// nullable: false,
/// primary_key: true,
/// unique: true,
/// foreign_key: None,
/// },
/// ColumnDef {
/// name: "title",
/// data_type: DataTypeKind::Text,
/// auto_increment: false,
/// nullable: false,
/// primary_key: false,
/// unique: false,
/// foreign_key: None,
/// },
/// ColumnDef {
/// name: "content",
/// data_type: DataTypeKind::Text,
/// auto_increment: false,
/// nullable: false,
/// primary_key: false,
/// unique: false,
/// foreign_key: None,
/// },
/// ColumnDef {
/// name: "user_id",
/// data_type: DataTypeKind::Uint32,
/// auto_increment: false,
/// nullable: false,
/// primary_key: false,
/// unique: false,
/// foreign_key: Some(ForeignKeyDef {
/// local_column: "user_id",
/// foreign_table: "users",
/// foreign_column: "id",
/// }),
/// },
/// ]
/// }
///
/// fn table_name() -> &'static str {
/// "posts"
/// }
///
/// fn primary_key() -> &'static str {
/// "id"
/// }
///
/// fn to_values(self) -> Vec<(ColumnDef, Value)> {
/// vec![
/// (Self::columns()[0], Value::Uint32(self.id)),
/// (Self::columns()[1], Value::Text(self.title)),
/// (Self::columns()[2], Value::Text(self.content)),
/// (Self::columns()[3], Value::Uint32(self.user_id)),
/// ]
/// }
/// }
/// ```
///
/// - Implement the associated `Record` type
/// - Implement the associated `InsertRecord` type
/// - Implement the associated `UpdateRecord` type
/// - If has foreign keys, implement the associated `ForeignFetcher`
///
/// So for each struct deriving `Table`, we will generate the following type. Given `${StructName}`, we will generate:
///
/// - `${StructName}Record` - implementing `TableRecord`
/// - `${StructName}InsertRequest` - implementing `InsertRecord`
/// - `${StructName}UpdateRequest` - implementing `UpdateRecord`
/// - `${StructName}ForeignFetcher` (only if foreign keys are present)
///
/// Also, we will implement the `TableSchema` trait for the struct itself and derive `Encode` for `${StructName}`.
///
/// ## Attributes
///
/// The `Table` derive macro supports the following attributes:
///
/// - `#[alignment = N]`: (optional) Specifies the alignment for the table records. Use only if you know what you are doing.
/// - `#[autoincrement]`: Marks a field as auto-incrementing. The macro will generate code to automatically fill in values for this field during inserts. Auto-increment fields must be non-nullable and cannot be marked as `#[unique]`.
/// - `#[candid]`: Marks the table as compatible with Candid serialization.
/// - `#[custom_type = "TypeName"]`: Specifies a custom data type for the
/// - `#[foreign_key(entity = "EntityName", table = "table_name", column = "column_name")]`: Defines a foreign key relationship.
/// - `#[index]`: Marks a field to be indexed for faster queries.
/// - `#[primary_key]`: Marks a field as the primary key of the table.
/// - `#[sanitizer(SanitizerType)]`: Specifies a sanitize for the field.
/// - `#[table = "table_name"]`: Specifies the name of the table in the database.
/// - `#[unique]`: Marks a field to have a unique constraint.
/// - `#[validate(ValidatorType)]`: Specifies a validator for the field.
///
/// Derives the [`CustomDataType`] trait and an `impl From<T> for Value` conversion
/// for a user-defined enum or struct.
///
/// The type must also derive [`Encode`] (for binary serialization) and implement
/// [`Display`](std::fmt::Display) (for the cached display string in [`CustomValue`]).
///
/// # Required attribute
///
/// - `#[type_tag = "..."]`: A unique string identifier for this custom data type.
///
/// # What the macro generates
///
/// Given a type like:
///
/// ```rust,ignore
/// #[derive(Encode, CustomDataType)]
/// #[type_tag = "status"]
/// enum Status { Active, Inactive }
/// ```
///
/// The macro expands into:
///
/// ```rust,ignore
/// impl CustomDataType for Status {
/// const TYPE_TAG: &'static str = "status";
/// }
///
/// impl From<Status> for Value {
/// fn from(val: Status) -> Value {
/// Value::Custom(CustomValue {
/// type_tag: "status".to_string(),
/// encoded: Encode::encode(&val).into_owned(),
/// display: val.to_string(),
/// })
/// }
/// }
/// ```
///
/// # Note
///
/// The user must also provide `Display`, `Default`, and `DataType` implementations
/// for the type. This macro only bridges the custom type to the `Value` system.
/// Generates a [`DatabaseSchema`] implementation that dispatches generic
/// DBMS operations to the correct concrete table types.
///
/// Given a struct annotated with `#[tables(User = "users", Post = "posts")]`,
/// this macro produces:
///
/// - `impl<M: MemoryProvider> DatabaseSchema<M>` with match-arm dispatch
/// for `select`, `insert`, `delete`, `update`, `validate_insert`,
/// `validate_update`, and `referenced_tables`.
/// - An inherent `register_tables` method that registers all tables in a
/// [`DbmsContext`].
///
/// # Example
///
/// ```rust,ignore
/// #[derive(DatabaseSchema)]
/// #[tables(User = "users", Post = "posts")]
/// pub struct MySchema;
///
/// // Register tables during initialization:
/// MySchema::register_tables(&ctx)?;
/// ```
///
/// # Requirements
///
/// - Each type in the `#[tables(...)]` attribute must implement
/// [`TableSchema`].
/// - The generated types (`UserInsertRequest`, `UserUpdateRequest`,
/// `UserRecord`, etc.) must be in scope.