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
//! Read and write layers through the Arrow C Data Interface.
//!
//! Feature data crosses the boundary as Arrow record batches in both
//! directions. [`gpkg_layer_read_arrow`], [`gpkg_layer_read_arrow_in`] and
//! [`gpkg_layer_read_arrow_filtered`] fill in an `ArrowArrayStream` that you
//! own and pull from. [`gpkg_layer_write_arrow`] consumes one. The geometry is
//! a GeoArrow WKB column whose Arrow metadata records the coordinate reference
//! system. That lets [`gpkg_create_layer_from_arrow_schema`] build a
//! destination layer from a source stream's schema, so the C API needs no
//! schema-description functions at all.
//!
//! The header declares the `ArrowSchema`, `ArrowArray` and `ArrowArrayStream`
//! structs verbatim from the Arrow specification, behind the guards the
//! specification names. A program that already has them from another
//! Arrow-exporting library keeps its own definitions.
//!
//! # Reading a layer
//!
//! Consume a stream as the specification says: call `get_schema` once, then
//! `get_next` until it returns a released array, then `release`.
//!
//! ```c
//! struct ArrowArrayStream stream;
//! memset(&stream, 0, sizeof(stream));
//! if (gpkg_layer_read_arrow(layer, &stream, &error) != GPKG_STATUS_OK) {
//! return fail("gpkg_layer_read_arrow", &error);
//! }
//!
//! struct ArrowSchema schema;
//! memset(&schema, 0, sizeof(schema));
//! if (stream.get_schema(&stream, &schema) != 0) {
//! fprintf(stderr, "get_schema: %s\n", stream.get_last_error(&stream));
//! stream.release(&stream);
//! return 1;
//! }
//! printf("%lld columns\n", (long long)schema.n_children);
//! schema.release(&schema);
//!
//! long long rows = 0;
//! for (;;) {
//! struct ArrowArray array;
//! memset(&array, 0, sizeof(array));
//! if (stream.get_next(&stream, &array) != 0) {
//! fprintf(stderr, "get_next: %s\n", stream.get_last_error(&stream));
//! stream.release(&stream);
//! return 1;
//! }
//! if (array.release == NULL) {
//! break; // a released array is how the interface spells end of stream
//! }
//! rows += array.length;
//! array.release(&array);
//! }
//! stream.release(&stream);
//! ```
//!
//! A stream reports failure the way the interface specifies, as a non-zero
//! return with the detail available from `get_last_error`, not through a
//! `gpkg_error_t`. The `gpkg_error_t` these calls take covers only opening the
//! stream.
//!
//! [`gpkg_layer_read_arrow_in`] also takes a bounding box, and returns the rows
//! whose geometry envelope intersects it:
//!
//! ```c
//! struct ArrowArrayStream stream;
//! memset(&stream, 0, sizeof(stream));
//! if (gpkg_layer_read_arrow_in(layer, -7.0, 53.0, -6.0, 54.0, &stream, &error)
//! != GPKG_STATUS_OK) {
//! return fail("gpkg_layer_read_arrow_in", &error);
//! }
//! // Pulled exactly as above.
//! ```
//!
//! # Writing a layer
//!
//! Create a layer from a schema, then fill it from a stream. Filling only
//! appends: nothing in this module updates or deletes an existing row. The
//! schema can come from any producer. If you take it from a source layer's own
//! stream, you can copy the layer without describing any columns:
//!
//! ```c
//! // The whole copy under one commit, so the SRS row, the layer and its rows
//! // land together or not at all.
//! gpkg_begin(dst, &error);
//! gpkg_add_epsg_srs(dst, 4326, &error);
//! gpkg_create_layer_from_arrow_schema(dst, "cities", &schema, true, &error);
//! schema.release(&schema); // still the caller's: the call borrowed it
//!
//! gpkg_layer_t *dst_layer = gpkg_layer_open(dst, "cities", &error);
//!
//! struct ArrowArrayStream data;
//! memset(&data, 0, sizeof(data));
//! gpkg_layer_read_arrow(src_layer, &data, &error);
//!
//! uint64_t written = 0;
//! // Takes ownership of the stream: it is released by the call, whether the
//! // write succeeds or fails, and must not be released here.
//! if (gpkg_layer_write_arrow(dst_layer, &data, 1000, &written, &error)
//! != GPKG_STATUS_OK) {
//! gpkg_rollback(dst, NULL);
//! return fail("gpkg_layer_write_arrow", &error);
//! }
//! gpkg_commit(dst, &error);
//! ```
//!
//! `examples/roundtrip.c` is the full program, including error handling, and
//! the test suite compiles and runs it.
//!
//! # Why the stream is implemented by hand
//!
//! `FFI_ArrowArrayStream::new` takes `Box<dyn RecordBatchReader + Send>`, so
//! the reader must be `Send + 'static`. `geopackage::ArrowBatches<'a>` is
//! neither. It borrows the layer, and its sequential variant keeps a
//! `&Connection`, which is not `Send` because `rusqlite::Connection` is not
//! `Sync`.
//!
//! The lifetime is the easy part. It is erased exactly as [`crate::handle`]
//! erases a layer's, and the same rule makes that sound: a stream counts as a
//! child of its container, so the container cannot close while the stream is
//! alive.
//!
//! `Send` cannot be supplied truthfully. Adding `unsafe impl Send` would assert
//! that a caller may pull batches from a thread other than the one holding the
//! connection, which is exactly what `Connection: !Sync` denies, and no
//! refcount can enforce the difference. Instead of making that claim, this
//! module fills in the four `ArrowArrayStream` callbacks itself. What the
//! module avoids is arrow-rs's `Send` bound, which exists for arrow-rs's own
//! constructor rather than for the C interface: the C Data Interface makes no
//! threading claim of its own.
//!
//! arrow-rs keeps `FFI_ArrowArrayStream`'s fields private and has no way to
//! install other callbacks, so the module builds a `RawStream`, the same
//! struct as the specification lays it out, and writes it through the
//! caller's `FFI_ArrowArrayStream` pointer. The exported signatures, and so
//! the C header, still name `FFI_ArrowArrayStream`.
//!
//! So the stream follows this crate's ordinary rule: use it from one thread at
//! a time, together with its container and the container's other handles.
//!
//! # Panics across the boundary
//!
//! A panic inside one of the stream callbacks aborts the process rather than
//! unwinding into the caller's frames.
use ;
use Array;
use RecordBatchReader;
use StructArray;
use FFI_ArrowArray;
use ;
use Schema;
use FFI_ArrowSchema;
use ;
use ;
use crate;
use crate;
use crateborrow_str;
use crate;
/// The C stream interface's `struct ArrowArrayStream`, field for field as the
/// Arrow specification defines it.
///
/// `FFI_ArrowArrayStream` has the same layout, but its fields are private.
/// The assertions below check that the two agree in size and alignment. Field
/// order is fixed by the specification, which both follow.
const _: = assert!;
const _: = assert!;
/// What a stream owns for as long as C holds it.
///
/// `batches` has had its borrow of the container erased. `_token` makes that
/// sound: it counts against the container's child count until the stream is
/// released.
/// Drops the stream's state and blanks the stream, as the C Data Interface
/// requires of a release callback.
///
/// # Safety
///
/// `stream` must be a stream this module produced, not already released.
unsafe extern "C"
/// Returns the stream's private state, or `None` when it has been released.
///
/// # Safety
///
/// `stream` must be a stream this module produced.
unsafe
/// Writes the stream's schema into `out`.
///
/// # Safety
///
/// `stream` must be a stream this module produced and `out` must be writable.
unsafe extern "C"
/// Writes the next batch into `out`, or a released array at end of stream.
///
/// # Safety
///
/// As [`get_schema`].
unsafe extern "C"
/// Returns the message from the last failing callback, or NULL.
///
/// The consumer borrows the message. It stays valid until the next call on the
/// stream.
///
/// # Safety
///
/// As [`get_schema`].
unsafe extern "C"
/// The errno values `EINVAL` and `EIO`, which the C Data Interface suggests
/// for a misused and a failing stream. They are defined here rather than taken
/// from libc, which this crate does not otherwise depend on.
const EINVAL: c_int = 22;
const EIO: c_int = 5;
/// Builds a stream over `batches`, holding `token` to keep the container
/// alive.
/// Reads a layer as an Arrow C Data Interface stream.
///
/// Fills in `out` with a stream that you own and must release through its own
/// `release` callback, as the C Data Interface specifies. The stream borrows
/// the layer's container, so the container cannot be closed until the stream
/// has been released, as with a layer handle.
///
/// ```c
/// struct ArrowArrayStream stream;
/// memset(&stream, 0, sizeof(stream));
/// if (gpkg_layer_read_arrow(layer, &stream, &error) != GPKG_STATUS_OK) {
/// return fail("gpkg_layer_read_arrow", &error);
/// }
///
/// for (;;) {
/// struct ArrowArray array;
/// memset(&array, 0, sizeof(array));
/// if (stream.get_next(&stream, &array) != 0) {
/// fprintf(stderr, "get_next: %s\n", stream.get_last_error(&stream));
/// break;
/// }
/// if (array.release == NULL) {
/// break; // end of stream
/// }
/// // ... consume array.length rows ...
/// array.release(&array);
/// }
/// stream.release(&stream);
/// ```
///
/// Rows arrive in primary-key order, in batches of up to 65,536 rows. A batch
/// ends early if its geometry would otherwise exceed a byte ceiling, so a layer
/// of very large geometries still reads. The ceiling is the smaller of 2 GB
/// (the reach of the geometry column's 32-bit Arrow offsets) and a quarter of
/// the machine's memory.
///
/// If reading fails part-way through, `get_next` returns non-zero and
/// `get_last_error` has the detail, as the interface specifies. The `error`
/// out-parameter covers only opening the stream.
///
/// Batches come back on one thread. The threaded reader assigns key windows to
/// workers, which needs a second connection per worker. A stream handed to C
/// is pulled on the caller's thread instead.
///
/// # Safety
///
/// `layer` must be a live layer handle, `out` must point at writable storage
/// for an `ArrowArrayStream`, and `error` must be NULL or writable. The
/// returned stream follows the threading rule for its container: use it, and
/// release it, only while no other thread is using that container or any
/// handle taken from it.
pub unsafe extern "C"
/// Reads the rows of a layer that intersect a bounding box, as an Arrow stream.
///
/// The box is in the layer's own spatial reference system. A row is returned
/// when its geometry's envelope intersects the box, edges included. An
/// envelope is not the geometry, so the result is a superset of the rows whose
/// geometries actually intersect. To test the geometries themselves, use the
/// WKB the stream yields.
///
/// The read uses the layer's RTree index when it has a usable one, and
/// otherwise a full scan with the same filter. Either way it returns the same
/// rows. `gpkg_layer_has_spatial_index` tells you which it will use.
///
/// ```c
/// struct ArrowArrayStream stream;
/// memset(&stream, 0, sizeof(stream));
/// if (gpkg_layer_read_arrow_in(layer, -7.0, 53.0, -6.0, 54.0, &stream, &error)
/// != GPKG_STATUS_OK) {
/// return fail("gpkg_layer_read_arrow_in", &error);
/// }
/// // Pulled and released exactly as gpkg_layer_read_arrow's stream is.
/// ```
///
/// Fails with `GPKG_STATUS_NOT_FOUND` on a layer with no geometry column,
/// which has nothing to intersect.
///
/// # Safety
///
/// As [`gpkg_layer_read_arrow`].
pub unsafe extern "C"
/// Reads the rows matching a SQL `WHERE` clause, a bounding box, or both, as an
/// Arrow stream.
///
/// This is the general form of the three readers. `bbox` is NULL or four
/// doubles (`min_x`, `min_y`, `max_x`, `max_y`), read as by
/// `gpkg_layer_read_arrow_in`. `where_clause` is NULL or a SQL clause, as
/// described below. With both NULL, this is `gpkg_layer_read_arrow`. With both
/// set, the stream yields the rows that satisfy both.
///
/// The clause is **raw SQL, trusted from the caller**. It is appended to the
/// query in parentheses, and is not parsed or sanitised, just as the Rust
/// crate's `Layer::select` treats it. Its placeholders are `?1` to `?N`, and
/// `params` bind them in array order. The SQL the read adds around the clause
/// never collides with that numbering. `params` reuses the writer's
/// `gpkg_value_t`, and is borrowed only for the duration of this call.
///
/// To read one row by feature id, use the clause `fid = ?1` with the id as its
/// parameter:
///
/// ```c
/// gpkg_value_t fid = {GPKG_VALUE_KIND_INTEGER, {.integer = 17}};
/// struct ArrowArrayStream stream;
/// memset(&stream, 0, sizeof(stream));
/// if (gpkg_layer_read_arrow_filtered(layer, NULL, "fid = ?1", &fid, 1,
/// &stream, &error) != GPKG_STATUS_OK) {
/// return fail("gpkg_layer_read_arrow_filtered", &error);
/// }
/// // Pulled and released exactly as gpkg_layer_read_arrow's stream is.
/// ```
///
/// Each batch is its own query, so a clause SQLite cannot prepare is reported
/// the interface's way, through the stream's first `get_next` and
/// `get_last_error`. The `error` out-parameter covers only opening the stream.
/// Passing `params` without a clause for them fails with
/// `GPKG_STATUS_INVALID_ARGUMENT`. A bounding box on a layer with no geometry
/// column fails with `GPKG_STATUS_NOT_FOUND`, as for
/// `gpkg_layer_read_arrow_in`.
///
/// # Safety
///
/// As [`gpkg_layer_read_arrow`], and additionally: `bbox` must be NULL or
/// point at four readable doubles; `where_clause` must be NULL or a
/// NUL-terminated UTF-8 string; `params` must be NULL (only when `params_len`
/// is 0) or point at `params_len` readable `gpkg_value_t` values, each with
/// the payload its kind promises, borrowed only for the duration of this
/// call.
pub unsafe extern "C"
/// Implements the three readers.
///
/// # Safety
///
/// As [`gpkg_layer_read_arrow`].
unsafe
/// Writes an Arrow C Data Interface stream into a layer.
///
/// Writing only appends. Every batch adds rows, and no existing row is changed
/// or removed. That suits a bulk load. It also means that re-writing rows that
/// supply their own feature ids fails on the primary key rather than replacing
/// them. To change or remove an existing feature, use a `gpkg_writer_t` from
/// `gpkg_layer_writer`.
///
/// Every column in the stream's schema must exist in the layer. A column the
/// layer does not have is rejected rather than dropped, because discarding
/// data you asked to write would be worse than rejecting it. A layer column
/// that the stream does not name is left to its default. A type the layer
/// cannot store fails with `GPKG_STATUS_INVALID_ARGUMENT`. If you build the
/// layer with `gpkg_create_layer_from_arrow_schema` from the same schema, the
/// two agree by construction.
///
/// A stream column matching the layer's primary key supplies each row's fid,
/// and a row with NULL there is assigned one. A fid the table already contains
/// fails the write, so when you append to a layer that already has rows, omit
/// that column or supply NULLs in it.
///
/// Takes ownership of `stream`, as the C Data Interface specifies for a moved
/// stream. The call releases it whether the write succeeds or fails, and you
/// must not release it again. If `out_rows` is non-NULL, it receives the
/// number of rows written.
///
/// ```c
/// struct ArrowArrayStream data;
/// memset(&data, 0, sizeof(data));
/// if (gpkg_layer_read_arrow(src_layer, &data, &error) != GPKG_STATUS_OK) {
/// return fail("gpkg_layer_read_arrow", &error);
/// }
///
/// uint64_t written = 0;
/// // `data` is consumed here, and must not be released afterwards.
/// if (gpkg_layer_write_arrow(dst_layer, &data, 1000, &written, &error)
/// != GPKG_STATUS_OK) {
/// return fail("gpkg_layer_write_arrow", &error);
/// }
/// printf("wrote %llu rows\n", (unsigned long long)written);
/// ```
///
/// `batch_size` is the number of rows per write transaction, and `0` writes
/// everything in one transaction. Inside a transaction you opened with
/// `gpkg_begin`, every batch belongs to that transaction. The batch size then
/// sets only how many rows are held at once, not what becomes durable.
///
/// If the write fails part-way through, the batches that have already
/// committed stay. So `batch_size` also decides how much a failed write can
/// leave behind. With `0` it leaves nothing, because there is one transaction.
/// Inside your own transaction, nothing is durable until you commit, and
/// `gpkg_rollback` discards all of it.
///
/// If the layer has a spatial index, the write brings it up to date.
///
/// # Safety
///
/// `layer` must be a live layer handle, `stream` must point at a stream the
/// caller owns and has not released, `out_rows` must be NULL or writable, and
/// `error` must be NULL or writable.
pub unsafe extern "C"
/// Creates a layer whose columns come from an Arrow schema.
///
/// The call borrows the schema rather than consuming it, so you still own it
/// and must release it. To copy a layer without describing any columns
/// yourself, take the schema from the source stream's `get_schema` and pass it
/// straight here.
///
/// ```c
/// struct ArrowArrayStream src_stream;
/// memset(&src_stream, 0, sizeof(src_stream));
/// gpkg_layer_read_arrow(src_layer, &src_stream, &error);
///
/// struct ArrowSchema schema;
/// memset(&schema, 0, sizeof(schema));
/// src_stream.get_schema(&src_stream, &schema);
/// src_stream.release(&src_stream); // the schema outlives the stream
///
/// gpkg_add_epsg_srs(dst, 4326, &error);
/// if (gpkg_create_layer_from_arrow_schema(dst, "cities", &schema, true, &error)
/// != GPKG_STATUS_OK) {
/// schema.release(&schema);
/// return fail("gpkg_create_layer_from_arrow_schema", &error);
/// }
/// schema.release(&schema);
/// ```
///
/// The geometry column and its spatial reference system come from the
/// schema's GeoArrow metadata. The referenced SRS must already exist in the
/// destination, and `gpkg_add_epsg_srs` can add it. The geometry column is
/// declared `GEOMETRY` rather than with the source's own type, because the
/// GeoArrow WKB encoding does not record that type.
///
/// `spatial_index` requests an RTree index over that column, the usual choice
/// for a layer you will query by bounding box. `gpkg_layer_create_spatial_index`
/// can add one later, at the cost of a pass over the rows.
///
/// Fails with `GPKG_STATUS_ALREADY_EXISTS` when the file already has a table
/// of that name, and with `GPKG_STATUS_NOT_FOUND` when the schema names a
/// spatial reference system the file does not register.
///
/// # Safety
///
/// `gpkg` must be a live container handle, `name` a NUL-terminated UTF-8
/// string, `schema` a valid `ArrowSchema` the caller owns, and `error` NULL or
/// writable.
pub unsafe extern "C"
/// Registers an EPSG spatial reference system in the file.
///
/// A layer cannot name an SRS the file does not register, so call this before
/// creating a layer that uses one.
///
/// # Safety
///
/// `gpkg` must be a live container handle and `error` NULL or writable.
pub unsafe extern "C"