Coverage for geoparser/gazetteer/build/stages/emit.py: 100%

74 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-20 18:08 +0000

1""" 

2Emission of the projected features into the SQLite artifact. 

3 

4Rows are copied from the DuckDB build tables into a temporary SQLite file in 

5batches; search structures (FTS5, soundex, indexes) and metadata are built 

6afterwards, then the file is vacuumed and atomically moved into place. 

7""" 

8 

9import sqlite3 

10import typing as t 

11from datetime import datetime, timezone 

12from pathlib import Path 

13 

14import duckdb 

15 

16from geoparser.gazetteer import artifact 

17from geoparser.gazetteer.build.progress import advance, item 

18from geoparser.gazetteer.build.schema import GazetteerConfig 

19 

20# Number of rows copied per batch from DuckDB to SQLite 

21BATCH_SIZE = 50000 

22 

23 

24def create_artifact_db(path: Path) -> sqlite3.Connection: 

25 """ 

26 Create a fresh artifact database with the base schema. 

27 

28 The connection is tuned for bulk writes with a bounded memory footprint: 

29 the artifact is a throwaway temporary file that is only moved into place 

30 after a fully successful build, so durability is irrelevant, but memory 

31 use must stay bounded even for very large gazetteers (tens of millions of 

32 rows). All temporary data spills to disk rather than RAM. 

33 

34 Args: 

35 path: Path of the artifact file to create 

36 

37 Returns: 

38 SQLite connection to the new database 

39 """ 

40 if path.exists(): 

41 path.unlink() 

42 connection = sqlite3.connect(path, isolation_level=None) 

43 connection.execute("PRAGMA synchronous=OFF") 

44 # No rollback journal: avoids buffering the whole bulk-load transaction in 

45 # memory, which would otherwise grow without bound on large builds. 

46 connection.execute("PRAGMA journal_mode=OFF") 

47 # Spill temporary data (index sorts, FTS rebuild, VACUUM) to disk, not RAM. 

48 connection.execute("PRAGMA temp_store=FILE") 

49 # Cap the page cache so memory stays bounded regardless of data size 

50 # (negative value = cache size in KiB, here 64 MiB). 

51 connection.execute("PRAGMA cache_size=-65536") 

52 for statement in artifact.BASE_SCHEMA: 

53 connection.execute(statement) 

54 return connection 

55 

56 

57def copy_rows( 

58 duckdb_connection: duckdb.DuckDBPyConnection, 

59 sqlite_connection: sqlite3.Connection, 

60 select_sql: str, 

61 insert_sql: str, 

62 bar: t.Any, 

63) -> int: 

64 """ 

65 Copy rows from a DuckDB query into a SQLite table in batches. 

66 

67 Args: 

68 duckdb_connection: DuckDB connection to read from 

69 sqlite_connection: SQLite connection to write to 

70 select_sql: DuckDB query producing the rows 

71 insert_sql: SQLite INSERT statement with positional placeholders 

72 bar: Item bar to report copy progress on, as a percentage of the 

73 total row count (known up front from a cheap count query) 

74 

75 Returns: 

76 Number of copied rows 

77 """ 

78 total = duckdb_connection.execute( 

79 f"SELECT count(*) FROM ({select_sql})" 

80 ).fetchone()[0] 

81 cursor = duckdb_connection.execute(select_sql) 

82 copied = 0 

83 sqlite_connection.execute("BEGIN") 

84 while True: 

85 batch = cursor.fetchmany(BATCH_SIZE) 

86 if not batch: 

87 break 

88 sqlite_connection.executemany(insert_sql, batch) 

89 copied += len(batch) 

90 if total: 

91 bar.set_progress(min(100.0, copied / total * 100)) 

92 sqlite_connection.execute("COMMIT") 

93 return copied 

94 

95 

96def emit( 

97 duckdb_connection: duckdb.DuckDBPyConnection, 

98 sqlite_connection: sqlite3.Connection, 

99) -> t.Tuple[int, int]: 

100 """ 

101 Copy the projected features and names into the artifact. 

102 

103 Expects the DuckDB build tables ``_features_final`` (id, identifier, source, 

104 data, geometry) and ``_names_final`` (feature_id, text) to exist. 

105 

106 Args: 

107 duckdb_connection: DuckDB connection holding the build tables 

108 sqlite_connection: SQLite connection of the artifact being built 

109 

110 Returns: 

111 Tuple of (feature count, name count) 

112 """ 

113 with item("Writing features", total=100) as bar: 

114 feature_count = copy_rows( 

115 duckdb_connection, 

116 sqlite_connection, 

117 "SELECT id, identifier, source, data, geometry " 

118 "FROM _features_final ORDER BY id", 

119 "INSERT INTO feature (id, identifier, source, data, geometry) " 

120 "VALUES (?, ?, ?, ?, ?)", 

121 bar, 

122 ) 

123 advance() 

124 with item("Writing names", total=100) as bar: 

125 name_count = copy_rows( 

126 duckdb_connection, 

127 sqlite_connection, 

128 "SELECT feature_id, text FROM _names_final ORDER BY feature_id, text", 

129 "INSERT INTO name (feature_id, text) VALUES (?, ?)", 

130 bar, 

131 ) 

132 advance() 

133 return feature_count, name_count 

134 

135 

136def finalize( 

137 sqlite_connection: sqlite3.Connection, 

138 config: GazetteerConfig, 

139 feature_count: int, 

140 name_count: int, 

141) -> None: 

142 """ 

143 Build the search structures and metadata, then compact the artifact. 

144 

145 Args: 

146 sqlite_connection: SQLite connection of the artifact being built 

147 config: The gazetteer configuration that was built 

148 feature_count: Number of emitted features 

149 name_count: Number of emitted names 

150 """ 

151 artifact.register_functions(sqlite_connection) 

152 

153 sqlite_connection.execute("BEGIN") 

154 with item("Building indexes", total=100) as bar: 

155 statements = artifact.SEARCH_SCHEMA 

156 for i, statement in enumerate(statements, start=1): 

157 sqlite_connection.execute(statement) 

158 bar.set_progress(i / len(statements) * 100) 

159 advance() 

160 

161 metadata = { 

162 "schema_version": artifact.SCHEMA_VERSION, 

163 "name": config.name, 

164 "crs": config.crs, 

165 "created_at": datetime.now(timezone.utc).isoformat(), 

166 "feature_count": str(feature_count), 

167 "name_count": str(name_count), 

168 } 

169 with item("Writing metadata", total=100) as bar: 

170 rows = list(metadata.items()) 

171 for i, row in enumerate(rows, start=1): 

172 sqlite_connection.execute( 

173 "INSERT INTO metadata (key, value) VALUES (?, ?)", row 

174 ) 

175 bar.set_progress(i / len(rows) * 100) 

176 sqlite_connection.execute("COMMIT") 

177 advance() 

178 

179 with item("Verifying integrity", total=100) as bar: 

180 # The emitted counts must match what is actually stored 

181 stored_features = sqlite_connection.execute( 

182 "SELECT count(*) FROM feature" 

183 ).fetchone()[0] 

184 bar.set_progress(50) 

185 stored_names = sqlite_connection.execute( 

186 "SELECT count(*) FROM name" 

187 ).fetchone()[0] 

188 bar.set_progress(100) 

189 if stored_features != feature_count or stored_names != name_count: 

190 raise RuntimeError( 

191 f"Artifact integrity check failed: expected {feature_count} features " 

192 f"and {name_count} names, found {stored_features} and {stored_names}" 

193 ) 

194 advance() 

195 

196 with item("Compacting artifact", total=100) as bar: 

197 sqlite_connection.execute("ANALYZE") 

198 bar.set_progress(50) 

199 sqlite_connection.execute("VACUUM") 

200 bar.set_progress(100) 

201 advance()