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
//! Protobuf exporter for generating .proto files from data models.
//!
//! # Security
//!
//! All identifiers are sanitized to comply with Protobuf naming rules.
//! Reserved words are prefixed with an underscore to avoid conflicts.
use super::{ExportError, ExportResult};
use crate::models::{DataModel, Table};
/// Protobuf reserved words that cannot be used as field names.
const PROTOBUF_RESERVED: &[&str] = &[
"syntax",
"import",
"weak",
"public",
"package",
"option",
"message",
"enum",
"service",
"extend",
"extensions",
"reserved",
"to",
"max",
"repeated",
"optional",
"required",
"group",
"oneof",
"map",
"returns",
"rpc",
"stream",
"true",
"false",
];
/// Exporter for Protobuf format.
pub struct ProtobufExporter;
impl ProtobufExporter {
/// Export tables to Protobuf format (SDK interface).
///
/// # Arguments
///
/// * `tables` - Slice of tables to export
///
/// # Returns
///
/// An `ExportResult` containing Protobuf `.proto` file content (proto3 by default).
///
/// # Example
///
/// ```rust
/// use data_modelling_core::export::protobuf::ProtobufExporter;
/// use data_modelling_core::models::{Table, Column};
///
/// let tables = vec![
/// Table::new("User".to_string(), vec![Column::new("id".to_string(), "INT64".to_string())]),
/// ];
///
/// let exporter = ProtobufExporter;
/// let result = exporter.export(&tables).unwrap();
/// assert_eq!(result.format, "protobuf");
/// assert!(result.content.contains("syntax = \"proto3\""));
/// ```
pub fn export(&self, tables: &[Table]) -> Result<ExportResult, ExportError> {
self.export_with_version(tables, "proto3")
}
/// Export tables to Protobuf format with specified version.
///
/// # Arguments
///
/// * `tables` - Slice of tables to export
/// * `version` - Protobuf syntax version ("proto2" or "proto3")
///
/// # Returns
///
/// An `ExportResult` containing Protobuf `.proto` file content.
pub fn export_with_version(
&self,
tables: &[Table],
version: &str,
) -> Result<ExportResult, ExportError> {
if version != "proto2" && version != "proto3" {
return Err(ExportError::InvalidArgument(format!(
"Invalid protobuf version: {}. Must be 'proto2' or 'proto3'",
version
)));
}
let proto = Self::export_model_from_tables_with_version(tables, version);
Ok(ExportResult {
content: proto,
format: "protobuf".to_string(),
})
}
fn export_model_from_tables_with_version(tables: &[Table], version: &str) -> String {
let mut proto = String::new();
proto.push_str(&format!("syntax = \"{}\";\n\n", version));
proto.push_str("package com.datamodel;\n\n");
let mut field_number = 0u32;
for table in tables {
proto.push_str(&Self::export_table_with_version(
table,
&mut field_number,
version,
));
proto.push('\n');
}
proto
}
/// Export tags as Protobuf comments.
fn export_tags_as_comments(tags: &[crate::models::Tag]) -> String {
if tags.is_empty() {
return String::new();
}
let tag_strings: Vec<String> = tags.iter().map(|t| t.to_string()).collect();
format!(" // tags: {}\n", tag_strings.join(", "))
}
/// Export a table to Protobuf message format.
///
/// # Arguments
///
/// * `table` - The table to export
/// * `field_number` - Mutable reference to field number counter (incremented for each field)
///
/// # Returns
///
/// A Protobuf message definition as a string.
///
/// # Example
///
/// ```rust
/// use data_modelling_core::export::protobuf::ProtobufExporter;
/// use data_modelling_core::models::{Table, Column};
///
/// let table = Table::new(
/// "User".to_string(),
/// vec![Column::new("id".to_string(), "INT64".to_string())],
/// );
///
/// let mut field_number = 0u32;
/// let proto = ProtobufExporter::export_table(&table, &mut field_number);
/// assert!(proto.contains("message User"));
/// ```
/// Export a table to Protobuf message format (proto3 by default).
pub fn export_table(table: &Table, field_number: &mut u32) -> String {
Self::export_table_with_version(table, field_number, "proto3")
}
/// Export a table to Protobuf message format with specified version.
pub fn export_table_with_version(
table: &Table,
field_number: &mut u32,
version: &str,
) -> String {
let mut proto = String::new();
let message_name = Self::sanitize_identifier(&table.name);
proto.push_str(&format!("message {} {{\n", message_name));
if !table.tags.is_empty() {
proto.push_str(&Self::export_tags_as_comments(&table.tags));
}
for column in &table.columns {
*field_number += 1;
let proto_type = Self::map_data_type_to_protobuf(&column.data_type);
let is_repeated = column.data_type.to_lowercase().contains("array");
let repeated = if is_repeated { "repeated " } else { "" };
let field_name = Self::sanitize_identifier(&column.name);
// Handle field labels based on proto version
let field_label = if is_repeated {
"" // Repeated fields don't need optional/required
} else if version == "proto2" {
// proto2: all fields need a label
if column.nullable {
"optional "
} else {
"required "
}
} else {
// proto3: optional only for nullable fields
if column.nullable { "optional " } else { "" }
};
proto.push_str(&format!(
" {}{}{} {} = {};",
field_label, repeated, proto_type, field_name, field_number
));
if !column.description.is_empty() {
let desc = column.description.replace('\n', " ").replace('\r', "");
proto.push_str(&format!(" // {}", desc));
}
proto.push('\n');
}
proto.push_str("}\n");
proto
}
/// Sanitize an identifier for use in Protobuf.
///
/// - Replaces invalid characters with underscores
/// - Prefixes reserved words with underscore
/// - Ensures identifier starts with a letter or underscore
fn sanitize_identifier(name: &str) -> String {
// Replace dots (nested columns) and other invalid chars with underscores
let mut sanitized: String = name
.chars()
.map(|c| {
if c.is_alphanumeric() || c == '_' {
c
} else {
'_'
}
})
.collect();
// Ensure starts with letter or underscore
if let Some(first) = sanitized.chars().next()
&& first.is_numeric()
{
sanitized = format!("_{}", sanitized);
}
// Handle reserved words
if PROTOBUF_RESERVED.contains(&sanitized.to_lowercase().as_str()) {
sanitized = format!("_{}", sanitized);
}
sanitized
}
/// Export a data model to Protobuf format (legacy method for compatibility, proto3).
pub fn export_model(model: &DataModel, table_ids: Option<&[uuid::Uuid]>) -> String {
let tables_to_export: Vec<&Table> = if let Some(ids) = table_ids {
model
.tables
.iter()
.filter(|t| ids.contains(&t.id))
.collect()
} else {
model.tables.iter().collect()
};
// Convert Vec<&Table> to &[Table] by cloning
let tables: Vec<Table> = tables_to_export.iter().map(|t| (*t).clone()).collect();
Self::export_model_from_tables_with_version(&tables, "proto3")
}
/// Map SQL/ODCL data types to Protobuf types.
///
/// Note: For timestamp types, this returns basic proto types. If you need
/// google.protobuf.Timestamp or wrapper types, consider using the wrapper
/// type export option (future enhancement).
fn map_data_type_to_protobuf(data_type: &str) -> String {
let dt_lower = data_type.to_lowercase();
match dt_lower.as_str() {
"int" | "integer" | "smallint" | "tinyint" | "int32" => "int32".to_string(),
"bigint" | "int64" | "long" => "int64".to_string(),
"float" | "real" => "float".to_string(),
"double" | "decimal" | "numeric" => "double".to_string(),
"boolean" | "bool" => "bool".to_string(),
"bytes" | "binary" | "varbinary" => "bytes".to_string(),
// Temporal types - use int64 for timestamps (epoch millis) or string
"timestamp" | "datetime" => "int64".to_string(),
"date" | "time" => "string".to_string(),
"uuid" => "string".to_string(),
_ => {
// Default to string for VARCHAR, TEXT, CHAR, etc.
"string".to_string()
}
}
}
}