geopackage-ffi 0.12.0

C ABI for the geopackage crate: read and write OGC GeoPackage (.gpkg) files from C
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
//! `gpkg_writer_t`: insert, update and delete features one row at a time.
//!
//! [`crate::stream`] moves whole layers as Arrow and only appends. A writer
//! inserts, updates and deletes single rows. Use a writer to edit an existing
//! file, and Arrow to load a million rows.
//!
//! A writer owns a transaction for its lifetime. Rows staged through it are not
//! durable until [`gpkg_writer_commit`], and [`gpkg_writer_free`] discards
//! them. If you opened a transaction with `gpkg_begin`, the writer joins it
//! instead. Its commit then only stages the work, and your `gpkg_commit` makes
//! it durable.
//!
//! ```c
//! gpkg_writer_t *writer = gpkg_layer_writer(layer, &error);
//! if (!writer) {
//!     return fail("gpkg_layer_writer", &error);
//! }
//!
//! // A point at 6.26W 53.35N, as little-endian WKB.
//! unsigned char wkb[] = {
//!     0x01, 0x01, 0x00, 0x00, 0x00,
//!     0x8d, 0x97, 0x6e, 0x12, 0x83, 0x08, 0x19, 0xc0,
//!     0x66, 0x66, 0x66, 0x66, 0x66, 0xac, 0x4a, 0x40,
//! };
//! gpkg_value_t values[] = {
//!     {GPKG_VALUE_KIND_TEXT, {.text = "Dublin"}},
//!     {GPKG_VALUE_KIND_INTEGER, {.integer = 592713}},
//! };
//!
//! int64_t fid = 0;
//! if (gpkg_writer_insert(writer, NULL, wkb, sizeof wkb, values, 2, &fid,
//!                        &error) != GPKG_STATUS_OK) {
//!     gpkg_writer_free(writer);
//!     return fail("gpkg_writer_insert", &error);
//! }
//!
//! // Correct one column of an existing row, and remove another row.
//! bool matched = false;
//! gpkg_value_t corrected = {GPKG_VALUE_KIND_INTEGER, {.integer = 592714}};
//! gpkg_writer_update_column(writer, fid, "population", &corrected, &matched,
//!                           &error);
//! gpkg_writer_delete(writer, 7, &matched, &error);
//!
//! // Commit consumes the writer, whether it succeeds or fails.
//! if (gpkg_writer_commit(writer, &error) != GPKG_STATUS_OK) {
//!     return fail("gpkg_writer_commit", &error);
//! }
//! ```
//!
//! # Feature ids and values
//!
//! A feature id is passed as a pointer so that you can either have one assigned
//! or supply your own. Pass NULL to have one assigned, and the assigned id
//! comes back through `out_fid`. A sentinel value would not work, because every
//! `int64_t` is a valid id.
//!
//! `values` holds the layer's value columns in the order that
//! [`crate::gpkg_layer_column_name`] reports them. It excludes the primary key
//! and the geometry, which are separate arguments. A count that does not match
//! the layer is rejected rather than padded.
//!
//! # Geometry
//!
//! Geometry is passed as WKB and stored as it arrives, wrapped in the GPB
//! header the format requires. Nothing is decoded on the way, so a write
//! preserves geometry this library could not otherwise represent, especially
//! curves. `NULL` with a length of zero writes a row with no geometry.

use std::ffi::c_char;

use crate::error::{Status, gpkg_error_t, set_error, set_library_error};
use crate::handle::{LayerHandle, WriterHandle};
use crate::util::borrow_str;
use crate::value::{borrow_values, gpkg_value_t};

/// A write transaction over one layer. This opaque handle is created by
/// `gpkg_layer_writer` and destroyed by `gpkg_writer_commit` or
/// `gpkg_writer_free`.
#[expect(
    non_camel_case_types,
    reason = "the C name is the type's name; cbindgen emits it verbatim"
)]
pub type gpkg_writer_t = WriterHandle;

/// Borrows a live writer, or reports a NULL handle.
///
/// # Safety
///
/// `writer` must be NULL or a live writer handle, and `error` NULL or writable.
unsafe fn writer_mut<'a>(
    writer: *mut gpkg_writer_t,
    what: &str,
    error: *mut gpkg_error_t,
) -> Option<&'a mut WriterHandle> {
    if writer.is_null() {
        let message = format!("{what}: writer is NULL");
        // SAFETY: forwarded to the caller's guarantee on `error`.
        unsafe { set_error(error, Status::BadArgument, &message) };
        return None;
    }
    // SAFETY: the caller guarantees a live writer handle, which came from
    // `Box::into_raw` and has not been freed.
    Some(unsafe { &mut *writer })
}

/// Reads a caller-supplied geometry. `NULL` with a length of zero means none.
///
/// # Safety
///
/// `wkb` must be NULL or readable for `wkb_len` bytes.
unsafe fn borrow_wkb<'a>(
    wkb: *const u8,
    wkb_len: usize,
    error: *mut gpkg_error_t,
) -> Option<Option<&'a [u8]>> {
    if wkb.is_null() {
        if wkb_len != 0 {
            // SAFETY: forwarded to the caller's guarantee on `error`.
            unsafe {
                set_error(
                    error,
                    Status::BadArgument,
                    "geometry is NULL with a non-zero length",
                );
            }
            return None;
        }
        return Some(None);
    }
    // SAFETY: the caller guarantees `wkb` is readable for `wkb_len`.
    Some(Some(unsafe { std::slice::from_raw_parts(wkb, wkb_len) }))
}

/// Reports a library error and returns its status.
///
/// # Safety
///
/// `error` must be NULL or writable.
unsafe fn failed(err: &geopackage::Error, error: *mut gpkg_error_t) -> Status {
    // SAFETY: forwarded to the caller's guarantee on `error`.
    unsafe { set_library_error(error, err) };
    Status::from(err)
}

/// Begins a write transaction over `layer`.
///
/// The writer borrows the layer's container, which cannot be closed while the
/// writer is alive. Finish with `gpkg_writer_commit`, or discard the work with
/// `gpkg_writer_free`.
///
/// Returns NULL on failure. A read-only handle fails here rather than at the
/// first write.
///
/// # Safety
///
/// `layer` must be a live layer handle and `error` NULL or writable. The
/// returned writer must be destroyed exactly once, with `gpkg_writer_commit` or
/// `gpkg_writer_free`, and used only while no other thread is using its
/// container or any handle taken from it.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn gpkg_layer_writer(
    layer: *const LayerHandle,
    error: *mut gpkg_error_t,
) -> *mut gpkg_writer_t {
    if layer.is_null() {
        // SAFETY: forwarded to the caller's guarantee on `error`.
        unsafe {
            set_error(
                error,
                Status::BadArgument,
                "gpkg_layer_writer: layer is NULL",
            )
        };
        return std::ptr::null_mut();
    }
    // SAFETY: the caller guarantees a live layer handle.
    match unsafe { (*layer).writer() } {
        Ok(writer) => Box::into_raw(Box::new(writer)),
        Err(err) => {
            // SAFETY: forwarded to the caller's guarantee on `error`.
            unsafe { set_library_error(error, &err) };
            std::ptr::null_mut()
        }
    }
}

/// Commits the writer's work and destroys the writer.
///
/// The handle is destroyed whether this succeeds or fails, so don't use it
/// again either way. Inside a transaction you opened with `gpkg_begin`, this
/// only stages the work, and your `gpkg_commit` makes it durable.
///
/// # Safety
///
/// `writer` must be a live writer handle that has not already been committed or
/// freed. `error` must be NULL or writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn gpkg_writer_commit(
    writer: *mut gpkg_writer_t,
    error: *mut gpkg_error_t,
) -> Status {
    if writer.is_null() {
        // SAFETY: forwarded to the caller's guarantee on `error`.
        unsafe {
            set_error(
                error,
                Status::BadArgument,
                "gpkg_writer_commit: writer is NULL",
            )
        };
        return Status::BadArgument;
    }
    // SAFETY: the caller guarantees a live handle from `gpkg_layer_writer`,
    // produced by `Box::into_raw` and not yet freed.
    let handle = unsafe { Box::from_raw(writer) };
    match handle.commit() {
        Ok(()) => Status::Ok,
        // SAFETY: forwarded to the caller's guarantee on `error`.
        Err(err) => unsafe { failed(&err, error) },
    }
}

/// Discards the writer's work and destroys the writer.
///
/// Everything staged since `gpkg_layer_writer` is rolled back. Inside a
/// transaction you opened, this rolls nothing back. The work stays staged in
/// that transaction, and `gpkg_rollback` discards it.
///
/// Passing NULL does nothing.
///
/// # Safety
///
/// `writer` must be NULL, or a live writer handle that has not already been
/// committed or freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn gpkg_writer_free(writer: *mut gpkg_writer_t) {
    if writer.is_null() {
        return;
    }
    // SAFETY: the caller guarantees a live handle from `gpkg_layer_writer`,
    // produced by `Box::into_raw` and not yet freed. Dropping it rolls the
    // transaction back and releases the container count.
    drop(unsafe { Box::from_raw(writer) });
}

/// Inserts a feature, with or without a geometry.
///
/// Pass NULL as `fid` to have an id assigned, or point it at the id to use.
/// If `out_fid` is non-NULL, it receives the id that was written.
///
/// `wkb` is the geometry, or NULL with `wkb_len` zero for a row with none.
/// `values` holds the layer's value columns in order, and `values_len` must
/// match the layer.
///
/// # Safety
///
/// `writer` must be a live writer handle. `fid` must be NULL or readable.
/// `wkb` must be NULL or readable for `wkb_len` bytes. `values` must be NULL
/// (with `values_len` zero) or point at `values_len` readable values.
/// `out_fid` and `error` must be NULL or writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn gpkg_writer_insert(
    writer: *mut gpkg_writer_t,
    fid: *const i64,
    wkb: *const u8,
    wkb_len: usize,
    values: *const gpkg_value_t,
    values_len: usize,
    out_fid: *mut i64,
    error: *mut gpkg_error_t,
) -> Status {
    // SAFETY: forwarded to this function's own contract.
    let Some(handle) = (unsafe { writer_mut(writer, "gpkg_writer_insert", error) }) else {
        return Status::BadArgument;
    };
    // SAFETY: the caller guarantees `fid` is NULL or readable.
    let fid = unsafe { fid.as_ref() }.copied();
    // SAFETY: forwarded to this function's own contract.
    let Some(geometry) = (unsafe { borrow_wkb(wkb, wkb_len, error) }) else {
        return Status::BadArgument;
    };
    // SAFETY: forwarded to this function's own contract.
    let values = match unsafe { borrow_values(values, values_len, error) } {
        Ok(values) => values,
        Err(status) => return status,
    };

    let written = match geometry {
        Some(wkb) => handle.writer_mut().insert_wkb(fid, wkb, &values),
        None => handle.writer_mut().insert_row(fid, &values),
    };
    match written {
        Ok(assigned) => {
            if !out_fid.is_null() {
                // SAFETY: the caller guarantees `out_fid` is NULL or writable.
                unsafe { *out_fid = assigned };
            }
            Status::Ok
        }
        // SAFETY: forwarded to the caller's guarantee on `error`.
        Err(err) => unsafe { failed(&err, error) },
    }
}

/// Updates the feature `fid`, replacing every value column and, when `wkb` is
/// given, the geometry.
///
/// `out_matched` reports whether a row with that id existed. A missing row is
/// not an error.
///
/// # Safety
///
/// As [`gpkg_writer_insert`], with `out_matched` NULL or writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn gpkg_writer_update(
    writer: *mut gpkg_writer_t,
    fid: i64,
    wkb: *const u8,
    wkb_len: usize,
    values: *const gpkg_value_t,
    values_len: usize,
    out_matched: *mut bool,
    error: *mut gpkg_error_t,
) -> Status {
    // SAFETY: forwarded to this function's own contract.
    let Some(handle) = (unsafe { writer_mut(writer, "gpkg_writer_update", error) }) else {
        return Status::BadArgument;
    };
    // SAFETY: forwarded to this function's own contract.
    let Some(geometry) = (unsafe { borrow_wkb(wkb, wkb_len, error) }) else {
        return Status::BadArgument;
    };
    // SAFETY: forwarded to this function's own contract.
    let values = match unsafe { borrow_values(values, values_len, error) } {
        Ok(values) => values,
        Err(status) => return status,
    };

    let updated = match geometry {
        Some(wkb) => handle.writer_mut().update_wkb(fid, wkb, &values),
        None => handle.writer_mut().update_row(fid, &values),
    };
    // SAFETY: forwarded to this function's own contract.
    unsafe { report_matched(updated, out_matched, error) }
}

/// Updates one column of the feature `fid`, leaving every other value and the
/// geometry alone.
///
/// Use this to correct one field without supplying the rest of the row.
///
/// # Safety
///
/// `writer` must be a live writer handle, `column` a NUL-terminated UTF-8
/// string, `value` a readable value, and `out_matched` and `error` NULL or
/// writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn gpkg_writer_update_column(
    writer: *mut gpkg_writer_t,
    fid: i64,
    column: *const c_char,
    value: *const gpkg_value_t,
    out_matched: *mut bool,
    error: *mut gpkg_error_t,
) -> Status {
    // SAFETY: forwarded to this function's own contract.
    let Some(handle) = (unsafe { writer_mut(writer, "gpkg_writer_update_column", error) }) else {
        return Status::BadArgument;
    };
    // SAFETY: forwarded to this function's own contract.
    let Some(column) = (unsafe { borrow_str(column, error, "column") }) else {
        return Status::BadArgument;
    };
    // SAFETY: forwarded to this function's own contract.
    let values = match unsafe { borrow_values(value, 1, error) } {
        Ok(values) => values,
        Err(status) => return status,
    };
    let Some(cell) = values.first().copied() else {
        return Status::InvalidArgument;
    };

    let updated = handle.writer_mut().update_column(fid, column, cell);
    // SAFETY: forwarded to this function's own contract.
    unsafe { report_matched(updated, out_matched, error) }
}

/// Deletes the feature `fid`.
///
/// `out_matched` reports whether a row with that id existed. A missing row is
/// not an error.
///
/// Neither this nor any other call shrinks the layer's recorded bounding box.
/// The specification permits an over-estimate, and shrinking the box would
/// mean rescanning the layer.
///
/// # Safety
///
/// `writer` must be a live writer handle, and `out_matched` and `error` NULL or
/// writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn gpkg_writer_delete(
    writer: *mut gpkg_writer_t,
    fid: i64,
    out_matched: *mut bool,
    error: *mut gpkg_error_t,
) -> Status {
    // SAFETY: forwarded to this function's own contract.
    let Some(handle) = (unsafe { writer_mut(writer, "gpkg_writer_delete", error) }) else {
        return Status::BadArgument;
    };
    let deleted = handle.writer_mut().delete(fid);
    // SAFETY: forwarded to this function's own contract.
    unsafe { report_matched(deleted, out_matched, error) }
}

/// Reports the outcome of an update or delete through `out_matched`.
///
/// # Safety
///
/// `out_matched` and `error` must be NULL or writable.
unsafe fn report_matched(
    outcome: geopackage::Result<bool>,
    out_matched: *mut bool,
    error: *mut gpkg_error_t,
) -> Status {
    match outcome {
        Ok(matched) => {
            if !out_matched.is_null() {
                // SAFETY: the caller guarantees `out_matched` is NULL or
                // writable.
                unsafe { *out_matched = matched };
            }
            Status::Ok
        }
        // SAFETY: forwarded to the caller's guarantee on `error`.
        Err(err) => unsafe { failed(&err, error) },
    }
}