Skip to main content

schema_sql_generator/common/
key_generator.rs

1use crate::common::generator_context::GeneratorContext;
2use schema_model::model::key::Key;
3use schema_model::model::table::Table;
4use schema_model::model::types::DatabaseType;
5use schema_model::naming::{primary_key_name, unique_key_name};
6
7pub trait KeyGenerator {
8    fn key_constraints(&self, table: &Table) -> Vec<String>;
9}
10
11pub struct DefaultKeyGenerator {
12    context: GeneratorContext,
13    nonclustered_primary_key: bool,
14}
15
16impl DefaultKeyGenerator {
17    pub fn new(context: GeneratorContext) -> Self {
18        Self {
19            context,
20            nonclustered_primary_key: false,
21        }
22    }
23
24    /// When set, primary key constraints render `primary key nonclustered (...)` instead of
25    /// `primary key (...)` when another key on the same table has explicitly claimed the
26    /// table's one clustered slot (`cluster="true"`). Has no effect otherwise - dialects
27    /// without a `clustered`/`nonclustered` constraint keyword (Postgres, SQLite) should
28    /// leave this false.
29    pub fn with_nonclustered_primary_key(mut self, value: bool) -> Self {
30        self.nonclustered_primary_key = value;
31        self
32    }
33
34    pub fn context(&self) -> &GeneratorContext {
35        &self.context
36    }
37
38    /// `cluster="true"` only has a rendering on SQL Server (`clustered`/`nonclustered` is a
39    /// SQL Server-only constraint keyword - PostgreSQL and SQLite have nothing equivalent).
40    /// On those dialects the attribute is ignored rather than hard-erroring, since one
41    /// schema.xml is meant to target all three databases and a SQL-Server-only tuning hint
42    /// shouldn't stop the other two from generating (M1).
43    fn effective_cluster(&self, table_name: &str, key_kind: &str, key: &Key) -> bool {
44        if !key.is_cluster() {
45            return false;
46        }
47
48        let database_type = self.context.settings().database_type();
49        if database_type == DatabaseType::SqlServer {
50            true
51        } else {
52            eprintln!(
53                "warning: table '{}' has a clustered {} constraint, but {:?} does not support clustered/nonclustered constraints -- ignoring",
54                table_name, key_kind, database_type
55            );
56            false
57        }
58    }
59
60    /// `compress="true"` on a `<primary>`/`<unique>` key only has a rendering on SQL Server
61    /// (`with (data_compression = page)`) - PostgreSQL and SQLite have no equivalent, so the
62    /// attribute is warned about and ignored there rather than hard-erroring, matching how
63    /// `effective_cluster` and the index generators handle dialect-specific tuning hints (M1).
64    fn effective_compress(&self, table_name: &str, key_kind: &str, key: &Key) -> bool {
65        if !key.is_compress() {
66            return false;
67        }
68
69        let database_type = self.context.settings().database_type();
70        if database_type == DatabaseType::SqlServer {
71            true
72        } else {
73            eprintln!(
74                "warning: table '{}' has a compressed {} constraint, but {:?} does not support key compression -- ignoring",
75                table_name, key_kind, database_type
76            );
77            false
78        }
79    }
80}
81
82impl DefaultKeyGenerator {
83    /// Same as `key_constraints`, but when `skip_primary_key` is true the primary key
84    /// constraint is left out entirely - for dialects (SQLite) that declare the primary key
85    /// inline on the column instead of as a separate table constraint.
86    pub fn key_constraints_filtered(&self, table: &Table, skip_primary_key: bool) -> Vec<String> {
87        let mut constraints = Vec::new();
88        let mut unique_key_counter = 0;
89
90        for key in table.keys() {
91            if key.is_index() {
92                continue;
93            }
94
95            match key.key_type() {
96                schema_model::model::types::KeyType::Primary => {
97                    if skip_primary_key {
98                        continue;
99                    }
100
101                    let database_type = self.context.settings().database_type();
102                    let constraint_name = primary_key_name(database_type, table.name());
103                    // `cluster="true"` always wins over the nonclustered fallback below -
104                    // otherwise a SQL Server primary key explicitly asking to be clustered
105                    // would render the opposite (M1).
106                    //
107                    // `NONCLUSTERED` is only ever emitted here when it's actually needed: a
108                    // table can have at most one clustered index/constraint, so if some other
109                    // key on this table explicitly claims that slot (`cluster="true"`), the PK
110                    // must be pushed off it. Otherwise the PK renders bare and SQL Server's own
111                    // default (`CLUSTERED` for a `PRIMARY KEY` constraint) applies - a plain
112                    // `nonclustered_primary_key` flag once forced this unconditionally, which
113                    // needlessly turned every SQL Server table into a heap even when nothing
114                    // else wanted the clustered slot.
115                    let other_key_is_clustered = self.nonclustered_primary_key
116                        && table.keys().iter().any(|k| {
117                            !k.is_index()
118                                && k.key_type() != schema_model::model::types::KeyType::Primary
119                                && k.is_cluster()
120                        });
121                    let primary_key_clause =
122                        if self.effective_cluster(table.name(), "primary key", key) {
123                            "primary key clustered"
124                        } else if other_key_is_clustered {
125                            "primary key nonclustered"
126                        } else {
127                            "primary key"
128                        };
129                    let compress_clause =
130                        if self.effective_compress(table.name(), "primary key", key) {
131                            " with (data_compression = page)"
132                        } else {
133                            ""
134                        };
135                    constraints.push(format!(
136                        "   constraint {} {} ({}){}",
137                        constraint_name,
138                        primary_key_clause,
139                        key.columns_as_string(),
140                        compress_clause
141                    ));
142                }
143                schema_model::model::types::KeyType::Unique => {
144                    unique_key_counter += 1;
145                    let database_type = self.context.settings().database_type();
146                    let constraint_name =
147                        unique_key_name(database_type, table.name(), unique_key_counter);
148                    let unique_clause = if self.effective_cluster(table.name(), "unique", key) {
149                        "unique clustered"
150                    } else {
151                        "unique"
152                    };
153                    let compress_clause = if self.effective_compress(table.name(), "unique", key) {
154                        " with (data_compression = page)"
155                    } else {
156                        ""
157                    };
158                    constraints.push(format!(
159                        "   constraint {} {} ({}){}",
160                        constraint_name,
161                        unique_clause,
162                        key.columns_as_string(),
163                        compress_clause
164                    ));
165                }
166                schema_model::model::types::KeyType::Index => unreachable!(),
167            }
168        }
169
170        constraints
171    }
172}
173
174impl KeyGenerator for DefaultKeyGenerator {
175    fn key_constraints(&self, table: &Table) -> Vec<String> {
176        self.key_constraints_filtered(table, false)
177    }
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183    use crate::common::test_support::make_context;
184    use schema_model::builder::TableBuilder;
185    use schema_model::model::database_model::DatabaseModel;
186    use schema_model::model::key::Key;
187    use schema_model::model::key::KeyColumn;
188    use schema_model::model::types::{BooleanMode, DatabaseType, ForeignKeyMode, KeyType};
189
190    #[test]
191    fn empty_keys_returns_empty_vec() {
192        let table = TableBuilder::new(None::<&str>, "users").build();
193        let schema = schema_model::builder::SchemaBuilder::new(None::<&str>)
194            .add_table(table.clone())
195            .build();
196        let model =
197            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
198        let (ctx, _buffer) = make_context(model, DatabaseType::Postgresql);
199
200        let generator = DefaultKeyGenerator::new(ctx);
201        assert_eq!(generator.key_constraints(&table), vec![] as Vec<String>);
202    }
203
204    #[test]
205    fn primary_key_single_column() {
206        let pk = Key::new(KeyType::Primary, vec![KeyColumn::new("id")]);
207        let table = TableBuilder::new(None::<&str>, "users").add_key(pk).build();
208        let schema = schema_model::builder::SchemaBuilder::new(None::<&str>)
209            .add_table(table.clone())
210            .build();
211        let model =
212            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
213        let (ctx, _buffer) = make_context(model, DatabaseType::Postgresql);
214
215        let generator = DefaultKeyGenerator::new(ctx);
216        let constraints = generator.key_constraints(&table);
217        assert_eq!(constraints.len(), 1);
218        assert_eq!(constraints[0], "   constraint pk_users primary key (id)");
219    }
220
221    #[test]
222    fn primary_key_multiple_columns() {
223        let pk = Key::new(
224            KeyType::Primary,
225            vec![KeyColumn::new("org_id"), KeyColumn::new("user_id")],
226        );
227        let table = TableBuilder::new(None::<&str>, "users").add_key(pk).build();
228        let schema = schema_model::builder::SchemaBuilder::new(None::<&str>)
229            .add_table(table.clone())
230            .build();
231        let model =
232            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
233        let (ctx, _buffer) = make_context(model, DatabaseType::Postgresql);
234
235        let generator = DefaultKeyGenerator::new(ctx);
236        let constraints = generator.key_constraints(&table);
237        assert_eq!(constraints.len(), 1);
238        assert_eq!(
239            constraints[0],
240            "   constraint pk_users primary key (org_id,user_id)"
241        );
242    }
243
244    #[test]
245    fn unique_key_single_column() {
246        let uq = Key::new(KeyType::Unique, vec![KeyColumn::new("email")]);
247        let table = TableBuilder::new(None::<&str>, "users").add_key(uq).build();
248        let schema = schema_model::builder::SchemaBuilder::new(None::<&str>)
249            .add_table(table.clone())
250            .build();
251        let model =
252            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
253        let (ctx, _buffer) = make_context(model, DatabaseType::Postgresql);
254
255        let generator = DefaultKeyGenerator::new(ctx);
256        let constraints = generator.key_constraints(&table);
257        assert_eq!(constraints.len(), 1);
258        assert_eq!(constraints[0], "   constraint ak_users1 unique (email)");
259    }
260
261    #[test]
262    fn unique_key_multiple_columns() {
263        let uq = Key::new(
264            KeyType::Unique,
265            vec![KeyColumn::new("tenant_id"), KeyColumn::new("code")],
266        );
267        let table = TableBuilder::new(None::<&str>, "products")
268            .add_key(uq)
269            .build();
270        let schema = schema_model::builder::SchemaBuilder::new(None::<&str>)
271            .add_table(table.clone())
272            .build();
273        let model =
274            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
275        let (ctx, _buffer) = make_context(model, DatabaseType::Postgresql);
276
277        let generator = DefaultKeyGenerator::new(ctx);
278        let constraints = generator.key_constraints(&table);
279        assert_eq!(constraints.len(), 1);
280        assert_eq!(
281            constraints[0],
282            "   constraint ak_products1 unique (tenant_id,code)"
283        );
284    }
285
286    #[test]
287    fn multiple_keys_primary_and_unique() {
288        let pk = Key::new(KeyType::Primary, vec![KeyColumn::new("id")]);
289        let uq1 = Key::new(KeyType::Unique, vec![KeyColumn::new("email")]);
290        let uq2 = Key::new(KeyType::Unique, vec![KeyColumn::new("username")]);
291        let table = TableBuilder::new(None::<&str>, "users")
292            .add_key(pk)
293            .add_key(uq1)
294            .add_key(uq2)
295            .build();
296        let schema = schema_model::builder::SchemaBuilder::new(None::<&str>)
297            .add_table(table.clone())
298            .build();
299        let model =
300            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
301        let (ctx, _buffer) = make_context(model, DatabaseType::Postgresql);
302
303        let generator = DefaultKeyGenerator::new(ctx);
304        let constraints = generator.key_constraints(&table);
305        assert_eq!(constraints.len(), 3);
306        assert_eq!(constraints[0], "   constraint pk_users primary key (id)");
307        assert_eq!(constraints[1], "   constraint ak_users1 unique (email)");
308        assert_eq!(constraints[2], "   constraint ak_users2 unique (username)");
309    }
310
311    #[test]
312    fn filters_out_index_keys() {
313        let pk = Key::new(KeyType::Primary, vec![KeyColumn::new("id")]);
314        let idx = Key::new(KeyType::Index, vec![KeyColumn::new("name")]);
315        let table = TableBuilder::new(None::<&str>, "users")
316            .add_key(pk)
317            .add_index(idx)
318            .build();
319        let schema = schema_model::builder::SchemaBuilder::new(None::<&str>)
320            .add_table(table.clone())
321            .build();
322        let model =
323            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
324        let (ctx, _buffer) = make_context(model, DatabaseType::Postgresql);
325
326        let generator = DefaultKeyGenerator::new(ctx);
327        let constraints = generator.key_constraints(&table);
328        // Only primary key should be emitted, index should be filtered
329        assert_eq!(constraints.len(), 1);
330        assert_eq!(constraints[0], "   constraint pk_users primary key (id)");
331    }
332
333    #[test]
334    fn unique_key_numbering_independent_of_primary_key() {
335        let uq1 = Key::new(KeyType::Unique, vec![KeyColumn::new("email")]);
336        let uq2 = Key::new(KeyType::Unique, vec![KeyColumn::new("username")]);
337        let table = TableBuilder::new(None::<&str>, "products")
338            .add_key(uq1)
339            .add_key(uq2)
340            .build();
341        let schema = schema_model::builder::SchemaBuilder::new(None::<&str>)
342            .add_table(table.clone())
343            .build();
344        let model =
345            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
346        let (ctx, _buffer) = make_context(model, DatabaseType::Postgresql);
347
348        let generator = DefaultKeyGenerator::new(ctx);
349        let constraints = generator.key_constraints(&table);
350        assert_eq!(constraints.len(), 2);
351        assert_eq!(constraints[0], "   constraint ak_products1 unique (email)");
352        assert_eq!(
353            constraints[1],
354            "   constraint ak_products2 unique (username)"
355        );
356    }
357
358    #[test]
359    fn constraint_name_truncates_for_long_table_names() {
360        let pk = Key::new(KeyType::Primary, vec![KeyColumn::new("id")]);
361        let uq = Key::new(KeyType::Unique, vec![KeyColumn::new("code")]);
362        let long_table_name = "a".repeat(70); // Exceeds postgres max of 63
363        let table = TableBuilder::new(None::<&str>, &long_table_name)
364            .add_key(pk)
365            .add_key(uq)
366            .build();
367        let schema = schema_model::builder::SchemaBuilder::new(None::<&str>)
368            .add_table(table.clone())
369            .build();
370        let model =
371            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
372        let (ctx, _buffer) = make_context(model, DatabaseType::Postgresql);
373
374        let generator = DefaultKeyGenerator::new(ctx);
375        let constraints = generator.key_constraints(&table);
376        assert_eq!(constraints.len(), 2);
377
378        // pk_* constraint name should be <= 63 chars
379        let pk_constraint = &constraints[0];
380        assert!(pk_constraint.contains("constraint pk_"));
381        assert!(pk_constraint.contains("primary key (id)"));
382        // Extract the constraint name part (between "constraint " and " primary")
383        if let Some(start) = pk_constraint.find("constraint ")
384            && let Some(end) = pk_constraint.find(" primary")
385        {
386            let constraint_name = &pk_constraint[start + 11..end];
387            assert!(
388                constraint_name.len() <= 63,
389                "Constraint name {} exceeds 63 chars",
390                constraint_name
391            );
392        }
393
394        // ak_*1 constraint name should be <= 63 chars
395        let ak_constraint = &constraints[1];
396        assert!(ak_constraint.contains("constraint ak_"));
397        assert!(ak_constraint.contains("unique (code)"));
398        // Extract the constraint name part
399        if let Some(start) = ak_constraint.find("constraint ")
400            && let Some(end) = ak_constraint.find(" unique")
401        {
402            let constraint_name = &ak_constraint[start + 11..end];
403            assert!(
404                constraint_name.len() <= 63,
405                "Constraint name {} exceeds 63 chars",
406                constraint_name
407            );
408        }
409    }
410
411    #[test]
412    fn constraint_name_truncates_multi_byte_table_name_without_panicking() {
413        // Regression test: byte-index slicing panics ("not a char boundary") on
414        // multi-byte UTF-8 once truncation kicks in; truncating by char must not.
415        let pk = Key::new(KeyType::Primary, vec![KeyColumn::new("id")]);
416        let long_table_name = "语".repeat(70);
417        let table = TableBuilder::new(None::<&str>, &long_table_name)
418            .add_key(pk)
419            .build();
420        let schema = schema_model::builder::SchemaBuilder::new(None::<&str>)
421            .add_table(table.clone())
422            .build();
423        let model =
424            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
425        let (ctx, _buffer) = make_context(model, DatabaseType::Postgresql);
426
427        let generator = DefaultKeyGenerator::new(ctx);
428        let constraints = generator.key_constraints(&table);
429        assert_eq!(constraints.len(), 1);
430        assert!(constraints[0].contains("constraint pk_"));
431    }
432
433    #[test]
434    fn with_nonclustered_primary_key_leaves_pk_bare_when_nothing_else_is_clustered() {
435        // Regression test: `nonclustered_primary_key` used to force `nonclustered`
436        // unconditionally on every SQL Server PK, turning tables into heaps even when
437        // nothing else on the table wanted the clustered slot. Since SQL Server's own
438        // default (`CLUSTERED` for a `PRIMARY KEY` constraint) is fine here, no keyword
439        // should be emitted.
440        let pk = Key::new(KeyType::Primary, vec![KeyColumn::new("id")]);
441        let uq = Key::new(KeyType::Unique, vec![KeyColumn::new("email")]);
442        let table = TableBuilder::new(None::<&str>, "users")
443            .add_key(pk)
444            .add_key(uq)
445            .build();
446        let schema = schema_model::builder::SchemaBuilder::new(None::<&str>)
447            .add_table(table.clone())
448            .build();
449        let model =
450            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
451        let (ctx, _buffer) = make_context(model, DatabaseType::SqlServer);
452
453        let generator = DefaultKeyGenerator::new(ctx).with_nonclustered_primary_key(true);
454        let constraints = generator.key_constraints(&table);
455        assert_eq!(constraints.len(), 2);
456        assert_eq!(constraints[0], "   constraint pk_users primary key (id)");
457        assert_eq!(constraints[1], "   constraint ak_users1 unique (email)");
458    }
459
460    #[test]
461    fn with_nonclustered_primary_key_adds_nonclustered_keyword_when_another_key_is_clustered() {
462        // The one case NONCLUSTERED is actually needed: a unique key has claimed the
463        // table's single clustered slot, so the PK must be pushed off it.
464        let pk = Key::new(KeyType::Primary, vec![KeyColumn::new("id")]);
465        let uq = Key::new_full(
466            KeyType::Unique,
467            vec![KeyColumn::new("location_id")],
468            true,
469            false,
470            false,
471            None::<String>,
472        );
473        let table = TableBuilder::new(None::<&str>, "users")
474            .add_key(pk)
475            .add_key(uq)
476            .build();
477        let schema = schema_model::builder::SchemaBuilder::new(None::<&str>)
478            .add_table(table.clone())
479            .build();
480        let model =
481            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
482        let (ctx, _buffer) = make_context(model, DatabaseType::SqlServer);
483
484        let generator = DefaultKeyGenerator::new(ctx).with_nonclustered_primary_key(true);
485        let constraints = generator.key_constraints(&table);
486        assert_eq!(constraints.len(), 2);
487        assert_eq!(
488            constraints[0],
489            "   constraint pk_users primary key nonclustered (id)"
490        );
491        assert_eq!(
492            constraints[1],
493            "   constraint ak_users1 unique clustered (location_id)"
494        );
495    }
496
497    #[test]
498    fn cluster_true_on_sql_server_overrides_nonclustered_primary_key_default() {
499        // Regression test for M1: `sqlserver_key_generator.rs` hard-codes
500        // `with_nonclustered_primary_key(true)`, so `<primary cluster="true">` used to
501        // render `primary key nonclustered` - the exact opposite of what was asked.
502        let pk = Key::new_full(
503            KeyType::Primary,
504            vec![KeyColumn::new("id")],
505            true,
506            false,
507            false,
508            None::<String>,
509        );
510        let table = TableBuilder::new(None::<&str>, "users").add_key(pk).build();
511        let schema = schema_model::builder::SchemaBuilder::new(None::<&str>)
512            .add_table(table.clone())
513            .build();
514        let model =
515            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
516        let (ctx, _buffer) = make_context(model, DatabaseType::SqlServer);
517
518        let generator = DefaultKeyGenerator::new(ctx).with_nonclustered_primary_key(true);
519        let constraints = generator.key_constraints(&table);
520        assert_eq!(
521            constraints,
522            vec!["   constraint pk_users primary key clustered (id)"]
523        );
524    }
525
526    #[test]
527    fn cluster_true_on_sql_server_unique_key_adds_clustered_keyword() {
528        let uq = Key::new_full(
529            KeyType::Unique,
530            vec![KeyColumn::new("email")],
531            true,
532            false,
533            false,
534            None::<String>,
535        );
536        let table = TableBuilder::new(None::<&str>, "users").add_key(uq).build();
537        let schema = schema_model::builder::SchemaBuilder::new(None::<&str>)
538            .add_table(table.clone())
539            .build();
540        let model =
541            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
542        let (ctx, _buffer) = make_context(model, DatabaseType::SqlServer);
543
544        let generator = DefaultKeyGenerator::new(ctx);
545        let constraints = generator.key_constraints(&table);
546        assert_eq!(
547            constraints,
548            vec!["   constraint ak_users1 unique clustered (email)"]
549        );
550    }
551
552    #[test]
553    fn cluster_true_is_ignored_on_dialects_without_clustered_constraints() {
554        // PostgreSQL/SQLite have no clustered/nonclustered constraint syntax - `cluster`
555        // is ignored (with a warning) rather than rendering invalid SQL (M1).
556        let pk = Key::new_full(
557            KeyType::Primary,
558            vec![KeyColumn::new("id")],
559            true,
560            false,
561            false,
562            None::<String>,
563        );
564        let uq = Key::new_full(
565            KeyType::Unique,
566            vec![KeyColumn::new("email")],
567            true,
568            false,
569            false,
570            None::<String>,
571        );
572        let table = TableBuilder::new(None::<&str>, "users")
573            .add_key(pk)
574            .add_key(uq)
575            .build();
576        let schema = schema_model::builder::SchemaBuilder::new(None::<&str>)
577            .add_table(table.clone())
578            .build();
579        let model =
580            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
581        let (ctx, _buffer) = make_context(model, DatabaseType::Postgresql);
582
583        let generator = DefaultKeyGenerator::new(ctx);
584        let constraints = generator.key_constraints(&table);
585        assert_eq!(constraints[0], "   constraint pk_users primary key (id)");
586        assert_eq!(constraints[1], "   constraint ak_users1 unique (email)");
587    }
588
589    #[test]
590    fn compress_true_on_sql_server_adds_data_compression_clause() {
591        let pk = Key::new_full(
592            KeyType::Primary,
593            vec![KeyColumn::new("id")],
594            false,
595            true,
596            false,
597            None::<String>,
598        );
599        let uq = Key::new_full(
600            KeyType::Unique,
601            vec![KeyColumn::new("email")],
602            false,
603            true,
604            false,
605            None::<String>,
606        );
607        let table = TableBuilder::new(None::<&str>, "users")
608            .add_key(pk)
609            .add_key(uq)
610            .build();
611        let schema = schema_model::builder::SchemaBuilder::new(None::<&str>)
612            .add_table(table.clone())
613            .build();
614        let model =
615            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
616        let (ctx, _buffer) = make_context(model, DatabaseType::SqlServer);
617
618        let generator = DefaultKeyGenerator::new(ctx).with_nonclustered_primary_key(true);
619        let constraints = generator.key_constraints(&table);
620        assert_eq!(
621            constraints[0],
622            "   constraint pk_users primary key (id) with (data_compression = page)"
623        );
624        assert_eq!(
625            constraints[1],
626            "   constraint ak_users1 unique (email) with (data_compression = page)"
627        );
628    }
629
630    #[test]
631    fn compress_true_combines_with_clustered_keyword() {
632        let pk = Key::new_full(
633            KeyType::Primary,
634            vec![KeyColumn::new("id")],
635            true,
636            true,
637            false,
638            None::<String>,
639        );
640        let table = TableBuilder::new(None::<&str>, "users").add_key(pk).build();
641        let schema = schema_model::builder::SchemaBuilder::new(None::<&str>)
642            .add_table(table.clone())
643            .build();
644        let model =
645            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
646        let (ctx, _buffer) = make_context(model, DatabaseType::SqlServer);
647
648        let generator = DefaultKeyGenerator::new(ctx).with_nonclustered_primary_key(true);
649        let constraints = generator.key_constraints(&table);
650        assert_eq!(
651            constraints,
652            vec![
653                "   constraint pk_users primary key clustered (id) with (data_compression = page)"
654            ]
655        );
656    }
657
658    #[test]
659    fn compress_true_is_ignored_on_dialects_without_key_compression() {
660        // PostgreSQL/SQLite have no key-level compression syntax - `compress` is ignored
661        // (with a warning) rather than rendering invalid SQL, matching `cluster` handling (M1).
662        let pk = Key::new_full(
663            KeyType::Primary,
664            vec![KeyColumn::new("id")],
665            false,
666            true,
667            false,
668            None::<String>,
669        );
670        let uq = Key::new_full(
671            KeyType::Unique,
672            vec![KeyColumn::new("email")],
673            false,
674            true,
675            false,
676            None::<String>,
677        );
678        let table = TableBuilder::new(None::<&str>, "users")
679            .add_key(pk)
680            .add_key(uq)
681            .build();
682        let schema = schema_model::builder::SchemaBuilder::new(None::<&str>)
683            .add_table(table.clone())
684            .build();
685        let model =
686            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
687        let (ctx, _buffer) = make_context(model, DatabaseType::Postgresql);
688
689        let generator = DefaultKeyGenerator::new(ctx);
690        let constraints = generator.key_constraints(&table);
691        assert_eq!(constraints[0], "   constraint pk_users primary key (id)");
692        assert_eq!(constraints[1], "   constraint ak_users1 unique (email)");
693    }
694}