prax-codegen 0.10.0

Procedural macros for code generation in the Prax ORM
Documentation
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! Procedural macros for the Prax ORM.
//!
//! This crate provides compile-time code generation for Prax, transforming
//! schema definitions into type-safe Rust code.
//!
//! # Macros
//!
//! - [`prax_schema!`] - Generate models from a `.prax` schema file
//! - [`Model`] - Derive macro for manual model definition
//!
//! # Plugins
//!
//! Code generation can be extended with plugins enabled via environment variables:
//!
//! ```bash
//! # Enable debug information
//! PRAX_PLUGIN_DEBUG=1 cargo build
//!
//! # Enable JSON Schema generation
//! PRAX_PLUGIN_JSON_SCHEMA=1 cargo build
//!
//! # Enable GraphQL SDL generation
//! PRAX_PLUGIN_GRAPHQL=1 cargo build
//!
//! # Enable custom serialization helpers
//! PRAX_PLUGIN_SERDE=1 cargo build
//!
//! # Enable runtime validation
//! PRAX_PLUGIN_VALIDATOR=1 cargo build
//!
//! # Enable all plugins
//! PRAX_PLUGINS_ALL=1 cargo build
//! ```
//!
//! # Example
//!
//! ```rust,ignore
//! // Generate models from schema file
//! prax::prax_schema!("schema.prax");
//!
//! // Or manually define with derive macro
//! #[derive(prax::Model)]
//! #[prax(table = "users")]
//! struct User {
//!     #[prax(id, auto)]
//!     id: i32,
//!     #[prax(unique)]
//!     email: String,
//!     name: Option<String>,
//! }
//! ```

use proc_macro::TokenStream;
use quote::quote;
use syn::{DeriveInput, LitStr, parse_macro_input};

mod generators;
mod macros;
mod plugins;
mod schema_reader;
mod types;

use generators::{
    generate_enum_module, generate_model_module_with_style, generate_type_module,
    generate_view_module,
};

/// Generate models from a Prax schema file.
///
/// This macro reads a `.prax` schema file at compile time and generates
/// type-safe Rust code for all models, enums, and types defined in the schema.
///
/// # Example
///
/// ```rust,ignore
/// prax::prax_schema!("schema.prax");
///
/// // Now you can use the generated types:
/// let user = client.user().find_unique(user::id::equals(1)).exec().await?;
/// ```
///
/// # Generated Code
///
/// For each model in the schema, this macro generates:
/// - A module with the model name (snake_case)
/// - A `Data` struct representing a row from the database
/// - A `CreateInput` struct for creating new records
/// - A `UpdateInput` struct for updating records
/// - Field modules with filter operations (`equals`, `contains`, `in_`, etc.)
/// - A `WhereParam` enum for type-safe filtering
/// - An `OrderByParam` enum for sorting
/// - Select and Include builders for partial queries
#[proc_macro]
pub fn prax_schema(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as LitStr);
    let schema_path = input.value();

    match generate_from_schema(&schema_path) {
        Ok(tokens) => tokens.into(),
        Err(err) => {
            let err_msg = err.to_string();
            quote! {
                compile_error!(#err_msg);
            }
            .into()
        }
    }
}

/// Derive macro for defining Prax models manually.
///
/// This derive macro allows you to define models in Rust code instead of
/// using a `.prax` schema file. It generates the same query builder methods
/// and type-safe operations.
///
/// # Attributes
///
/// ## Struct-level
/// - `#[prax(table = "table_name")]` - Map to a different table name
/// - `#[prax(schema = "schema_name")]` - Specify database schema
///
/// ## Field-level
/// - `#[prax(id)]` - Mark as primary key
/// - `#[prax(auto)]` - Auto-increment field
/// - `#[prax(unique)]` - Unique constraint
/// - `#[prax(default = value)]` - Default value
/// - `#[prax(column = "col_name")]` - Map to different column
/// - `#[prax(relation(...))]` - Define relation
///
/// # Example
///
/// ```rust,ignore
/// #[derive(prax::Model)]
/// #[prax(table = "users")]
/// struct User {
///     #[prax(id, auto)]
///     id: i32,
///
///     #[prax(unique)]
///     email: String,
///
///     #[prax(column = "display_name")]
///     name: Option<String>,
///
///     #[prax(default = "now()")]
///     created_at: chrono::DateTime<chrono::Utc>,
/// }
/// ```
#[proc_macro_derive(Model, attributes(prax))]
pub fn derive_model(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    match generators::derive_model_impl(&input) {
        Ok(tokens) => tokens.into(),
        Err(err) => err.to_compile_error().into(),
    }
}

/// `prax::find_many!` — schema-aware declarative DSL for the
/// fluent-builder's `find_many` operation. See spec §4 for the full
/// grammar.
///
/// ```rust,ignore
/// prax::find_many!(client.user, {
///     where: { email: { contains: "@example.com" } },
///     order_by: { created_at: desc },
///     take: 10,
/// });
/// ```
#[proc_macro]
pub fn find_many(input: TokenStream) -> TokenStream {
    match macros::ops::find_many::expand_find_many(input.into()) {
        Ok(t) => t.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

/// `prax::find_unique!` — schema-aware DSL targeting `find_unique`.
/// The `where:` block must match a single `@unique` (or `@id`) column.
#[proc_macro]
pub fn find_unique(input: TokenStream) -> TokenStream {
    match macros::ops::find_unique::expand_find_unique(input.into()) {
        Ok(t) => t.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

/// `prax::find_first!` — schema-aware DSL targeting `find_first`.
#[proc_macro]
pub fn find_first(input: TokenStream) -> TokenStream {
    match macros::ops::find_first::expand_find_first(input.into()) {
        Ok(t) => t.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

/// `prax::count!` — schema-aware DSL targeting `count`. Phase 3 only
/// supports the `where:` key; the Prisma-style `_count` aggregate
/// (`select: { _count: { posts: true } }`) is phase 6.
#[proc_macro]
pub fn count(input: TokenStream) -> TokenStream {
    match macros::ops::count::expand_count(input.into()) {
        Ok(t) => t.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

/// `prax::aggregate!` — schema-aware DSL targeting `aggregate`. Accepts
/// `where:`, `_count:`, `_sum:`, `_avg:`, `_min:`, `_max:` keys. At least one
/// aggregate key is required.
///
/// ```rust,ignore
/// prax::aggregate!(client.user, {
///     where: { active: true },
///     _sum: { views: true, score: true },
///     _avg: { score: true },
///     _count: { _all: true },
/// });
/// ```
#[proc_macro]
pub fn aggregate(input: TokenStream) -> TokenStream {
    match macros::ops::aggregate::expand_aggregate(input.into()) {
        Ok(t) => t.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

/// `prax::group_by!` — schema-aware DSL targeting `group_by_columns`.
/// Accepts `by:` (required), `where:`, `_count:`, `_sum:`, `_avg:`, `_min:`,
/// `_max:`, and `having:` keys.
///
/// ```rust,ignore
/// prax::group_by!(client.user, {
///     by: [team_id, region],
///     where: { active: true },
///     _count: { _all: true },
///     _sum: { views: true },
///     having: { _count: { _all: { gt: 5 } } },
/// });
/// ```
#[proc_macro]
pub fn group_by(input: TokenStream) -> TokenStream {
    match macros::ops::group_by::expand_group_by(input.into()) {
        Ok(t) => t.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

/// `prax::delete!` — schema-aware DSL targeting `delete`. The
/// `where:` block must match a unique column.
#[proc_macro]
pub fn delete(input: TokenStream) -> TokenStream {
    match macros::ops::delete::expand_delete(input.into()) {
        Ok(t) => t.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

/// `prax::delete_many!` — schema-aware DSL targeting `delete_many`.
/// The `where:` block is the non-unique form.
///
/// **Warning:** an empty / `Filter::None` filter matches every row in
/// the table. See `WhereInput`'s trait-level note.
#[proc_macro]
pub fn delete_many(input: TokenStream) -> TokenStream {
    match macros::ops::delete_many::expand_delete_many(input.into()) {
        Ok(t) => t.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

/// `prax::r#where!` — schema-aware shape macro returning a
/// `<Model>WhereInput` value. Composes with the read macros via
/// `..spread`:
///
/// ```rust,ignore
/// let active = prax::r#where!(User, { active: true });
/// let _ = prax::find_many!(client.user, {
///     ..active,
///     email: { contains: "@x.com" },
/// });
/// ```
///
/// Exported as `r#where` because `where` is a Rust keyword and the
/// raw-identifier prefix is required at the call site whenever the
/// macro is reached through a path (`prax::r#where!(...)`).
#[proc_macro]
pub fn r#where(input: TokenStream) -> TokenStream {
    match macros::ops::shape::expand_where_shape(input.into()) {
        Ok(t) => t.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

/// `prax::include!` — schema-aware shape macro returning a
/// `<Model>Include` value. Composes with the read macros via
/// `..spread` to build reusable relation-include shapes.
///
/// ```rust,ignore
/// let with_posts = prax::include!(User, { posts: true });
/// let _ = prax::find_unique!(client.user, {
///     where: { id: 1 },
///     include: { ..with_posts },
/// });
/// ```
///
/// Distinct from `std::include!` — they live in different modules and
/// there is no ambiguity at the call site as long as the path is
/// fully qualified (`prax::include!`).
#[proc_macro]
pub fn include(input: TokenStream) -> TokenStream {
    match macros::ops::shape::expand_include_shape(input.into()) {
        Ok(t) => t.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

/// `prax::select!` — schema-aware shape macro returning a
/// `<Model>Select` value. Composes with the read macros via `..spread`.
///
/// ```rust,ignore
/// let lite = prax::select!(User, { id: true, email: true });
/// let _ = prax::find_many!(client.user, {
///     select: { ..lite },
/// });
/// ```
#[proc_macro]
pub fn select(input: TokenStream) -> TokenStream {
    match macros::ops::shape::expand_select_shape(input.into()) {
        Ok(t) => t.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

/// `prax::order_by!` — schema-aware shape macro returning an
/// `OrderBy` value. Accepts either a single `{ field: dir }` block or
/// a list of such blocks for multi-key sorts.
///
/// ```rust,ignore
/// let newest_first = prax::order_by!(User, { created_at: desc });
/// let _ = prax::find_many!(client.user, {
///     order_by: { created_at: desc },
/// });
/// // or as a list:
/// let by_active_then_email = prax::order_by!(User, [
///     { active: desc },
///     { email: asc },
/// ]);
/// ```
#[proc_macro]
pub fn order_by(input: TokenStream) -> TokenStream {
    match macros::ops::shape::expand_order_by_shape(input.into()) {
        Ok(t) => t.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

/// `prax::create!` — schema-aware DSL targeting `create`. Top-level
/// keys: `data:` (required), `include` xor `select`. Phase 5a is
/// scalar-only — relation operators inside `data:` (nested writes)
/// land in phase 5b.
///
/// ```rust,ignore
/// prax::create!(client.user, {
///     data: { email: "a@x.com", name: "Alice", age: 30 },
///     select: { id: true, email: true },
/// });
/// ```
#[proc_macro]
pub fn create(input: TokenStream) -> TokenStream {
    match macros::ops::create::expand_create(input.into()) {
        Ok(t) => t.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

/// `prax::update!` — schema-aware DSL targeting `update`. Top-level
/// keys: `where:` (required, unique), `data:` (required), `include`
/// xor `select`. Atomic operators (`increment`, `decrement`,
/// `multiply`, `divide`, `unset`) work via `{ <op>: V }` blocks inside
/// `data:` — see spec §4.
///
/// ```rust,ignore
/// prax::update!(client.user, {
///     where: { id: 1 },
///     data: {
///         name: "Renamed",
///         age: { increment: 1 },
///         last_seen: { unset: true },
///     },
///     select: { id: true, age: true },
/// });
/// ```
#[proc_macro]
pub fn update(input: TokenStream) -> TokenStream {
    match macros::ops::update::expand_update(input.into()) {
        Ok(t) => t.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

/// `prax::upsert!` — schema-aware DSL targeting `upsert`. Top-level
/// keys: `where:` (required, unique), `create:` (required), `update:`
/// (required), `include` xor `select`. On hit applies the `update:`
/// payload; on miss inserts the `create:` payload.
///
/// ```rust,ignore
/// prax::upsert!(client.user, {
///     where: { email: "a@x.com" },
///     create: { email: "a@x.com", name: "Alice", active: true, created_at: @(now) },
///     update: { name: { set: "Renamed" }, age: { increment: 1 } },
///     select: { id: true },
/// });
/// ```
#[proc_macro]
pub fn upsert(input: TokenStream) -> TokenStream {
    match macros::ops::upsert::expand_upsert(input.into()) {
        Ok(t) => t.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

/// `prax::create_many!` — schema-aware DSL targeting `create_many`.
/// Top-level keys: `data:` (required list of blocks),
/// `skip_duplicates:` (optional bool).
///
/// ```rust,ignore
/// prax::create_many!(client.user, {
///     data: [
///         { email: "a@x.com", name: "Alice" },
///         { email: "b@x.com", name: "Bob" },
///     ],
///     skip_duplicates: true,
/// });
/// ```
#[proc_macro]
pub fn create_many(input: TokenStream) -> TokenStream {
    match macros::ops::create_many::expand_create_many(input.into()) {
        Ok(t) => t.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

/// `prax::update_many!` — schema-aware DSL targeting `update_many`.
/// Top-level keys: `where:` (optional non-unique filter), `data:`
/// (required).
///
/// **Warning:** an empty/omitted `where:` matches every row in the
/// table — see the trait-level note on `WhereInput`.
///
/// ```rust,ignore
/// prax::update_many!(client.user, {
///     where: { active: false },
///     data: { active: true },
/// });
/// ```
#[proc_macro]
pub fn update_many(input: TokenStream) -> TokenStream {
    match macros::ops::update_many::expand_update_many(input.into()) {
        Ok(t) => t.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

/// `prax::cursor!` — schema-aware shape macro returning a
/// `<Model>WhereUniqueInput` value for use as a `cursor:` argument to
/// the read macros.
///
/// The block must have exactly one entry whose key refers to an
/// `@id` or `@unique` column on the model.
///
/// ```rust,ignore
/// let from = prax::cursor!(User, { id: 42 });
/// let _ = prax::find_many!(client.user, {
///     cursor: { id: 42 },
///     take: 10,
/// });
/// ```
#[proc_macro]
pub fn cursor(input: TokenStream) -> TokenStream {
    match macros::ops::shape::expand_cursor_shape(input.into()) {
        Ok(t) => t.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

/// Internal function to generate code from a schema file.
fn generate_from_schema(schema_path: &str) -> Result<proc_macro2::TokenStream, syn::Error> {
    use plugins::{PluginConfig, PluginContext, PluginRegistry};
    use schema_reader::read_schema_with_config;

    // Read and parse the schema file along with prax.toml configuration
    let schema_with_config = read_schema_with_config(schema_path).map_err(|e| {
        syn::Error::new(
            proc_macro2::Span::call_site(),
            format!("Failed to parse schema: {}", e),
        )
    })?;

    let schema = schema_with_config.schema;
    let model_style = schema_with_config.model_style;

    // Initialize plugin system with model_style from prax.toml
    // This auto-enables graphql plugins when model_style is GraphQL
    let plugin_config = PluginConfig::with_model_style(model_style);
    let plugin_registry = PluginRegistry::with_builtins();
    let plugin_ctx = PluginContext::new(&schema, &plugin_config);

    let mut output = proc_macro2::TokenStream::new();

    // Run plugin start hooks
    let start_output = plugin_registry.run_start(&plugin_ctx);
    output.extend(start_output.tokens);
    output.extend(start_output.root_items);

    // Generate enums first (models may reference them)
    for (_, enum_def) in &schema.enums {
        output.extend(generate_enum_module(enum_def)?);

        // Run plugin enum hooks
        let plugin_output = plugin_registry.run_enum(&plugin_ctx, enum_def);
        if !plugin_output.is_empty() {
            // Add plugin output to the enum module
            output.extend(plugin_output.tokens);
        }
    }

    // Generate composite types
    for (_, type_def) in &schema.types {
        output.extend(generate_type_module(type_def)?);

        // Run plugin type hooks
        let plugin_output = plugin_registry.run_type(&plugin_ctx, type_def);
        if !plugin_output.is_empty() {
            output.extend(plugin_output.tokens);
        }
    }

    // Generate views
    for (_, view_def) in &schema.views {
        output.extend(generate_view_module(view_def)?);

        // Run plugin view hooks
        let plugin_output = plugin_registry.run_view(&plugin_ctx, view_def);
        if !plugin_output.is_empty() {
            output.extend(plugin_output.tokens);
        }
    }

    // Generate models with the configured model style
    for (_, model_def) in &schema.models {
        output.extend(generate_model_module_with_style(
            model_def,
            &schema,
            model_style,
        )?);

        // Run plugin model hooks
        let plugin_output = plugin_registry.run_model(&plugin_ctx, model_def);
        if !plugin_output.is_empty() {
            output.extend(plugin_output.tokens);
        }
    }

    // Run plugin finish hooks
    let finish_output = plugin_registry.run_finish(&plugin_ctx);
    output.extend(finish_output.tokens);
    output.extend(finish_output.root_items);

    // Generate plugin documentation
    output.extend(plugins::generate_plugin_docs(&plugin_registry));

    Ok(output)
}