1use ifc::selector::{value_text, Selector, SelectorError, SelectorIndex, SetTarget, ValuePath};
19use ifc::sheet::{self, KeyColumn, Sheet, SheetFormat, SheetFormatError, SheetOptions};
20use ifc::EntityId;
21
22use crate::record::{Field, Record, ToRecord};
23use crate::selector::{parse_error, selector_error};
24use crate::{BindingError, IfcModel};
25
26#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct TableChange {
29 pub row: usize,
31 pub column: usize,
33 pub key: String,
35 pub path: String,
37 pub entity: u64,
39 pub target_entity: u64,
42 pub target: String,
44 pub before: String,
46 pub after: String,
48}
49
50#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct TableRefusal {
53 pub row: Option<usize>,
55 pub column: Option<usize>,
57 pub code: String,
63 pub message: String,
65 pub span: Option<(usize, usize)>,
67}
68
69#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct TableImport {
72 pub applied: bool,
75 pub changes: Vec<TableChange>,
77 pub refusals: Vec<TableRefusal>,
79}
80
81impl ToRecord for TableChange {
82 fn to_record(&self) -> Record {
83 Record::new(
84 "TableChange",
85 vec![
86 ("row", Field::Count(self.row)),
87 ("column", Field::Count(self.column)),
88 ("key", Field::Text(self.key.clone())),
89 ("path", Field::Text(self.path.clone())),
90 ("entity", Field::Id(self.entity)),
91 ("target_entity", Field::Id(self.target_entity)),
92 ("target", Field::Text(self.target.clone())),
93 ("before", Field::Text(self.before.clone())),
94 ("after", Field::Text(self.after.clone())),
95 ],
96 )
97 }
98}
99
100impl ToRecord for TableRefusal {
101 fn to_record(&self) -> Record {
102 Record::new(
103 "TableRefusal",
104 vec![
105 ("row", Field::optional(self.row, Field::Count)),
106 ("column", Field::optional(self.column, Field::Count)),
107 ("code", Field::Text(self.code.clone())),
108 ("message", Field::Text(self.message.clone())),
109 (
110 "span",
111 Field::optional(self.span, |(start, end)| {
112 Field::List(vec![Field::Count(start), Field::Count(end)])
113 }),
114 ),
115 ],
116 )
117 }
118}
119
120impl ToRecord for TableImport {
121 fn to_record(&self) -> Record {
122 Record::new(
123 "TableImport",
124 vec![
125 ("applied", Field::Bool(self.applied)),
126 ("changes", Field::records(&self.changes)),
127 ("refusals", Field::records(&self.refusals)),
128 ],
129 )
130 }
131}
132
133fn format(name: &str) -> Result<SheetFormat, BindingError> {
135 SheetFormat::from_name(name).ok_or_else(|| {
136 BindingError::InvalidValue(format!("{name:?} is no table format (csv, tsv, xlsx)"))
137 })
138}
139
140fn options(key: Option<&str>, null: &str) -> Result<SheetOptions, BindingError> {
142 let mut options = SheetOptions::default().with_null(null);
143 if let Some(name) = key {
144 let key = KeyColumn::from_name(name).ok_or_else(|| {
145 BindingError::InvalidValue(format!("{name:?} is no key column (GlobalId, id)"))
146 })?;
147 options = options.with_key(key);
148 }
149 Ok(options)
150}
151
152fn format_error(error: SheetFormatError) -> BindingError {
153 match error {
154 SheetFormatError::FeatureDisabled(feature) => BindingError::FeatureDisabled(feature),
155 SheetFormatError::TooLarge(detail) => BindingError::Unsupported(detail),
156 other => BindingError::Parse(other.to_string()),
157 }
158}
159
160impl IfcModel {
161 pub fn export_table(
172 &self,
173 query: &str,
174 columns: &[String],
175 format_name: &str,
176 key: Option<&str>,
177 null: &str,
178 ) -> Result<Vec<u8>, BindingError> {
179 let format = format(format_name)?;
180 let options = options(key, null)?;
181 let selector = Selector::parse(query).map_err(parse_error)?;
182 let paths = columns
183 .iter()
184 .map(|path| ValuePath::parse(path).map_err(parse_error))
185 .collect::<Result<Vec<_>, _>>()?;
186 let schema = self.declared_schema()?;
187 let index = SelectorIndex::new(&self.inner, schema);
188 let selected = index.select(&selector).map_err(selector_error)?;
189 let table =
190 sheet::export(&index, &selected, &paths, &options).map_err(|error| match error {
191 sheet::ExportError::Value { error, .. } => selector_error(*error),
192 other => BindingError::WrongEntityType(other.to_string()),
193 })?;
194 table.write(format).map_err(format_error)
195 }
196
197 pub fn import_table(
211 &mut self,
212 data: &[u8],
213 format_name: &str,
214 key: Option<&str>,
215 null: &str,
216 dry_run: bool,
217 ) -> Result<TableImport, BindingError> {
218 let seed = crate::relations::fresh_seed()?;
219 self.tracked(|this| this.import_table_seeded(data, format_name, key, null, dry_run, seed))
220 }
221
222 pub fn import_table_seeded(
229 &mut self,
230 data: &[u8],
231 format_name: &str,
232 key: Option<&str>,
233 null: &str,
234 dry_run: bool,
235 seed: u128,
236 ) -> Result<TableImport, BindingError> {
237 let format = format(format_name)?;
238 let options = options(key, null)?;
239 let table = match Sheet::read(data, format) {
240 Ok(table) => table,
241 Err(SheetFormatError::Malformed {
242 row,
243 column,
244 detail,
245 }) => {
246 return Ok(TableImport {
247 applied: false,
248 changes: Vec::new(),
249 refusals: vec![TableRefusal {
250 row: Some(row),
251 column,
252 code: "malformed-table".to_owned(),
253 message: detail,
254 span: None,
255 }],
256 })
257 }
258 Err(other) => return Err(format_error(other)),
259 };
260 let schema = self.declared_schema()?;
261 let planned = sheet::plan_import(
262 &SelectorIndex::new(&self.inner, schema),
263 &table,
264 &options,
265 seed,
266 );
267 let plan = match planned {
268 Ok(plan) => plan,
269 Err(refused) => {
270 return Ok(TableImport {
271 applied: false,
272 changes: Vec::new(),
273 refusals: refused.iter().map(refusal).collect(),
274 })
275 }
276 };
277 let changes: Vec<TableChange> = plan
278 .changes
279 .iter()
280 .map(|cell| {
281 let (target_entity, target) = target(&cell.change.target);
282 TableChange {
283 row: cell.row,
284 column: cell.column,
285 key: cell.key.clone(),
286 path: cell.path.clone(),
287 entity: cell.change.entity.0,
288 target_entity,
289 target,
290 before: value_text(&cell.change.before, null),
291 after: value_text(&cell.change.after, null),
292 }
293 })
294 .collect();
295 if dry_run || changes.is_empty() {
296 return Ok(TableImport {
297 applied: false,
298 changes,
299 refusals: Vec::new(),
300 });
301 }
302 match self.tracked(|this| plan.commit(&mut this.inner)) {
303 Ok(_) => Ok(TableImport {
304 applied: true,
305 changes,
306 refusals: Vec::new(),
307 }),
308 Err(refused) => Ok(TableImport {
309 applied: false,
310 changes,
311 refusals: refused.iter().map(refusal).collect(),
312 }),
313 }
314 }
315}
316
317fn target(target: &SetTarget) -> (u64, String) {
318 match target {
319 SetTarget::Attribute {
320 entity: EntityId(id),
321 name,
322 } => (*id, name.clone()),
323 SetTarget::Property {
324 object: EntityId(id),
325 set,
326 property,
327 } => (*id, format!("{set}.{property}")),
328 other => (0, format!("{other:?}")),
329 }
330}
331
332fn refusal(refused: &sheet::SheetRefusal) -> TableRefusal {
333 use sheet::SheetRefusalReason as R;
334 let (code, span) = match &refused.reason {
335 R::Empty => ("empty-table".to_owned(), None),
336 R::Header(error) => (
337 "invalid-header".to_owned(),
338 Some((error.span.start, error.span.end)),
339 ),
340 R::DuplicateColumn { .. } => ("duplicate-column".to_owned(), None),
341 R::NoKeyColumn(_) => ("no-key-column".to_owned(), None),
342 R::RaggedRow { .. } => ("ragged-row".to_owned(), None),
343 R::EmptyKey => ("empty-key".to_owned(), None),
344 R::UnknownKey(_) => ("unknown-key".to_owned(), None),
345 R::DuplicateKey { .. } => ("duplicate-key".to_owned(), None),
346 R::AmbiguousKey(_) => ("ambiguous-key".to_owned(), None),
347 R::Value(error) => (value_code(error), None),
348 _ => ("invalid-value".to_owned(), None),
349 };
350 TableRefusal {
351 row: refused.row,
352 column: refused.column,
353 code,
354 message: refused.reason.to_string(),
355 span,
356 }
357}
358
359fn value_code(error: &SelectorError) -> String {
361 match error {
362 SelectorError::InvalidText { .. } => "type-mismatch".to_owned(),
363 SelectorError::ConflictingWrite { .. } => "invalid-value".to_owned(),
364 other => selector_error(other.clone()).code().to_owned(),
365 }
366}