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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
// Copyright (c) 2026, Salesforce, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Table definition types.
use std::borrow::Cow;
use crate::error::{Error, Result};
use hyperdb_api_core::types::{ColumnDefinition as TypesColumnDefinition, Nullability, SqlType};
/// Possible persistence levels for database objects.
///
/// This enum controls whether a table is permanent (persisted to disk) or
/// temporary (only available in the current session).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Persistence {
/// Permanent: The table is persisted to disk and survives session restarts.
#[default]
Permanent,
/// Temporary: The table only exists for the current session and is not persisted.
Temporary,
}
impl std::fmt::Display for Persistence {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Persistence::Permanent => write!(f, "Permanent"),
Persistence::Temporary => write!(f, "Temporary"),
}
}
}
/// Internal representation of a column's SQL type.
///
/// This enum ensures a single source of truth for the type - either a structured
/// `SqlType` or a raw string type name.
#[derive(Debug, Clone)]
enum SqlTypeOrName {
/// Structured SQL type with full type information.
SqlType(SqlType),
/// Raw string type name (used when `SqlType` is unavailable, e.g., from catalog queries).
TypeName(String),
}
impl SqlTypeOrName {
/// Returns the type name as a string.
///
/// Returns a borrowed reference for `TypeName` variant to avoid allocation,
/// and an owned string for `SqlType` variant (requires formatting).
fn type_name(&self) -> Cow<'_, str> {
match self {
SqlTypeOrName::SqlType(t) => Cow::Owned(t.to_string()),
SqlTypeOrName::TypeName(s) => Cow::Borrowed(s),
}
}
/// Returns the SQL type if this is a structured type.
fn sql_type(&self) -> Option<SqlType> {
match self {
SqlTypeOrName::SqlType(t) => Some(*t),
SqlTypeOrName::TypeName(_) => None,
}
}
}
/// A column definition.
///
/// This struct supports both string-based type names (for simplicity) and
/// SqlType-based definitions (for type safety). Internally, it uses a single source
/// of truth to avoid synchronization issues.
#[derive(Debug, Clone)]
pub struct ColumnDefinition {
/// Column name.
pub name: String,
/// SQL type representation (either structured `SqlType` or raw string).
sql_type_or_name: SqlTypeOrName,
/// Whether the column is nullable.
pub nullable: bool,
/// The collation for text columns (e.g., "`en_US`", "binary").
collation: Option<String>,
}
impl ColumnDefinition {
/// Creates a new column definition using a type name string.
///
/// # Example
///
/// ```
/// use hyperdb_api::ColumnDefinition;
///
/// let col = ColumnDefinition::new("id", "INT", false);
/// assert_eq!(col.name, "id");
/// assert_eq!(col.type_name(), "INT");
/// ```
pub fn new(name: impl Into<String>, type_name: impl Into<String>, nullable: bool) -> Self {
ColumnDefinition {
name: name.into(),
sql_type_or_name: SqlTypeOrName::TypeName(type_name.into()),
nullable,
collation: None,
}
}
/// Creates a column definition using `SqlType`.
///
/// # Example
///
/// ```
/// use hyperdb_api::ColumnDefinition;
/// use hyperdb_api_core::types::{SqlType, Nullability};
///
/// let col = ColumnDefinition::with_sql_type("id", SqlType::int(), Nullability::NotNullable);
/// assert_eq!(col.name, "id");
/// assert!(!col.nullable);
/// ```
pub fn with_sql_type(
name: impl Into<String>,
sql_type: SqlType,
nullability: Nullability,
) -> Self {
ColumnDefinition {
name: name.into(),
sql_type_or_name: SqlTypeOrName::SqlType(sql_type),
nullable: nullability.is_nullable(),
collation: None,
}
}
/// Creates a column definition with a collation.
///
/// The collation specifies the sorting and comparison behavior for text columns.
///
/// # Example
///
/// ```
/// use hyperdb_api::ColumnDefinition;
/// use hyperdb_api_core::types::{SqlType, Nullability};
///
/// let col = ColumnDefinition::with_collation("name", SqlType::text(), "en_US", Nullability::Nullable);
/// assert_eq!(col.collation(), Some("en_US"));
/// ```
pub fn with_collation(
name: impl Into<String>,
sql_type: SqlType,
collation: impl Into<String>,
nullability: Nullability,
) -> Self {
ColumnDefinition {
name: name.into(),
sql_type_or_name: SqlTypeOrName::SqlType(sql_type),
nullable: nullability.is_nullable(),
collation: Some(collation.into()),
}
}
/// Creates a nullable column definition using `SqlType`.
pub fn nullable(name: impl Into<String>, sql_type: SqlType) -> Self {
Self::with_sql_type(name, sql_type, Nullability::Nullable)
}
/// Creates a non-nullable column definition using `SqlType`.
pub fn not_null(name: impl Into<String>, sql_type: SqlType) -> Self {
Self::with_sql_type(name, sql_type, Nullability::NotNullable)
}
/// Returns the nullability as a Nullability enum.
#[must_use]
pub fn nullability(&self) -> Nullability {
if self.nullable {
Nullability::Nullable
} else {
Nullability::NotNullable
}
}
/// Returns the SQL type if this column was created with a structured type.
#[must_use]
pub fn sql_type(&self) -> Option<SqlType> {
self.sql_type_or_name.sql_type()
}
/// Returns the type name string representation.
///
/// When created with `SqlType`, this is derived from it. Otherwise, it's the
/// string provided during construction.
///
/// Returns `Cow<str>` to avoid allocation when the type name is already stored
/// as a string internally.
#[must_use]
pub fn type_name(&self) -> Cow<'_, str> {
self.sql_type_or_name.type_name()
}
/// Returns the collation if set.
#[must_use]
pub fn collation(&self) -> Option<&str> {
self.collation.as_deref()
}
/// Sets the collation for this column.
pub fn set_collation(&mut self, collation: impl Into<String>) {
self.collation = Some(collation.into());
}
/// Sets the SQL type, replacing any previous type information.
///
/// This replaces the internal type representation with the provided `SqlType`.
pub fn set_sql_type(&mut self, sql_type: SqlType) {
self.sql_type_or_name = SqlTypeOrName::SqlType(sql_type);
}
/// Converts to the hyper-types `ColumnDefinition` (if `SqlType` is set).
#[must_use]
pub fn to_types_column_definition(&self) -> Option<TypesColumnDefinition> {
self.sql_type()
.map(|sql_type| TypesColumnDefinition::new(&self.name, sql_type, self.nullability()))
}
}
impl From<TypesColumnDefinition> for ColumnDefinition {
fn from(col: TypesColumnDefinition) -> Self {
ColumnDefinition {
name: col.name.clone(),
sql_type_or_name: SqlTypeOrName::SqlType(col.sql_type),
nullable: col.nullability.is_nullable(),
collation: None,
}
}
}
/// A table definition.
///
/// This struct defines the schema of a table including its name, optional schema
/// and database names, and column definitions.
///
/// # Example
///
/// Using the fluent builder pattern:
///
/// ```
/// use hyperdb_api::{TableDefinition, Result};
/// use hyperdb_api_core::types::{SqlType, Nullability};
///
/// # fn main() -> Result<()> {
/// let table = TableDefinition::new("users")
/// .add_required_column("id", SqlType::int())
/// .add_nullable_column("name", SqlType::text());
///
/// let sql = table.to_create_sql(true)?;
/// assert!(sql.contains("CREATE TABLE"));
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
#[must_use = "TableDefinition uses a consuming builder pattern - each method takes ownership and returns a new instance. You must use the returned value or your table definition changes will be lost"]
pub struct TableDefinition {
/// Table name.
pub name: String,
/// Schema name.
pub schema: Option<String>,
/// Database name.
pub database: Option<String>,
/// Column definitions.
pub columns: Vec<ColumnDefinition>,
/// Table persistence (permanent or temporary).
persistence: Persistence,
}
impl Default for TableDefinition {
fn default() -> Self {
Self::new("unnamed_table")
}
}
impl From<&str> for TableDefinition {
fn from(name: &str) -> Self {
Self::new(name)
}
}
impl From<String> for TableDefinition {
fn from(name: String) -> Self {
Self::new(name)
}
}
impl TableDefinition {
/// Creates a new table definition.
pub fn new(name: impl Into<String>) -> Self {
TableDefinition {
name: name.into(),
schema: None,
database: None,
columns: Vec::new(),
persistence: Persistence::Permanent,
}
}
/// Creates a table definition from a validated `TableName`.
///
/// This constructor uses a pre-validated `TableName`, ensuring all name components
/// have already passed validation (non-empty, within length limits).
///
/// # Example
///
/// ```
/// use hyperdb_api::{TableDefinition, TableName};
/// use hyperdb_api_core::types::{SqlType, Nullability};
///
/// // First create a validated TableName
/// let table_name = TableName::try_new("users")?
/// .with_schema("public")?
/// .with_database("mydb")?;
///
/// // Then create TableDefinition from it
/// let table = TableDefinition::from_table_name(table_name)?
/// .add_required_column("id", SqlType::int());
///
/// assert_eq!(table.name, "users");
/// assert_eq!(table.schema, Some("public".to_string()));
/// assert_eq!(table.database, Some("mydb".to_string()));
///
/// // Direct conversion from string also works
/// let table2 = TableDefinition::from_table_name("public.users")?;
/// assert_eq!(table2.schema, Some("public".to_string()));
/// # Ok::<(), hyperdb_api::Error>(())
/// ```
///
/// # Errors
///
/// Returns the conversion error (typically [`Error::InvalidName`]) if
/// `table_name` cannot be parsed into a
/// [`TableName`](crate::TableName).
pub fn from_table_name<T>(table_name: T) -> Result<Self>
where
T: TryInto<crate::TableName>,
crate::Error: From<T::Error>,
{
let table_name = table_name.try_into()?;
Ok(TableDefinition {
name: table_name.table().unescaped().to_string(),
schema: table_name.schema().map(|s| s.unescaped().to_string()),
database: table_name.database().map(|d| d.unescaped().to_string()),
columns: Vec::new(),
persistence: Persistence::Permanent,
})
}
/// Sets the schema name (fluent builder pattern).
///
/// # Example
///
/// ```
/// use hyperdb_api::TableDefinition;
/// use hyperdb_api_core::types::{SqlType, Nullability};
///
/// let table = TableDefinition::new("Extract")
/// .with_schema("Extract")
/// .add_required_column("id", SqlType::int());
/// ```
pub fn with_schema(mut self, schema: impl Into<String>) -> Self {
self.schema = Some(schema.into());
self
}
/// Sets the database name (fluent builder pattern).
pub fn with_database(mut self, database: impl Into<String>) -> Self {
self.database = Some(database.into());
self
}
/// Sets the persistence (fluent builder pattern).
///
/// # Example
///
/// ```
/// use hyperdb_api::{TableDefinition, Persistence};
/// use hyperdb_api_core::types::SqlType;
///
/// let temp_table = TableDefinition::new("temp_data")
/// .with_persistence(Persistence::Temporary)
/// .add_required_column("id", SqlType::int());
/// assert_eq!(temp_table.get_persistence(), Persistence::Temporary);
/// ```
pub fn with_persistence(mut self, persistence: Persistence) -> Self {
self.persistence = persistence;
self
}
/// Returns the persistence setting.
#[must_use]
pub fn get_persistence(&self) -> Persistence {
self.persistence
}
/// Sets the persistence.
pub fn set_persistence(&mut self, persistence: Persistence) {
self.persistence = persistence;
}
/// Adds a column to the table definition (fluent builder pattern).
///
/// This is an internal method. Use `add_nullable_column()` or `add_required_column()` instead.
#[expect(
dead_code,
reason = "called from the `table!` declarative macro; not invoked by the crate itself"
)]
pub(crate) fn add_column(
mut self,
name: impl Into<String>,
sql_type: SqlType,
nullability: Nullability,
) -> Self {
self.columns
.push(ColumnDefinition::with_sql_type(name, sql_type, nullability));
self
}
/// Adds a nullable column using `SqlType` (fluent builder pattern).
///
/// # Example
///
/// ```
/// use hyperdb_api::TableDefinition;
/// use hyperdb_api_core::types::SqlType;
///
/// let table = TableDefinition::new("products")
/// .add_nullable_column("name", SqlType::text())
/// .add_nullable_column("price", SqlType::numeric(18, 2));
/// ```
pub fn add_nullable_column(mut self, name: impl Into<String>, sql_type: SqlType) -> Self {
self.columns.push(ColumnDefinition::with_sql_type(
name,
sql_type,
Nullability::Nullable,
));
self
}
/// Adds a required (non-nullable) column using `SqlType` (fluent builder pattern).
///
/// # Example
///
/// ```
/// use hyperdb_api::TableDefinition;
/// use hyperdb_api_core::types::SqlType;
///
/// let table = TableDefinition::new("products")
/// .add_required_column("id", SqlType::int())
/// .add_required_column("name", SqlType::text());
/// ```
pub fn add_required_column(mut self, name: impl Into<String>, sql_type: SqlType) -> Self {
self.columns.push(ColumnDefinition::with_sql_type(
name,
sql_type,
Nullability::NotNullable,
));
self
}
/// Adds a column with a collation (fluent builder pattern).
///
/// This is an internal method. Use `add_nullable_column_with_collation()` or `add_required_column_with_collation()` instead.
#[expect(
dead_code,
reason = "called from the `table!` declarative macro; not invoked by the crate itself"
)]
pub(crate) fn add_column_with_collation(
mut self,
name: impl Into<String>,
sql_type: SqlType,
collation: impl Into<String>,
nullability: Nullability,
) -> Self {
self.columns.push(ColumnDefinition::with_collation(
name,
sql_type,
collation,
nullability,
));
self
}
/// Adds a nullable column with a collation (fluent builder pattern).
///
/// # Example
///
/// ```
/// use hyperdb_api::TableDefinition;
/// use hyperdb_api_core::types::SqlType;
///
/// let table = TableDefinition::new("products")
/// .add_nullable_column_with_collation("name", SqlType::text(), "en_US");
/// ```
pub fn add_nullable_column_with_collation(
mut self,
name: impl Into<String>,
sql_type: SqlType,
collation: impl Into<String>,
) -> Self {
self.columns.push(ColumnDefinition::with_collation(
name,
sql_type,
collation,
Nullability::Nullable,
));
self
}
/// Adds a required (non-nullable) column with a collation (fluent builder pattern).
///
/// # Example
///
/// ```
/// use hyperdb_api::TableDefinition;
/// use hyperdb_api_core::types::SqlType;
///
/// let table = TableDefinition::new("products")
/// .add_required_column_with_collation("name", SqlType::text(), "en_US");
/// ```
pub fn add_required_column_with_collation(
mut self,
name: impl Into<String>,
sql_type: SqlType,
collation: impl Into<String>,
) -> Self {
self.columns.push(ColumnDefinition::with_collation(
name,
sql_type,
collation,
Nullability::NotNullable,
));
self
}
/// Adds a `ColumnDefinition` directly (fluent builder pattern).
pub fn add_column_def(mut self, column: ColumnDefinition) -> Self {
self.columns.push(column);
self
}
/// Adds a column with raw type string (internal use).
#[expect(
dead_code,
reason = "retained for catalog reflection paths that pass string type names"
)]
pub(crate) fn add_column_raw(&mut self, name: &str, type_name: &str, nullable: bool) {
// Map the Hyper type name to SqlType if possible
let sql_type_or_name = Self::type_name_to_sql_type(type_name).map_or_else(
|| SqlTypeOrName::TypeName(type_name.to_string()),
SqlTypeOrName::SqlType,
);
self.columns.push(ColumnDefinition {
name: name.to_string(),
sql_type_or_name,
nullable,
collation: None,
});
}
/// Adds a column with a pre-constructed `SqlType` (internal use).
///
/// This is used by the catalog when it has OID and type modifier information
/// to construct the proper `SqlType` with precision/scale.
pub(crate) fn add_column_with_sql_type(
&mut self,
name: &str,
sql_type: SqlType,
nullable: bool,
) {
self.columns.push(ColumnDefinition {
name: name.to_string(),
sql_type_or_name: SqlTypeOrName::SqlType(sql_type),
nullable,
collation: None,
});
}
/// Maps a Hyper type name from `pg_type` to `SqlType`.
#[allow(
dead_code,
reason = "helper used only by `add_column_raw`, which is itself gated on macro use"
)]
fn type_name_to_sql_type(type_name: &str) -> Option<SqlType> {
// Hyper uses PostgreSQL-style type names
match type_name.to_lowercase().as_str() {
"integer" | "int4" | "int" => Some(SqlType::int()),
"smallint" | "int2" => Some(SqlType::small_int()),
"bigint" | "int8" => Some(SqlType::big_int()),
"double precision" | "float8" => Some(SqlType::double()),
"real" | "float4" => Some(SqlType::float()),
"text" => Some(SqlType::text()),
"boolean" | "bool" => Some(SqlType::bool()),
"date" => Some(SqlType::date()),
"time" | "time without time zone" => Some(SqlType::time()),
"timestamp" | "timestamp without time zone" => Some(SqlType::timestamp()),
"timestamptz" | "timestamp with time zone" => Some(SqlType::timestamp_tz()),
"bytea" => Some(SqlType::bytes()),
"numeric" => Some(SqlType::numeric(38, 0)), // Default precision/scale
"json" => Some(SqlType::json()),
"geography" => Some(SqlType::tabgeography()),
s if s.starts_with("varchar") || s.starts_with("character varying") => {
Some(SqlType::varchar(Some(1000))) // Default max length
}
s if s.starts_with("char") || s.starts_with("character") => {
Some(SqlType::char(1)) // Default length
}
_ => None,
}
}
/// Returns the number of columns.
#[must_use]
pub fn column_count(&self) -> usize {
self.columns.len()
}
/// Returns the column definitions.
#[must_use]
pub fn columns(&self) -> &[ColumnDefinition] {
&self.columns
}
/// Returns the column at the given position.
///
/// # Panics
///
/// Panics if the index is out of bounds.
#[must_use]
pub fn column(&self, index: usize) -> &ColumnDefinition {
&self.columns[index]
}
/// Returns the column with the given name, if it exists.
#[must_use]
pub fn column_by_name(&self, name: &str) -> Option<&ColumnDefinition> {
self.columns.iter().find(|c| c.name == name)
}
/// Returns the position of the column with the given name.
#[must_use]
pub fn column_position_by_name(&self, name: &str) -> Option<usize> {
self.columns.iter().position(|c| c.name == name)
}
/// Returns the table name (unqualified, escaped).
///
/// This returns just the table name portion, properly escaped for use in SQL.
///
/// # Example
///
/// ```
/// use hyperdb_api::TableDefinition;
///
/// let table = TableDefinition::new("Extract").with_schema("Extract");
/// // "Extract" is quoted because it contains uppercase letters (to preserve case)
/// assert_eq!(table.table_name(), "\"Extract\"");
/// ```
#[must_use]
pub fn table_name(&self) -> String {
format!("{}", SqlIdentifier(&self.name))
}
/// Returns the schema name (escaped), if set.
#[must_use]
pub fn schema_name(&self) -> Option<String> {
self.schema
.as_ref()
.map(|s| format!("{}", SqlIdentifier(s)))
}
/// Returns the database name (escaped), if set.
#[must_use]
pub fn database_name(&self) -> Option<String> {
self.database
.as_ref()
.map(|s| format!("{}", SqlIdentifier(s)))
}
/// Returns the qualified table name (escaped).
///
/// Format: `database.schema.table` (if all parts are set, unquoted if valid identifiers)
#[must_use]
pub fn qualified_name(&self) -> String {
match (&self.database, &self.schema) {
(Some(db), Some(schema)) => format!(
"{}.{}.{}",
SqlIdentifier(db),
SqlIdentifier(schema),
SqlIdentifier(&self.name)
),
(None, Some(schema)) => {
format!("{}.{}", SqlIdentifier(schema), SqlIdentifier(&self.name))
}
(Some(db), None) => format!("{}.{}", SqlIdentifier(db), SqlIdentifier(&self.name)),
(None, None) => format!("{}", SqlIdentifier(&self.name)),
}
}
/// Sets the table name.
pub fn set_table_name(&mut self, name: impl Into<String>) {
self.name = name.into();
}
/// Converts this `TableDefinition` to a validated `TableName`.
///
/// This method validates all name components (table, schema, database) and returns
/// a type-safe `TableName`. Use this when you need to ensure the names are valid.
///
/// # Errors
///
/// Returns an error if any name component is empty or exceeds the `PostgreSQL` identifier limit.
///
/// # Example
///
/// ```
/// use hyperdb_api::TableDefinition;
///
/// let table = TableDefinition::new("users")
/// .with_schema("public")
/// .with_database("mydb");
///
/// // Validate all names
/// let table_name = table.to_table_name()?;
/// assert_eq!(table_name.to_string(), "\"mydb\".\"public\".\"users\"");
/// # Ok::<(), hyperdb_api::Error>(())
/// ```
pub fn to_table_name(&self) -> Result<crate::TableName> {
let mut table = crate::TableName::try_new(&self.name)?;
if let Some(ref schema) = self.schema {
table = table.with_schema(schema)?;
}
if let Some(ref database) = self.database {
table = table.with_database(database)?;
}
Ok(table)
}
/// Generates CREATE TABLE SQL.
///
/// # Arguments
///
/// * `fail_if_exists` - If true, the statement will fail if the table exists.
/// If false, uses CREATE TABLE IF NOT EXISTS.
///
/// # Example
///
/// ```
/// use hyperdb_api::{TableDefinition, Result};
/// use hyperdb_api_core::types::{SqlType, Nullability};
///
/// # fn main() -> Result<()> {
/// let table = TableDefinition::new("users")
/// .add_required_column("id", SqlType::int());
///
/// let sql = table.to_create_sql(true)?;
/// assert_eq!(sql, r#"CREATE TABLE users (id INTEGER NOT NULL)"#);
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns [`Error::Other`] with message
/// `"Table must have at least one column"` if this definition has no
/// columns.
pub fn to_create_sql(&self, fail_if_exists: bool) -> Result<String> {
if self.columns.is_empty() {
return Err(Error::new("Table must have at least one column"));
}
let mut sql = String::new();
// Handle temporary tables
let create_keyword = match self.persistence {
Persistence::Permanent => {
if fail_if_exists {
"CREATE TABLE "
} else {
"CREATE TABLE IF NOT EXISTS "
}
}
Persistence::Temporary => {
if fail_if_exists {
"CREATE TEMPORARY TABLE "
} else {
"CREATE TEMPORARY TABLE IF NOT EXISTS "
}
}
};
sql.push_str(create_keyword);
sql.push_str(&self.qualified_name());
sql.push_str(" (");
for (i, col) in self.columns.iter().enumerate() {
if i > 0 {
sql.push_str(", ");
}
// Always quote column names in CREATE TABLE to preserve case
// (PostgreSQL/Hyper case-folds unquoted identifiers to lowercase)
// Note: write! to String is infallible, so we can ignore the Result
let _ = write!(sql, "{} {}", SqlIdentifier(&col.name), col.type_name());
// Add collation if specified
if let Some(collation) = &col.collation {
let _ = write!(sql, " COLLATE {}", SqlIdentifier(collation));
}
if !col.nullable {
sql.push_str(" NOT NULL");
}
}
sql.push(')');
Ok(sql)
}
/// Generates DROP TABLE SQL.
///
/// # Arguments
///
/// * `fail_if_not_exists` - If true, the statement will fail if the table doesn't exist.
/// If false, uses DROP TABLE IF EXISTS.
#[must_use]
pub fn to_drop_sql(&self, fail_if_not_exists: bool) -> String {
let mut sql = String::new();
if fail_if_not_exists {
sql.push_str("DROP TABLE ");
} else {
sql.push_str("DROP TABLE IF EXISTS ");
}
sql.push_str(&self.qualified_name());
sql
}
}
use hyperdb_api_core::protocol::escape::SqlIdentifier;
use std::fmt::Write;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_create_sql() {
let table = TableDefinition::new("users")
.add_required_column("id", SqlType::int())
.add_nullable_column("name", SqlType::text());
let sql = table.to_create_sql(true).unwrap();
assert_eq!(sql, r"CREATE TABLE users (id INTEGER NOT NULL, name TEXT)");
// Verify type_name accessor works
assert_eq!(table.columns[0].type_name(), "INTEGER");
assert_eq!(table.columns[1].type_name(), "TEXT");
}
#[test]
fn test_create_sql_with_numeric() {
let table = TableDefinition::new("products")
.add_required_column("id", SqlType::int())
.add_nullable_column("name", SqlType::text())
.add_nullable_column("price", SqlType::numeric(18, 2));
let sql = table.to_create_sql(true).unwrap();
assert_eq!(
sql,
r"CREATE TABLE products (id INTEGER NOT NULL, name TEXT, price NUMERIC(18, 2))"
);
}
#[test]
fn test_qualified_name() {
let table = TableDefinition::new("users")
.with_schema("public")
.with_database("mydb");
assert_eq!(table.qualified_name(), r"mydb.public.users");
}
#[test]
fn test_table_name() {
let table = TableDefinition::new("Extract").with_schema("Extract");
// "Extract" is quoted because it contains uppercase letters (to preserve case)
assert_eq!(table.table_name(), r#""Extract""#);
}
#[test]
fn test_drop_sql() {
let table = TableDefinition::new("users");
assert_eq!(table.to_drop_sql(true), r"DROP TABLE users");
assert_eq!(table.to_drop_sql(false), r"DROP TABLE IF EXISTS users");
}
#[test]
fn test_column_definition_helpers() {
let not_null = ColumnDefinition::not_null("id", SqlType::int());
assert!(!not_null.nullable);
let nullable = ColumnDefinition::nullable("name", SqlType::text());
assert!(nullable.nullable);
}
#[test]
fn test_persistence() {
let perm = TableDefinition::new("data");
assert_eq!(perm.get_persistence(), Persistence::Permanent);
let temp = TableDefinition::new("temp_data").with_persistence(Persistence::Temporary);
assert_eq!(temp.get_persistence(), Persistence::Temporary);
}
#[test]
fn test_temporary_table_sql() {
let table = TableDefinition::new("temp_data")
.with_persistence(Persistence::Temporary)
.add_required_column("id", SqlType::int());
let sql = table.to_create_sql(true).unwrap();
assert_eq!(
sql,
r"CREATE TEMPORARY TABLE temp_data (id INTEGER NOT NULL)"
);
}
#[test]
fn test_collation() {
let col = ColumnDefinition::with_collation(
"name",
SqlType::text(),
"en_US",
Nullability::Nullable,
);
assert_eq!(col.collation(), Some("en_US"));
}
#[test]
fn test_column_with_collation_sql() {
let table = TableDefinition::new("users").add_nullable_column_with_collation(
"name",
SqlType::text(),
"en_US",
);
let sql = table.to_create_sql(true).unwrap();
// "en_US" is quoted because it contains uppercase letters (to preserve case)
assert!(sql.contains(r#"COLLATE "en_US""#));
}
#[test]
fn test_column_lookup() {
let table = TableDefinition::new("users")
.add_required_column("id", SqlType::int())
.add_nullable_column("name", SqlType::text());
assert!(table.column_by_name("id").is_some());
assert!(table.column_by_name("nonexistent").is_none());
assert_eq!(table.column_position_by_name("name"), Some(1));
}
#[test]
fn test_fluent_builder_pattern() {
// This test demonstrates the fluent builder pattern
let table = TableDefinition::new("Extract")
.with_schema("Extract")
.add_required_column("Customer ID", SqlType::text())
.add_required_column("Customer Name", SqlType::text())
.add_required_column("Loyalty Reward Points", SqlType::big_int())
.add_required_column("Segment", SqlType::text());
assert_eq!(table.column_count(), 4);
assert_eq!(table.schema, Some("Extract".to_string()));
assert_eq!(table.name, "Extract");
}
}