xberg 1.2.2

High-performance document intelligence library for Rust. Extract text, metadata, and structured data from PDFs, Office documents, images, and 107 formats and 371 programming languages via tree-sitter code intelligence with async/sync APIs.
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
mod helpers;

use helpers::extract_bytes_document;
use rusqlite::Connection;
use tempfile::TempDir;
use xberg::extractors::security::SecurityError;
use xberg::{
    ExtractInput, ExtractionConfig, OutputFormat, SecurityLimits, XbergError, detect_mime_type,
    detect_mime_type_from_bytes, extract, get_extensions_for_mime, list_supported_formats,
};

const SQLITE_MIME: &str = "application/vnd.sqlite3";
const GEOPACKAGE_MIME: &str = "application/geopackage+sqlite3";
const SQLITE_ALIAS_MIME: &str = "application/x-sqlite3";
const OCTET_STREAM_MIME: &str = "application/octet-stream";
const GEOPACKAGE_1_0_APPLICATION_ID: u32 = 0x4750_3130;
const GEOPACKAGE_1_2_APPLICATION_ID: u32 = 0x4750_4B47;

fn database_bytes(schema_and_data: &str) -> Vec<u8> {
    let directory = TempDir::new().expect("temporary database directory should be created");
    let path = directory.path().join("fixture.sqlite");
    let connection = Connection::open(&path).expect("synthetic SQLite database should open");
    connection
        .execute_batch(schema_and_data)
        .expect("synthetic SQLite schema and rows should be created");
    drop(connection);
    std::fs::read(path).expect("synthetic SQLite database should be readable")
}

fn database_bytes_with_application_id(application_id: u32, schema_and_data: &str) -> Vec<u8> {
    database_bytes(&format!("PRAGMA application_id = {application_id};\n{schema_and_data}"))
}

fn sqlite_input(bytes: Vec<u8>, filename: &str) -> ExtractInput {
    ExtractInput::from_bytes(bytes, OCTET_STREAM_MIME, Some(filename.to_string()))
}

async fn extraction_error(bytes: Vec<u8>, filename: &str, config: &ExtractionConfig) -> XbergError {
    extract(sqlite_input(bytes, filename), config)
        .await
        .expect_err("single-document extraction should propagate parser and security failures")
}

fn security_config(limits: SecurityLimits) -> ExtractionConfig {
    ExtractionConfig {
        security_limits: Some(limits),
        ..ExtractionConfig::default()
    }
}

#[test]
fn should_detect_sqlite_magic_before_the_text_fallback() {
    let bytes = database_bytes("CREATE TABLE records (id INTEGER PRIMARY KEY, value TEXT);");

    assert_eq!(detect_mime_type_from_bytes(&bytes).unwrap(), SQLITE_MIME);
}

#[test]
fn should_detect_geopackage_application_ids_from_the_sqlite_header() {
    for application_id in [GEOPACKAGE_1_0_APPLICATION_ID, GEOPACKAGE_1_2_APPLICATION_ID] {
        let bytes = database_bytes_with_application_id(
            application_id,
            "CREATE TABLE records (id INTEGER PRIMARY KEY, value TEXT);",
        );

        assert_eq!(
            detect_mime_type_from_bytes(&bytes).unwrap(),
            GEOPACKAGE_MIME,
            "application ID {application_id:#010x} should identify a GeoPackage"
        );
    }
}

#[test]
fn should_register_all_sqlite_and_geopackage_extensions_case_insensitively() {
    assert_eq!(
        get_extensions_for_mime(SQLITE_MIME).unwrap(),
        ["db", "sqlite", "sqlite3"]
    );
    assert_eq!(
        get_extensions_for_mime(SQLITE_ALIAS_MIME).unwrap(),
        ["db", "sqlite", "sqlite3"]
    );
    assert_eq!(get_extensions_for_mime(GEOPACKAGE_MIME).unwrap(), ["gpkg", "gpkx"]);
    let advertised: std::collections::HashMap<String, String> = list_supported_formats()
        .into_iter()
        .map(|format| (format.extension, format.mime_type))
        .collect();
    for (extension, expected_mime) in [
        ("db", SQLITE_MIME),
        ("sqlite", SQLITE_MIME),
        ("sqlite3", SQLITE_MIME),
        ("gpkg", GEOPACKAGE_MIME),
        ("gpkx", GEOPACKAGE_MIME),
    ] {
        assert_eq!(advertised.get(extension).map(String::as_str), Some(expected_mime));
        assert_eq!(
            detect_mime_type(format!("fixture.{}", extension.to_ascii_uppercase()), false).unwrap(),
            expected_mime
        );
    }
}

#[test]
fn should_route_the_sqlite_mime_alias_to_the_same_extractor() {
    xberg::extractors::ensure_initialized().expect("built-in extractor registration should succeed");
    let registry = xberg::plugins::registry::get_document_extractor_registry();
    let registry = registry.read();

    let canonical = registry
        .get(SQLITE_MIME)
        .unwrap_or_else(|error| panic!("{SQLITE_MIME} should route: {error}"));
    let alias = registry
        .get(SQLITE_ALIAS_MIME)
        .unwrap_or_else(|error| panic!("{SQLITE_ALIAS_MIME} should route: {error}"));
    assert_eq!(alias.name(), canonical.name());
}

#[tokio::test]
async fn should_extract_user_tables_in_deterministic_name_and_row_order() {
    let bytes = database_bytes(
        r#"
        CREATE TABLE zeta (key TEXT, value INTEGER);
        INSERT INTO zeta VALUES ('last', 9), ('later', 10);
        CREATE TABLE alpha (
            id INTEGER,
            label TEXT,
            amount REAL,
            optional TEXT,
            payload BLOB
        );
        INSERT INTO alpha VALUES (1, 'A|B', 3.5, NULL, X'00017F');
        "#,
    );

    let config = ExtractionConfig {
        output_format: OutputFormat::Markdown,
        ..ExtractionConfig::default()
    };
    let document = extract_bytes_document(&bytes, SQLITE_MIME, &config)
        .await
        .expect("SQLite extraction should succeed");

    assert_eq!(document.mime_type, SQLITE_MIME);
    assert_eq!(document.tables.len(), 2);
    assert_eq!(
        document.tables[0].cells,
        vec![
            vec!["id", "label", "amount", "optional", "payload"],
            vec!["1", "A|B", "3.5", "", "[BLOB: 3 bytes]"],
        ]
    );
    assert_eq!(
        document.tables[0].markdown,
        "| id | label | amount | optional | payload |\n\
         | --- | --- | --- | --- | --- |\n\
         | 1 | A\\|B | 3.5 |  | [BLOB: 3 bytes] |\n"
    );
    assert_eq!(
        document.tables[1].cells,
        vec![vec!["key", "value"], vec!["last", "9"], vec!["later", "10"]]
    );
    assert_eq!(
        document.content,
        "## alpha\n\n\
         | id | label | amount | optional | payload |\n\
         | --- | --- | --- | --- | --- |\n\
         | 1 | A\\|B | 3.5 |  | [BLOB: 3 bytes] |\n\n\
         ## zeta\n\n\
         | key | value |\n\
         | --- | --- |\n\
         | last | 9 |\n\
         | later | 10 |\n"
    );
}

#[tokio::test]
async fn should_refine_geopackage_mime_from_valid_signatures_not_the_filename() {
    for application_id in [GEOPACKAGE_1_0_APPLICATION_ID, GEOPACKAGE_1_2_APPLICATION_ID] {
        let geopackage = database_bytes_with_application_id(
            application_id,
            r#"
            CREATE TABLE gpkg_contents (table_name TEXT PRIMARY KEY, data_type TEXT);
            INSERT INTO gpkg_contents VALUES ('roads', 'features');
            CREATE TABLE roads (id INTEGER, name TEXT);
            INSERT INTO roads VALUES (1, 'Main Street');
            "#,
        );

        let document = extract(sqlite_input(geopackage, "misleading.db"), &ExtractionConfig::default())
            .await
            .expect("GeoPackage extraction should return an envelope");
        assert_eq!(document.summary.results, 1);
        assert_eq!(document.results[0].mime_type, GEOPACKAGE_MIME);
        assert_eq!(document.results[0].tables.len(), 1);
        assert_eq!(document.results[0].tables[0].cells[0], vec!["id", "name"]);
    }

    let ordinary_sqlite = database_bytes("CREATE TABLE records (id INTEGER); INSERT INTO records VALUES (1);");

    let sqlite_document = extract(
        sqlite_input(ordinary_sqlite, "misleading.gpkg"),
        &ExtractionConfig::default(),
    )
    .await
    .expect("ordinary SQLite extraction should return an envelope");
    assert_eq!(sqlite_document.summary.results, 1);
    assert_eq!(sqlite_document.results[0].mime_type, SQLITE_MIME);
}

#[tokio::test]
async fn should_not_treat_a_reserved_table_name_as_a_geopackage_signature() {
    let spoof = database_bytes(
        r#"
        CREATE TABLE gpkg_contents (table_name TEXT PRIMARY KEY, data_type TEXT);
        INSERT INTO gpkg_contents VALUES ('records', 'attributes');
        CREATE TABLE records (id INTEGER, value TEXT);
        INSERT INTO records VALUES (1, 'ordinary SQLite');
        "#,
    );

    assert_eq!(detect_mime_type_from_bytes(&spoof).unwrap(), SQLITE_MIME);
    let document = extract(sqlite_input(spoof, "spoof.gpkg"), &ExtractionConfig::default())
        .await
        .expect("ordinary SQLite extraction should return an envelope");
    assert_eq!(document.summary.results, 1);
    assert_eq!(document.results[0].mime_type, SQLITE_MIME);
    assert_eq!(document.results[0].tables.len(), 2);
    assert_eq!(
        document.results[0].tables[0].cells,
        vec![vec!["table_name", "data_type"], vec!["records", "attributes"],]
    );
    assert_eq!(
        document.results[0].tables[1].cells,
        vec![vec!["id", "value"], vec!["1", "ordinary SQLite"]]
    );
}

#[tokio::test]
async fn should_exclude_internal_metadata_views_and_virtual_tables() {
    let bytes = database_bytes_with_application_id(
        GEOPACKAGE_1_2_APPLICATION_ID,
        r#"
        CREATE TABLE gpkg_contents (table_name TEXT PRIMARY KEY, data_type TEXT);
        INSERT INTO gpkg_contents VALUES ('public_data', 'attributes');
        CREATE TABLE public_data (id INTEGER PRIMARY KEY AUTOINCREMENT, value TEXT);
        INSERT INTO public_data (value) VALUES ('visible');
        CREATE TABLE gpkg_spatial_ref_sys (srs_id INTEGER, organization TEXT);
        INSERT INTO gpkg_spatial_ref_sys VALUES (4326, 'EPSG');
        CREATE TABLE rtree_public_data_geom (id INTEGER, min_x REAL, max_x REAL);
        INSERT INTO rtree_public_data_geom VALUES (1, 0.0, 1.0);
        CREATE VIEW leaked_view AS SELECT 'hidden' AS secret;
        CREATE VIRTUAL TABLE search_index USING fts5(body);
        INSERT INTO search_index VALUES ('indexed but hidden');
        CREATE TABLE gpkgish (value TEXT);
        INSERT INTO gpkgish VALUES ('prefix is not reserved');
        "#,
    );

    let document = extract_bytes_document(&bytes, SQLITE_MIME, &ExtractionConfig::default())
        .await
        .expect("GeoPackage extraction should succeed");

    assert_eq!(document.mime_type, GEOPACKAGE_MIME);
    assert_eq!(document.tables.len(), 2);
    assert_eq!(document.tables[0].cells[0], vec!["value"]);
    assert_eq!(document.tables[0].cells[1], vec!["prefix is not reserved"]);
    assert_eq!(document.tables[1].cells[0], vec!["id", "value"]);
    assert_eq!(document.tables[1].cells[1], vec!["1", "visible"]);
    assert!(!document.content.contains("EPSG"));
    assert!(!document.content.contains("hidden"));
    assert!(!document.content.contains("indexed but hidden"));
}

#[tokio::test]
async fn should_quote_table_and_column_identifiers_without_executing_them() {
    let bytes = database_bytes(
        r#"
        CREATE TABLE safe (value TEXT);
        INSERT INTO safe VALUES ('still present');
        CREATE TABLE "odd""name; DROP TABLE safe; --" ("value""name" TEXT);
        INSERT INTO "odd""name; DROP TABLE safe; --" VALUES ('quoted value');
        "#,
    );

    let document = extract_bytes_document(&bytes, SQLITE_MIME, &ExtractionConfig::default())
        .await
        .expect("quoted identifiers should extract safely");

    assert_eq!(document.tables.len(), 2);
    assert_eq!(
        document.tables[0].cells,
        vec![vec!["value\"name"], vec!["quoted value"]]
    );
    assert_eq!(document.tables[1].cells, vec![vec!["value"], vec!["still present"]]);
}

#[tokio::test]
async fn should_skip_virtual_generated_columns_before_query_evaluation() {
    let bytes = database_bytes(
        "CREATE TABLE records (\
            value TEXT, \
            bomb TEXT GENERATED ALWAYS AS (hex(zeroblob(1000000))) VIRTUAL\
         ); \
         INSERT INTO records (value) VALUES ('safe');",
    );
    let config = security_config(SecurityLimits {
        max_entity_length: 16,
        ..SecurityLimits::default()
    });

    let document = extract_bytes_document(&bytes, SQLITE_MIME, &config)
        .await
        .expect("virtual generated columns should be excluded before evaluation");

    assert_eq!(document.tables.len(), 1);
    assert_eq!(document.tables[0].cells, vec![vec!["value"], vec!["safe"]]);
    assert!(!document.content.contains("bomb"));
}

#[tokio::test]
async fn should_not_evaluate_a_generated_column_that_shadows_rowid_ordering() {
    let bytes = database_bytes(
        "CREATE TABLE records (\
            value INTEGER, \
            rowid INTEGER GENERATED ALWAYS AS (-value) VIRTUAL\
         ); \
         INSERT INTO records (value) VALUES (1), (2);",
    );
    let config = security_config(SecurityLimits {
        max_entity_length: 16,
        ..SecurityLimits::default()
    });

    let document = extract_bytes_document(&bytes, SQLITE_MIME, &config)
        .await
        .expect("rowid ordering should not resolve to a generated column");

    assert_eq!(document.tables.len(), 1);
    assert_eq!(document.tables[0].cells, vec![vec!["value"], vec!["1"], vec!["2"]]);
}

#[tokio::test]
async fn should_fall_back_to_visible_columns_when_all_rowid_aliases_are_shadowed() {
    let bytes = database_bytes(
        "CREATE TABLE records (\
            value INTEGER, \
            rowid INTEGER GENERATED ALWAYS AS (-value) VIRTUAL, \
            _rowid_ INTEGER GENERATED ALWAYS AS (-value) VIRTUAL, \
            oid INTEGER GENERATED ALWAYS AS (-value) VIRTUAL\
         ); \
         INSERT INTO records (value) VALUES (2), (1);",
    );

    let document = extract_bytes_document(&bytes, SQLITE_MIME, &ExtractionConfig::default())
        .await
        .expect("visible columns should provide safe deterministic ordering");

    assert_eq!(document.tables.len(), 1);
    assert_eq!(document.tables[0].cells, vec![vec!["value"], vec!["1"], vec!["2"]]);
}

#[tokio::test]
async fn should_report_a_parsing_error_for_a_malformed_sqlite_database() {
    let mut malformed = b"SQLite format 3\0".to_vec();
    malformed.resize(512, 0);

    let error = extraction_error(malformed, "broken.sqlite", &ExtractionConfig::default()).await;

    assert!(matches!(&error, XbergError::Parsing { .. }));
    assert!(
        error.to_string().to_ascii_lowercase().contains("sqlite"),
        "unexpected error message: {error}"
    );
}

#[tokio::test]
async fn should_reject_the_database_before_extraction_when_input_exceeds_the_content_limit() {
    let bytes = database_bytes("CREATE TABLE records (value TEXT); INSERT INTO records VALUES ('visible');");
    let byte_count = bytes.len();
    let config = security_config(SecurityLimits {
        max_content_size: byte_count - 1,
        ..SecurityLimits::default()
    });

    let error = extraction_error(bytes, "large.sqlite", &config).await;

    assert!(matches!(&error, XbergError::Security { .. }));
    assert!(
        error.to_string().contains(&format!("{byte_count} bytes")),
        "unexpected error message: {error}"
    );
}

#[tokio::test]
async fn should_enforce_the_table_cell_limit_across_the_database() {
    let bytes = database_bytes("CREATE TABLE records (left TEXT, right TEXT); INSERT INTO records VALUES ('a', 'b');");
    let config = security_config(SecurityLimits {
        max_table_cells: 3,
        ..SecurityLimits::default()
    });

    let error = extraction_error(bytes, "cells.sqlite", &config).await;

    assert!(matches!(&error, XbergError::Security { .. }));
    let source = std::error::Error::source(&error)
        .and_then(|source| source.downcast_ref::<SecurityError>())
        .expect("security violation should retain the structured source error");
    assert!(
        matches!(source, SecurityError::TooManyCells { cells: 4, max: 3 }),
        "unexpected structured security source: {source:?}"
    );
}

#[tokio::test]
async fn should_enforce_the_entity_limit_for_column_names_and_cell_values() {
    let column_bytes = database_bytes("CREATE TABLE t (column_name_that_is_too_long TEXT);");
    let column_config = security_config(SecurityLimits {
        max_entity_length: 16,
        ..SecurityLimits::default()
    });
    let column_error = extraction_error(column_bytes, "column.sqlite", &column_config).await;

    assert!(matches!(&column_error, XbergError::Security { .. }));
    assert!(column_error.to_string().contains("Entity too long: 28 chars (max: 16)"));

    let value_bytes =
        database_bytes("CREATE TABLE t (value TEXT); INSERT INTO t VALUES ('cell_value_that_is_too_long');");
    let value_config = security_config(SecurityLimits {
        max_entity_length: 16,
        ..SecurityLimits::default()
    });

    let value_error = extraction_error(value_bytes, "value.sqlite", &value_config).await;

    assert!(matches!(&value_error, XbergError::Security { .. }));
    assert!(value_error.to_string().contains("Entity too long: 27 chars (max: 16)"));
}

#[tokio::test]
async fn should_enforce_the_iteration_limit_across_schema_and_row_scans() {
    let bytes = database_bytes("CREATE TABLE records (value TEXT); INSERT INTO records VALUES ('one'), ('two');");
    let config = security_config(SecurityLimits {
        max_iterations: 2,
        ..SecurityLimits::default()
    });

    let error = extraction_error(bytes, "iterations.sqlite", &config).await;

    assert!(matches!(&error, XbergError::Security { .. }));
    assert!(error.to_string().contains("Too many iterations: 3 (max: 2)"));
}

#[tokio::test]
async fn should_count_reserved_table_schema_rows_towards_the_iteration_limit() {
    let bytes = database_bytes(
        "CREATE TABLE gpkg_first (value TEXT); \
         CREATE TABLE gpkg_second (value TEXT);",
    );
    let config = security_config(SecurityLimits {
        max_iterations: 1,
        ..SecurityLimits::default()
    });

    let error = extraction_error(bytes, "reserved.sqlite", &config).await;

    assert!(matches!(&error, XbergError::Security { .. }));
    assert!(error.to_string().contains("Too many iterations: 2 (max: 1)"));
}

#[tokio::test]
async fn should_not_charge_intrinsic_sqlite_schema_names_to_user_entity_limits() {
    let bytes = database_bytes("CREATE TABLE t (c TEXT);");
    let config = security_config(SecurityLimits {
        max_entity_length: 1,
        ..SecurityLimits::default()
    });

    let document = extract_bytes_document(&bytes, SQLITE_MIME, &config)
        .await
        .expect("intrinsic SQLite metadata should not consume user entity limits");

    assert_eq!(document.tables.len(), 1);
    assert_eq!(document.tables[0].cells, vec![vec!["c"]]);
}

#[tokio::test]
async fn should_count_without_rowid_primary_key_schema_rows_towards_the_iteration_limit() {
    let bytes = database_bytes("CREATE TABLE records (key TEXT PRIMARY KEY) WITHOUT ROWID;");
    let config = security_config(SecurityLimits {
        max_iterations: 1,
        ..SecurityLimits::default()
    });

    let error = extraction_error(bytes, "without-rowid.sqlite", &config).await;

    assert!(matches!(&error, XbergError::Security { .. }));
    assert!(error.to_string().contains("Too many iterations: 2 (max: 1)"));
}