geolith-search-builder 0.3.2

Builds geocoding indexes from Overture Maps and OpenStreetMap: Postgres COPY files, Photon and Pelias bulk files, and the search part of a .glx file
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
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
//! PostgreSQL COPY format serializer for geocoding records.
//!
//! Outputs tab-separated values compatible with PostgreSQL `COPY FROM STDIN`
//! for bulk loading into a pg_textsearch-compatible schema.
//!
//! # Format
//!
//! Each record is one line with fields separated by tabs. Special characters
//! (tab, newline, backslash) are escaped per the PostgreSQL COPY spec.
//! NULL values are represented as `\N`.

use std::io::Write;

use crate::options::PgIndexFlavor;
use crate::record::GeocodingRecord;

/// PostgreSQL COPY writer for geocoding records.
pub struct PgCopyWriter<W: Write> {
    writer: W,
    count: u64,
}

impl<W: Write> PgCopyWriter<W> {
    /// Create a new PostgreSQL COPY writer.
    ///
    /// Writes the header row immediately.
    ///
    /// # Errors
    ///
    /// The writer's [`std::io::Error`] when the header row cannot be written.
    pub fn new(mut writer: W) -> std::io::Result<Self> {
        writeln!(
            writer,
            "id\tname\tsearch_text\tlon\tlat\tlayer\tcountry_code\tcountry\tregion\tcounty\tlocality\tstreet\tpostcode\timportance\tnames"
        )?;
        Ok(Self { writer, count: 0 })
    }

    /// Write a single geocoding record as a COPY row.
    ///
    /// The row is PostgreSQL COPY **text** format: tab-separated, `\N` for
    /// NULL, and backslash escapes in every text field (including the JSON
    /// in `names`), so it loads with `FORMAT text`.
    ///
    /// # Errors
    ///
    /// The writer's [`std::io::Error`] when the row cannot be written.
    pub fn write_record(&mut self, record: &GeocodingRecord) -> std::io::Result<()> {
        let layer = record.layer.as_str().to_owned();
        let names_json = escape_pg(&names_to_json(&record.names));
        let text = |v: Option<&str>| match v {
            Some(s) if !s.is_empty() => escape_pg(s),
            _ => r"\N".to_string(),
        };
        let address = record.address.as_ref();

        writeln!(
            self.writer,
            "{}\t{}\t{}\t{:.7}\t{:.7}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{:.4}\t{}",
            pg_bigint_id(record.id),
            escape_pg(&record.name),
            escape_pg(&record.search_text),
            record.lon,
            record.lat,
            layer,
            text(record.country_code.as_deref()),
            text(record.admin.country.as_deref()),
            text(record.admin.region.as_deref()),
            text(record.admin.county.as_deref()),
            text(record.admin.locality.as_deref()),
            text(address.and_then(|a| a.street.as_deref())),
            text(address.and_then(|a| a.postcode.as_deref())),
            record.importance,
            names_json,
        )?;
        self.count += 1;
        Ok(())
    }

    /// Return the number of records written.
    #[must_use]
    pub const fn count(&self) -> u64 {
        self.count
    }

    /// Flush the underlying writer.
    ///
    /// # Errors
    ///
    /// The writer's [`std::io::Error`] when the flush fails.
    pub fn flush(&mut self) -> std::io::Result<()> {
        self.writer.flush()
    }
}

/// Generate the companion DDL SQL for the geocoding table.
///
/// Returns a SQL string with `CREATE TABLE` and `CREATE INDEX` statements.
///
/// `flavor` selects the text index over `search_text`. The table, the `PostGIS`
/// location index, and the layer index are identical either way.
#[must_use]
pub fn generate_ddl(table_name: &str, flavor: PgIndexFlavor) -> String {
    // PostGIS provides `ST_MakePoint` for the location index; without it the
    // DDL fails. TIN provides the BM25 text index.
    let preamble = match flavor {
        PgIndexFlavor::Tin => {
            "CREATE EXTENSION IF NOT EXISTS postgis;\nCREATE EXTENSION IF NOT EXISTS tin;\n\n"
        }
        PgIndexFlavor::Gin => "CREATE EXTENSION IF NOT EXISTS postgis;\n\n",
    };

    // TIN indexes the `text` column directly; GIN needs a `tsvector` expression.
    let search_index = match flavor {
        PgIndexFlavor::Tin => "USING tin (search_text)",
        PgIndexFlavor::Gin => "USING GIN (to_tsvector('simple', search_text))",
    };

    format!(
        r#"{preamble}CREATE TABLE IF NOT EXISTS {table_name} (
    id BIGINT PRIMARY KEY,
    name TEXT NOT NULL,
    search_text TEXT NOT NULL,
    lon DOUBLE PRECISION NOT NULL,
    lat DOUBLE PRECISION NOT NULL,
    layer TEXT NOT NULL,
    country_code TEXT,
    country TEXT,
    region TEXT,
    county TEXT,
    locality TEXT,
    street TEXT,
    postcode TEXT,
    importance REAL NOT NULL DEFAULT 0.0,
    names JSONB NOT NULL DEFAULT '{{}}'::jsonb
);

CREATE INDEX IF NOT EXISTS {table_name}_search_text_idx
    ON {table_name} {search_index};

CREATE INDEX IF NOT EXISTS {table_name}_location_idx
    ON {table_name} USING GIST (ST_MakePoint(lon, lat));

CREATE INDEX IF NOT EXISTS {table_name}_layer_idx
    ON {table_name} (layer);
"#
    )
}

/// Escape a string for PostgreSQL COPY format.
///
/// Escapes: backslash → `\\`, tab → `\t`, newline → `\n`, carriage return → `\r`.
/// NUL is dropped: Postgres cannot store it in `TEXT`, and `COPY` rejects the
/// whole load on one (a real Overture venue name ends in NUL).
#[must_use]
fn escape_pg(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '\0' => {}
            '\\' => out.push_str(r"\\"),
            '\t' => out.push_str(r"\t"),
            '\n' => out.push_str(r"\n"),
            '\r' => out.push_str(r"\r"),
            c => out.push(c),
        }
    }
    out
}

/// The record id as a PostgreSQL `BIGINT`.
///
/// Record ids are `u64` hashes; about half exceed `i64::MAX`, which
/// `BIGINT` rejects, aborting the whole `COPY`. The id is written as the
/// same 64 bits read as signed, which keeps every id unique.
#[must_use]
pub(crate) const fn pg_bigint_id(id: u64) -> i64 {
    i64::from_ne_bytes(id.to_ne_bytes())
}

/// Serialize multilingual names as a JSONB-compatible JSON object.
fn names_to_json(names: &std::collections::HashMap<String, String>) -> String {
    if names.is_empty() {
        return "{}".to_string();
    }
    let mut parts: Vec<String> = names
        .iter()
        .map(|(k, v)| format!("\"{}\":\"{}\"", escape_json(k), escape_json(v)))
        .collect();
    parts.sort(); // deterministic output
    format!("{{{}}}", parts.join(","))
}

/// Minimal JSON string escaping (quotes and backslashes).
fn escape_json(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            // JSONB rejects `\u0000` as well, so NUL is dropped here too.
            '\0' => {}
            c if u32::from(c) < 0x20 => out.push_str(&format!("\\u{:04x}", u32::from(c))),
            c => out.push(c),
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::record::RecordInit;

    #[test]
    fn escape_pg_plain_string() {
        assert_eq!(escape_pg("hello world"), "hello world");
    }

    #[test]
    fn escape_pg_tab_and_newline() {
        assert_eq!(escape_pg("a\tb\nc"), r"a\tb\nc");
    }

    #[test]
    fn escape_pg_backslash() {
        assert_eq!(escape_pg(r"a\b"), r"a\\b");
    }

    /// 9757825574500787218 is a real record id from the 2026-08-19.0 release
    /// that `BIGINT` rejected. As signed 64-bit it is
    /// 9757825574500787218 - 2^64 = -8688918499208764398.
    #[test]
    fn ids_above_i64_max_become_negative_bigints() {
        assert_eq!(
            pg_bigint_id(9_757_825_574_500_787_218),
            -8_688_918_499_208_764_398
        );
        assert_eq!(
            pg_bigint_id(7_736_742_789_674_403_100),
            7_736_742_789_674_403_100
        );
        assert_eq!(pg_bigint_id(u64::MAX), -1);
    }

    #[test]
    fn distinct_ids_stay_distinct() {
        let ids = [0, 1, i64::MAX as u64, i64::MAX as u64 + 1, u64::MAX];
        let mapped: std::collections::HashSet<i64> = ids.iter().map(|&i| pg_bigint_id(i)).collect();
        assert_eq!(mapped.len(), ids.len());
    }

    /// From the 2026-08-19.0 release: a venue named "MEA Shipping\0". The
    /// row must carry no NUL byte anywhere, or `COPY` rejects the whole load.
    #[test]
    fn nul_bytes_never_reach_the_row() {
        let mut record = sample_record(None);
        record.name = "MEA Shipping\0".into();
        record.search_text = "MEA Shipping\0".into();
        record.names.insert("en".into(), "MEA\0 Shipping".into());
        let mut w = PgCopyWriter::new(Vec::new()).unwrap();
        w.write_record(&record).unwrap();
        let row = String::from_utf8(w.writer).unwrap();
        assert!(!row.contains('\0'));
        assert!(!row.contains(r"\u0000"));
        let cols: Vec<&str> = row.lines().nth(1).unwrap().split('\t').collect();
        assert_eq!(cols[1], "MEA Shipping");
        assert_eq!(cols[14], r#"{"en":"MEA Shipping","fr":"Londres"}"#);
    }

    /// JSONB rejects raw control characters; they must be `\u00XX` escapes.
    #[test]
    fn escape_json_escapes_other_control_characters() {
        assert_eq!(escape_json("a\u{1}b\u{1f}"), r"a\u0001b\u001f");
    }

    fn record_row(record: &GeocodingRecord) -> Vec<String> {
        let mut w = PgCopyWriter::new(Vec::new()).unwrap();
        w.write_record(record).unwrap();
        let out = String::from_utf8(w.writer).unwrap();
        let row = out.lines().nth(1).unwrap();
        row.split('\t').map(str::to_string).collect()
    }

    /// COPY text format decodes `\\` to `\` and `\t` to a tab. A name with a
    /// quote and a backslash must still decode to valid JSON, and a tab in a
    /// street must not split the row.
    #[test]
    fn row_escapes_names_json_and_every_text_field() {
        let mut record = sample_record(Some(AddressFields {
            street: Some("Main\tStreet".into()),
            ..Default::default()
        }));
        record.id = u64::MAX;
        record.names.clear();
        record
            .names
            .insert("en".into(), r#"Joe's "Diner" \ Grill"#.into());

        let cols = record_row(&record);
        assert_eq!(cols.len(), 15, "{cols:?}");
        assert_eq!(cols[0], "-1");
        assert_eq!(cols[11], r"Main\tStreet");
        assert_eq!(cols[12], r"\N");
        // Undo COPY text escaping the way Postgres does, then parse.
        let decoded = cols[14].replace(r"\\", "\u{0}").replace('\u{0}', r"\");
        let parsed: serde_json::Value = serde_json::from_str(&decoded).unwrap();
        assert_eq!(parsed["en"], r#"Joe's "Diner" \ Grill"#);
    }

    #[test]
    fn names_to_json_empty() {
        assert_eq!(names_to_json(&std::collections::HashMap::new()), "{}");
    }

    #[test]
    fn names_to_json_single() {
        let mut m = std::collections::HashMap::new();
        m.insert("en".to_string(), "Paris".to_string());
        let json = names_to_json(&m);
        assert_eq!(json, r#"{"en":"Paris"}"#);
    }

    #[test]
    fn generate_ddl_contains_table_name() {
        let ddl = generate_ddl("geocoding", PgIndexFlavor::Tin);
        assert!(ddl.contains("CREATE TABLE IF NOT EXISTS geocoding"));
        assert!(ddl.contains("search_text_idx"));
    }

    #[test]
    fn pg_copy_writer_header() {
        let mut buf = Vec::new();
        let writer = PgCopyWriter::new(&mut buf).expect("writer");
        let _ = writer;
        let output = String::from_utf8(buf).expect("utf8");
        assert!(output.starts_with("id\tname\tsearch_text"));
    }

    use crate::record::{AddressFields, GeocodingLayer, GeocodingRecord};
    use geolith::admin::AdminHierarchy;
    use geolith::source::input::{DataSource, OsmElementType};
    use std::collections::HashMap;

    fn sample_record(addr: Option<AddressFields>) -> GeocodingRecord {
        let mut names = HashMap::new();
        names.insert("en".to_string(), "London".to_string());
        names.insert("fr".to_string(), "Londres".to_string());
        GeocodingRecord::new(RecordInit {
            id: 42,
            source: DataSource::Osm {
                element_type: OsmElementType::Node,
                relations: vec![],
            },
            layer: GeocodingLayer::Locality,
            name: "London".to_string(),
            lon: -0.1,
            lat: 51.5,
            admin: AdminHierarchy {
                country_code: Some("GB".to_string()),
                country: Some("United Kingdom".to_string()),
                region: Some("England".to_string()),
                county: Some("Greater London".to_string()),
                locality: Some("London".to_string()),
                neighbourhood: None,
                borough: None,
                postcode: None,
                city: None,
            },
            address: addr,
            names,
            importance: 0.7,
        })
    }

    #[test]
    fn escape_pg_carriage_return() {
        assert_eq!(escape_pg("a\rb"), r"a\rb");
    }

    #[test]
    fn escape_pg_empty_string() {
        assert_eq!(escape_pg(""), "");
    }

    #[test]
    fn escape_pg_unicode_passes_through() {
        assert_eq!(escape_pg("café"), "café");
        assert_eq!(escape_pg("北京"), "北京");
    }

    #[test]
    fn escape_pg_all_special_chars_combined() {
        assert_eq!(escape_pg("\\\t\n\r"), r"\\\t\n\r");
    }

    #[test]
    fn names_to_json_multiple_entries_sorted() {
        let mut m = HashMap::new();
        m.insert("zh".to_string(), "伦敦".to_string());
        m.insert("en".to_string(), "London".to_string());
        m.insert("fr".to_string(), "Londres".to_string());
        let json = names_to_json(&m);
        assert!(json.contains(r#""en":"London""#));
        let en_pos = json.find(r#""en""#).unwrap();
        let fr_pos = json.find(r#""fr""#).unwrap();
        let zh_pos = json.find(r#""zh""#).unwrap();
        assert!(en_pos < fr_pos);
        assert!(fr_pos < zh_pos);
    }

    #[test]
    fn names_to_json_escapes_quote_and_backslash() {
        let mut m = HashMap::new();
        m.insert("k".to_string(), "v\"with\\back".to_string());
        let json = names_to_json(&m);
        assert!(json.contains(r#"v\"with\\back"#));
    }

    #[test]
    fn escape_json_all_special_chars() {
        assert_eq!(escape_json("\""), "\\\"");
        assert_eq!(escape_json("\\"), "\\\\");
        assert_eq!(escape_json("\n"), "\\n");
        assert_eq!(escape_json("\r"), "\\r");
        assert_eq!(escape_json("\t"), "\\t");
        assert_eq!(escape_json(""), "");
        assert_eq!(escape_json("plain"), "plain");
    }

    #[test]
    fn generate_ddl_contains_all_required_indexes() {
        for flavor in [PgIndexFlavor::Tin, PgIndexFlavor::Gin] {
            let ddl = generate_ddl("places", flavor);
            assert!(ddl.contains("CREATE TABLE IF NOT EXISTS places"));
            assert!(ddl.contains("places_search_text_idx"));
            assert!(ddl.contains("places_location_idx"));
            assert!(ddl.contains("places_layer_idx"));
            assert!(
                ddl.contains("USING GIST") && ddl.contains("ST_MakePoint"),
                "{flavor:?} must keep the PostGIS location index"
            );
        }
    }

    #[test]
    fn tin_flavor_indexes_the_text_column_directly() {
        let ddl = generate_ddl("places", PgIndexFlavor::Tin);

        // TIN indexes `text` directly and needs its extension installed first.
        assert!(ddl.contains("CREATE EXTENSION IF NOT EXISTS tin;"));
        assert!(ddl.contains("USING tin (search_text)"));
        assert!(
            !ddl.contains("to_tsvector"),
            "TIN does not take a tsvector expression"
        );
        assert!(
            ddl.find("CREATE EXTENSION") < ddl.find("CREATE TABLE"),
            "the extension must be created before the table that indexes with it"
        );
    }

    /// GIN is built in, so the only extension the GIN DDL needs is `PostGIS`,
    /// for `ST_MakePoint` in the location index. Without it, loading fails with
    /// "function `st_makepoint(double` precision, double precision) does not exist".
    #[test]
    fn gin_flavor_needs_only_postgis() {
        let ddl = generate_ddl("places", PgIndexFlavor::Gin);

        assert!(ddl.contains("USING GIN (to_tsvector('simple', search_text))"));
        assert!(ddl.contains("CREATE EXTENSION IF NOT EXISTS postgis;"));
        assert!(!ddl.contains("tin;"));
        assert!(!ddl.contains("USING tin"));
    }

    #[test]
    fn both_flavors_create_postgis_before_the_location_index() {
        for flavor in [PgIndexFlavor::Tin, PgIndexFlavor::Gin] {
            let ddl = generate_ddl("places", flavor);
            let ext = ddl.find("CREATE EXTENSION IF NOT EXISTS postgis;");
            let index = ddl.find("ST_MakePoint");
            assert!(ext.is_some() && ext < index, "{flavor:?}");
        }
    }

    #[test]
    fn the_default_flavor_is_tin() {
        let ddl = generate_ddl("places", PgIndexFlavor::default());

        assert!(
            ddl.contains("USING tin (search_text)"),
            "an unspecified flavor must emit the faster TIN index"
        );
    }

    #[test]
    fn pg_copy_writer_writes_full_record_with_all_admin_fields() {
        let mut buf = Vec::new();
        let mut writer = PgCopyWriter::new(&mut buf).expect("writer");
        let record = sample_record(None);
        writer.write_record(&record).expect("write");
        let output = String::from_utf8(buf).expect("utf8");
        let row = output.lines().nth(1).expect("data row");
        assert!(row.contains("42"));
        assert!(row.contains("London"));
        assert!(row.contains("locality"));
        assert!(row.contains("GB"));
        assert!(row.contains("United Kingdom"));
        assert!(row.contains("England"));
        assert!(row.contains("Greater London"));
        assert!(row.contains("0.7000"));
    }

    #[test]
    fn pg_copy_writer_emits_null_for_missing_address() {
        let mut buf = Vec::new();
        let mut writer = PgCopyWriter::new(&mut buf).expect("writer");
        let record = sample_record(None);
        writer.write_record(&record).expect("write");
        let output = String::from_utf8(buf).expect("utf8");
        let row = output.lines().nth(1).expect("data row");
        let cols: Vec<&str> = row.split('\t').collect();
        let street_col = cols[11];
        let postcode_col = cols[12];
        assert_eq!(street_col, r"\N");
        assert_eq!(postcode_col, r"\N");
    }

    #[test]
    fn pg_copy_writer_emits_null_for_empty_address_strings() {
        let mut buf = Vec::new();
        let mut writer = PgCopyWriter::new(&mut buf).expect("writer");
        let record = sample_record(Some(AddressFields {
            number: None,
            street: Some(String::new()),
            unit: None,
            postcode: Some(String::new()),
            city: None,
        }));
        writer.write_record(&record).expect("write");
        let output = String::from_utf8(buf).expect("utf8");
        let row = output.lines().nth(1).expect("data row");
        let cols: Vec<&str> = row.split('\t').collect();
        assert_eq!(cols[11], r"\N");
        assert_eq!(cols[12], r"\N");
    }

    #[test]
    fn pg_copy_writer_emits_address_when_present() {
        let mut buf = Vec::new();
        let mut writer = PgCopyWriter::new(&mut buf).expect("writer");
        let record = sample_record(Some(AddressFields {
            number: Some("123".into()),
            street: Some("Main St".into()),
            unit: None,
            postcode: Some("E1 6AN".into()),
            city: None,
        }));
        writer.write_record(&record).expect("write");
        let output = String::from_utf8(buf).expect("utf8");
        let row = output.lines().nth(1).expect("data row");
        let cols: Vec<&str> = row.split('\t').collect();
        assert_eq!(cols[11], "Main St");
        assert_eq!(cols[12], "E1 6AN");
    }

    #[test]
    fn pg_copy_writer_count_increments() {
        let mut buf = Vec::new();
        let mut writer = PgCopyWriter::new(&mut buf).expect("writer");
        for _ in 0..5 {
            writer.write_record(&sample_record(None)).expect("write");
        }
        assert_eq!(writer.count(), 5);
    }

    #[test]
    fn pg_copy_writer_flush() {
        let mut probe = FlushProbe::default();
        let mut writer = PgCopyWriter::new(&mut probe).expect("writer");
        writer.flush().expect("flush");
        assert!(probe.flushed, "flush reaches the underlying writer");
    }

    /// A sink that only records whether `flush` reached it.
    #[derive(Default)]
    struct FlushProbe {
        flushed: bool,
    }

    impl std::io::Write for FlushProbe {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            Ok(buf.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            self.flushed = true;
            Ok(())
        }
    }

    #[test]
    fn pg_copy_writer_lat_lon_seven_decimals() {
        let mut buf = Vec::new();
        let mut writer = PgCopyWriter::new(&mut buf).expect("writer");
        let mut record = sample_record(None);
        record.lon = -122.4194155;
        record.lat = 37.7749295;
        writer.write_record(&record).expect("write");
        let output = String::from_utf8(buf).expect("utf8");
        let row = output.lines().nth(1).expect("data row");
        assert!(row.contains("-122.4194155"));
        assert!(row.contains("37.7749295"));
    }
}