use std::io::Write;
use crate::options::PgIndexFlavor;
use crate::record::GeocodingRecord;
pub struct PgCopyWriter<W: Write> {
writer: W,
count: u64,
}
impl<W: Write> PgCopyWriter<W> {
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 })
}
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(())
}
#[must_use]
pub const fn count(&self) -> u64 {
self.count
}
pub fn flush(&mut self) -> std::io::Result<()> {
self.writer.flush()
}
}
#[must_use]
pub fn generate_ddl(table_name: &str, flavor: PgIndexFlavor) -> String {
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",
};
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);
"#
)
}
#[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
}
#[must_use]
pub(crate) const fn pg_bigint_id(id: u64) -> i64 {
i64::from_ne_bytes(id.to_ne_bytes())
}
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(); format!("{{{}}}", parts.join(","))
}
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"),
'\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");
}
#[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());
}
#[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"}"#);
}
#[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()
}
#[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");
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);
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"
);
}
#[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");
}
#[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"));
}
}