@konstit/dne 0.0.2 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +215 -13
- package/data/dne.bin +0 -0
- package/dist/bairro.d.ts +27 -0
- package/dist/bairro.js +9 -0
- package/dist/bairro.js.map +1 -0
- package/dist/binary-db-errors.d.ts +56 -0
- package/dist/binary-db-errors.js +68 -0
- package/dist/binary-db-errors.js.map +1 -0
- package/dist/binary-db-format.d.ts +192 -0
- package/dist/binary-db-format.js +250 -0
- package/dist/binary-db-format.js.map +1 -0
- package/dist/binary-db-reader.d.ts +114 -0
- package/dist/binary-db-reader.js +700 -0
- package/dist/binary-db-reader.js.map +1 -0
- package/dist/cep.d.ts +50 -0
- package/dist/cep.js +184 -0
- package/dist/cep.js.map +1 -0
- package/dist/errors.d.ts +14 -0
- package/dist/errors.js +21 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.js +55 -33
- package/dist/index.js.map +29 -16
- package/dist/library.d.ts +10 -0
- package/dist/library.js +8 -0
- package/dist/library.js.map +1 -0
- package/dist/schema.d.ts +88 -0
- package/dist/schema.js +233 -0
- package/dist/schema.js.map +1 -0
- package/dist/settings.d.ts +34 -0
- package/dist/settings.js +35 -0
- package/dist/settings.js.map +1 -0
- package/dist/sqlite-db-errors.d.ts +40 -0
- package/dist/sqlite-db-errors.js +54 -0
- package/dist/sqlite-db-errors.js.map +1 -0
- package/dist/sqlite-db-reader.d.ts +130 -0
- package/dist/sqlite-db-reader.js +307 -0
- package/dist/sqlite-db-reader.js.map +1 -0
- package/dist/sqlite-db-schema.d.ts +49 -0
- package/dist/sqlite-db-schema.js +115 -0
- package/dist/sqlite-db-schema.js.map +1 -0
- package/dist/types.d.ts +90 -0
- package/dist/types.js +49 -0
- package/dist/types.js.map +1 -0
- package/package.json +17 -4
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { type DneBairro, type DneFaixaCep } from './bairro.ts';
|
|
2
|
+
import type { DneRow, LoadMetadata } from './types.ts';
|
|
3
|
+
/** Error classes and discriminants used by the SQLite reader. */
|
|
4
|
+
export type { DneBairro, DneFaixaCep } from './bairro.ts';
|
|
5
|
+
export { DneDatabaseClosedError, DneDatabaseDataError, DneDatabaseError, type DneDatabaseErrorCode, DneDatabaseIOError, DneDatabaseQueryError, DneDatabaseSchemaError, } from './sqlite-db-errors.ts';
|
|
6
|
+
export type { DneRow, LoadMetadata } from './types.ts';
|
|
7
|
+
/** Read-only SQLite access for CEP lookup, schema inspection, metadata, and bounded SQL queries. */
|
|
8
|
+
export declare class DneDatabaseReader {
|
|
9
|
+
private readonly databasePath;
|
|
10
|
+
private readonly db;
|
|
11
|
+
private closed;
|
|
12
|
+
private normalizedSchemaReady;
|
|
13
|
+
/**
|
|
14
|
+
* Opens an existing SQLite database in read-only mode with a 30-second busy timeout.
|
|
15
|
+
* @param databasePath - Path to the SQLite database.
|
|
16
|
+
* @throws {DneDatabaseIOError} If SQLite cannot open or configure the connection.
|
|
17
|
+
*/
|
|
18
|
+
constructor(databasePath: string);
|
|
19
|
+
/**
|
|
20
|
+
* Closes the SQLite connection. Repeated calls are safe; subsequent reads throw.
|
|
21
|
+
* @throws {DneDatabaseIOError} If SQLite cannot close the connection.
|
|
22
|
+
*/
|
|
23
|
+
close(): void;
|
|
24
|
+
/**
|
|
25
|
+
* Checks whether a named table exists in the database catalog.
|
|
26
|
+
* @param tableName - Physical table name.
|
|
27
|
+
* @returns True when the catalog contains a table with this name.
|
|
28
|
+
* @throws {DneDatabaseClosedError} If the reader is closed, including for invalid input.
|
|
29
|
+
* @throws {DneDatabaseQueryError} If SQLite cannot prepare or execute the read.
|
|
30
|
+
*/
|
|
31
|
+
hasTable(tableName: string): boolean;
|
|
32
|
+
/**
|
|
33
|
+
* Reads the import metadata table.
|
|
34
|
+
* @returns A new metadata map, or undefined when the metadata table is absent.
|
|
35
|
+
* @throws {DneDatabaseClosedError} If the reader is closed, including for invalid input.
|
|
36
|
+
* @throws {DneDatabaseQueryError} If SQLite cannot prepare or execute the read.
|
|
37
|
+
*/
|
|
38
|
+
metadata(): LoadMetadata | undefined;
|
|
39
|
+
/**
|
|
40
|
+
* Looks up a plain or hyphenated CEP in the default unified table.
|
|
41
|
+
* @param cep - Eight ASCII digits or `NNNNN-NNN`, without surrounding whitespace.
|
|
42
|
+
* @returns The matching address, or undefined for invalid input or a missing CEP.
|
|
43
|
+
* @throws {DneDatabaseSchemaError} If normalized neighborhoods or locality fields are absent.
|
|
44
|
+
* @throws {DneDatabaseDataError} If the matched row contains invalid locality indicators.
|
|
45
|
+
* @throws {DneDatabaseClosedError} If the reader is closed, including for invalid input.
|
|
46
|
+
* @throws {DneDatabaseQueryError} If SQLite cannot prepare or execute the read.
|
|
47
|
+
*/
|
|
48
|
+
queryCep(cep: string): DneRow | undefined;
|
|
49
|
+
/**
|
|
50
|
+
* Reads a neighborhood by its original DNE identifier.
|
|
51
|
+
* @param neighborhoodId - Positive `BAI_NU` identifier.
|
|
52
|
+
* @returns The neighborhood, or undefined for an invalid or unknown identifier.
|
|
53
|
+
* @throws {DneDatabaseSchemaError} If normalized neighborhoods are absent.
|
|
54
|
+
* @throws {DneDatabaseClosedError} If the reader is closed, including for invalid input.
|
|
55
|
+
* @throws {DneDatabaseQueryError} If SQLite cannot prepare or execute the read.
|
|
56
|
+
*/
|
|
57
|
+
queryNeighborhood(neighborhoodId: number): DneBairro | undefined;
|
|
58
|
+
/**
|
|
59
|
+
* Resolves the actual neighborhood attached to a CEP, without treating a district or village as a neighborhood.
|
|
60
|
+
* @param cep - Eight ASCII digits or `NNNNN-NNN`.
|
|
61
|
+
* @returns The neighborhood, or undefined for an invalid, unknown, or neighborhood-free CEP.
|
|
62
|
+
* @throws {DneDatabaseSchemaError} If normalized neighborhoods are absent.
|
|
63
|
+
* @throws {DneDatabaseClosedError} If the reader is closed, including for invalid input.
|
|
64
|
+
* @throws {DneDatabaseQueryError} If SQLite cannot prepare or execute the read.
|
|
65
|
+
*/
|
|
66
|
+
queryNeighborhoodByCep(cep: string): DneBairro | undefined;
|
|
67
|
+
/**
|
|
68
|
+
* Lists a neighborhood's original CEP intervals without merging gaps.
|
|
69
|
+
* @param neighborhoodId - Positive `BAI_NU` identifier.
|
|
70
|
+
* @returns Intervals sorted by their lower and upper bounds; an empty array for invalid, unknown, or rangeless neighborhoods.
|
|
71
|
+
* @throws {DneDatabaseSchemaError} If normalized neighborhoods are absent.
|
|
72
|
+
* @throws {DneDatabaseClosedError} If the reader is closed, including for invalid input.
|
|
73
|
+
* @throws {DneDatabaseQueryError} If SQLite cannot prepare or execute the read.
|
|
74
|
+
*/
|
|
75
|
+
queryNeighborhoodCepRanges(neighborhoodId: number): DneFaixaCep[];
|
|
76
|
+
private requireCurrentSchema;
|
|
77
|
+
/**
|
|
78
|
+
* Counts all rows in a SQLite table.
|
|
79
|
+
* @param tableName - Existing physical table name.
|
|
80
|
+
* @returns The number of rows reported by SQLite.
|
|
81
|
+
* @throws {DneDatabaseClosedError} If the reader is closed, including for invalid input.
|
|
82
|
+
* @throws {DneDatabaseQueryError} If SQLite cannot prepare or execute the read.
|
|
83
|
+
*/
|
|
84
|
+
rowCount(tableName: string): number;
|
|
85
|
+
/**
|
|
86
|
+
* Reads a table's stored CREATE statement without reconstructing it from the declared schema.
|
|
87
|
+
* @param tableName - Physical table name.
|
|
88
|
+
* @returns The catalog SQL, or undefined when no SQL definition is available.
|
|
89
|
+
* @throws {DneDatabaseClosedError} If the reader is closed, including for invalid input.
|
|
90
|
+
* @throws {DneDatabaseQueryError} If SQLite cannot prepare or execute the read.
|
|
91
|
+
*/
|
|
92
|
+
tableSchema(tableName: string): string | undefined;
|
|
93
|
+
/**
|
|
94
|
+
* Executes caller-supplied SQL on the read-only connection, retaining a bounded result.
|
|
95
|
+
* @param sql - A statement accepted by SQLite; this method does not apply the CLI's statement filter.
|
|
96
|
+
* @param limit - Positive maximum number of rows to retain.
|
|
97
|
+
* @returns Rows plus a flag indicating whether at least one additional row was available.
|
|
98
|
+
* @throws {DneDatabaseClosedError} If the reader is closed, including for invalid input.
|
|
99
|
+
* @throws {DneDatabaseQueryError} If SQLite cannot prepare or execute the read.
|
|
100
|
+
*/
|
|
101
|
+
querySql(sql: string, limit: number): {
|
|
102
|
+
rows: Record<string, unknown>[];
|
|
103
|
+
truncated: boolean;
|
|
104
|
+
};
|
|
105
|
+
private readSafely;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Converts a supported SQLite URL to its path without resolving relative paths.
|
|
109
|
+
* @param value - Plain path, `:memory:`, or a URL beginning with `sqlite:///`.
|
|
110
|
+
* @returns The path after removing the supported URL prefix, without URI decoding.
|
|
111
|
+
* @throws {Error} If a different URL scheme is supplied.
|
|
112
|
+
*/
|
|
113
|
+
export declare function sqlitePathFromDatabaseUrl(value: string): string;
|
|
114
|
+
/**
|
|
115
|
+
* Reads SQLite load metadata using a temporary read-only connection.
|
|
116
|
+
* @param databasePath - Path to the SQLite database.
|
|
117
|
+
* @returns Metadata, or undefined if the file or metadata table is missing.
|
|
118
|
+
* @throws {DneDatabaseIOError} If an existing database cannot be opened or closed.
|
|
119
|
+
* @throws {DneDatabaseQueryError} If its metadata cannot be queried.
|
|
120
|
+
*/
|
|
121
|
+
export declare function readDatabaseMetadata(databasePath: string): Promise<LoadMetadata | undefined>;
|
|
122
|
+
/**
|
|
123
|
+
* Checks for a SQLite table without creating a missing database.
|
|
124
|
+
* @param databasePath - Database file path; `:memory:` reports false.
|
|
125
|
+
* @param tableName - Physical table name to locate.
|
|
126
|
+
* @returns False for a missing database or table.
|
|
127
|
+
* @throws {DneDatabaseIOError} If an existing database cannot be opened or closed.
|
|
128
|
+
* @throws {DneDatabaseQueryError} If its catalog cannot be queried.
|
|
129
|
+
*/
|
|
130
|
+
export declare function hasTable(databasePath: string, tableName: string): Promise<boolean>;
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite';
|
|
2
|
+
import { isBairroId, } from "./bairro.js";
|
|
3
|
+
import { cepToU32 } from "./cep.js";
|
|
4
|
+
import { LOCALIDADE_SITUACOES, LOCALIDADE_TIPO_CODIGOS, LOCALIDADE_TIPOS, } from "./schema.js";
|
|
5
|
+
import { SQLITE_BAIRRO_FAIXAS_TABLE_NAME, SQLITE_BAIRROS_TABLE_NAME, SQLITE_CEP_TABLE_NAME, SQLITE_METADATA_TABLE_NAME, } from "./settings.js";
|
|
6
|
+
import { DneDatabaseClosedError, DneDatabaseDataError, DneDatabaseError, DneDatabaseIOError, DneDatabaseQueryError, DneDatabaseSchemaError, } from "./sqlite-db-errors.js";
|
|
7
|
+
import { cepViewName, quoteIdent, } from "./sqlite-db-schema.js";
|
|
8
|
+
export { DneDatabaseClosedError, DneDatabaseDataError, DneDatabaseError, DneDatabaseIOError, DneDatabaseQueryError, DneDatabaseSchemaError, } from "./sqlite-db-errors.js";
|
|
9
|
+
/** Read-only SQLite access for CEP lookup, schema inspection, metadata, and bounded SQL queries. */
|
|
10
|
+
export class DneDatabaseReader {
|
|
11
|
+
databasePath;
|
|
12
|
+
db;
|
|
13
|
+
closed = false;
|
|
14
|
+
normalizedSchemaReady = false;
|
|
15
|
+
/**
|
|
16
|
+
* Opens an existing SQLite database in read-only mode with a 30-second busy timeout.
|
|
17
|
+
* @param databasePath - Path to the SQLite database.
|
|
18
|
+
* @throws {DneDatabaseIOError} If SQLite cannot open or configure the connection.
|
|
19
|
+
*/
|
|
20
|
+
constructor(databasePath) {
|
|
21
|
+
this.databasePath = databasePath;
|
|
22
|
+
let db;
|
|
23
|
+
try {
|
|
24
|
+
db = new Database(databasePath, { readonly: true });
|
|
25
|
+
db.run('PRAGMA busy_timeout = 30000');
|
|
26
|
+
this.db = db;
|
|
27
|
+
}
|
|
28
|
+
catch (cause) {
|
|
29
|
+
try {
|
|
30
|
+
db?.close();
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
// Preserve the opening failure if cleanup also fails.
|
|
34
|
+
}
|
|
35
|
+
throw new DneDatabaseIOError(databasePath, { cause });
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Closes the SQLite connection. Repeated calls are safe; subsequent reads throw.
|
|
40
|
+
* @throws {DneDatabaseIOError} If SQLite cannot close the connection.
|
|
41
|
+
*/
|
|
42
|
+
close() {
|
|
43
|
+
if (this.closed) {
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
try {
|
|
47
|
+
this.db.close();
|
|
48
|
+
this.closed = true;
|
|
49
|
+
}
|
|
50
|
+
catch (cause) {
|
|
51
|
+
throw new DneDatabaseIOError(this.databasePath, { cause });
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Checks whether a named table exists in the database catalog.
|
|
56
|
+
* @param tableName - Physical table name.
|
|
57
|
+
* @returns True when the catalog contains a table with this name.
|
|
58
|
+
* @throws {DneDatabaseClosedError} If the reader is closed, including for invalid input.
|
|
59
|
+
* @throws {DneDatabaseQueryError} If SQLite cannot prepare or execute the read.
|
|
60
|
+
*/
|
|
61
|
+
hasTable(tableName) {
|
|
62
|
+
return this.readSafely(() => {
|
|
63
|
+
return Boolean(this.db.query('SELECT 1 FROM sqlite_master WHERE type = \'table\' AND name = ?').get(tableName));
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Reads the import metadata table.
|
|
68
|
+
* @returns A new metadata map, or undefined when the metadata table is absent.
|
|
69
|
+
* @throws {DneDatabaseClosedError} If the reader is closed, including for invalid input.
|
|
70
|
+
* @throws {DneDatabaseQueryError} If SQLite cannot prepare or execute the read.
|
|
71
|
+
*/
|
|
72
|
+
metadata() {
|
|
73
|
+
return this.readSafely(() => {
|
|
74
|
+
if (!this.hasTable(SQLITE_METADATA_TABLE_NAME)) {
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
77
|
+
const rows = this.db.query(`SELECT key, value FROM ${quoteIdent(SQLITE_METADATA_TABLE_NAME)}`).all();
|
|
78
|
+
return Object.fromEntries(rows.map((row) => [row.key, row.value]));
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Looks up a plain or hyphenated CEP in the default unified table.
|
|
83
|
+
* @param cep - Eight ASCII digits or `NNNNN-NNN`, without surrounding whitespace.
|
|
84
|
+
* @returns The matching address, or undefined for invalid input or a missing CEP.
|
|
85
|
+
* @throws {DneDatabaseSchemaError} If normalized neighborhoods or locality fields are absent.
|
|
86
|
+
* @throws {DneDatabaseDataError} If the matched row contains invalid locality indicators.
|
|
87
|
+
* @throws {DneDatabaseClosedError} If the reader is closed, including for invalid input.
|
|
88
|
+
* @throws {DneDatabaseQueryError} If SQLite cannot prepare or execute the read.
|
|
89
|
+
*/
|
|
90
|
+
queryCep(cep) {
|
|
91
|
+
return this.readSafely(() => {
|
|
92
|
+
const parsed = cepToU32(cep);
|
|
93
|
+
if (Number.isNaN(parsed)) {
|
|
94
|
+
return undefined;
|
|
95
|
+
}
|
|
96
|
+
this.requireCurrentSchema();
|
|
97
|
+
const row = this.db.query(`SELECT * FROM ${quoteIdent(cepViewName(SQLITE_CEP_TABLE_NAME))} WHERE cep = ?`)
|
|
98
|
+
.get(cep.length === 8 ? cep : `${cep.slice(0, 5)}${cep.slice(6)}`);
|
|
99
|
+
if (!row) {
|
|
100
|
+
return undefined;
|
|
101
|
+
}
|
|
102
|
+
if (row.localidade_situacao === undefined || row.localidade_tipo === undefined) {
|
|
103
|
+
throw new DneDatabaseSchemaError('Database schema lacks locality indicators. Rebuild the database with build --force.');
|
|
104
|
+
}
|
|
105
|
+
const situacao = LOCALIDADE_SITUACOES[row.localidade_situacao];
|
|
106
|
+
const tipo = LOCALIDADE_TIPOS[LOCALIDADE_TIPO_CODIGOS.indexOf(row.localidade_tipo)];
|
|
107
|
+
if (situacao === undefined || tipo === undefined) {
|
|
108
|
+
throw new DneDatabaseDataError('Database contains invalid locality indicators. Rebuild the database with build --force.');
|
|
109
|
+
}
|
|
110
|
+
return { ...row, localidade_situacao: situacao, localidade_tipo: tipo };
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Reads a neighborhood by its original DNE identifier.
|
|
115
|
+
* @param neighborhoodId - Positive `BAI_NU` identifier.
|
|
116
|
+
* @returns The neighborhood, or undefined for an invalid or unknown identifier.
|
|
117
|
+
* @throws {DneDatabaseSchemaError} If normalized neighborhoods are absent.
|
|
118
|
+
* @throws {DneDatabaseClosedError} If the reader is closed, including for invalid input.
|
|
119
|
+
* @throws {DneDatabaseQueryError} If SQLite cannot prepare or execute the read.
|
|
120
|
+
*/
|
|
121
|
+
queryNeighborhood(neighborhoodId) {
|
|
122
|
+
return this.readSafely(() => {
|
|
123
|
+
if (!isBairroId(neighborhoodId)) {
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
this.requireCurrentSchema();
|
|
127
|
+
const row = this.db.query(`SELECT * FROM ${quoteIdent(SQLITE_BAIRROS_TABLE_NAME)} WHERE bairro_id = ?`)
|
|
128
|
+
.get(neighborhoodId);
|
|
129
|
+
return row ?? undefined;
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Resolves the actual neighborhood attached to a CEP, without treating a district or village as a neighborhood.
|
|
134
|
+
* @param cep - Eight ASCII digits or `NNNNN-NNN`.
|
|
135
|
+
* @returns The neighborhood, or undefined for an invalid, unknown, or neighborhood-free CEP.
|
|
136
|
+
* @throws {DneDatabaseSchemaError} If normalized neighborhoods are absent.
|
|
137
|
+
* @throws {DneDatabaseClosedError} If the reader is closed, including for invalid input.
|
|
138
|
+
* @throws {DneDatabaseQueryError} If SQLite cannot prepare or execute the read.
|
|
139
|
+
*/
|
|
140
|
+
queryNeighborhoodByCep(cep) {
|
|
141
|
+
return this.readSafely(() => {
|
|
142
|
+
if (Number.isNaN(cepToU32(cep))) {
|
|
143
|
+
return undefined;
|
|
144
|
+
}
|
|
145
|
+
this.requireCurrentSchema();
|
|
146
|
+
const row = this.db.query(`
|
|
147
|
+
SELECT b.* FROM ${quoteIdent(SQLITE_CEP_TABLE_NAME)} d
|
|
148
|
+
JOIN ${quoteIdent(SQLITE_BAIRROS_TABLE_NAME)} b ON b.bairro_id = d.bairro_id
|
|
149
|
+
WHERE d.cep = ?
|
|
150
|
+
`).get(cep.replace('-', ''));
|
|
151
|
+
return row ?? undefined;
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Lists a neighborhood's original CEP intervals without merging gaps.
|
|
156
|
+
* @param neighborhoodId - Positive `BAI_NU` identifier.
|
|
157
|
+
* @returns Intervals sorted by their lower and upper bounds; an empty array for invalid, unknown, or rangeless neighborhoods.
|
|
158
|
+
* @throws {DneDatabaseSchemaError} If normalized neighborhoods are absent.
|
|
159
|
+
* @throws {DneDatabaseClosedError} If the reader is closed, including for invalid input.
|
|
160
|
+
* @throws {DneDatabaseQueryError} If SQLite cannot prepare or execute the read.
|
|
161
|
+
*/
|
|
162
|
+
queryNeighborhoodCepRanges(neighborhoodId) {
|
|
163
|
+
return this.readSafely(() => {
|
|
164
|
+
if (!isBairroId(neighborhoodId)) {
|
|
165
|
+
return [];
|
|
166
|
+
}
|
|
167
|
+
this.requireCurrentSchema();
|
|
168
|
+
return this.db.query(`
|
|
169
|
+
SELECT cep_inicial, cep_final FROM ${quoteIdent(SQLITE_BAIRRO_FAIXAS_TABLE_NAME)}
|
|
170
|
+
WHERE bairro_id = ? ORDER BY cep_inicial, cep_final
|
|
171
|
+
`).all(neighborhoodId);
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
requireCurrentSchema() {
|
|
175
|
+
if (!this.normalizedSchemaReady) {
|
|
176
|
+
this.normalizedSchemaReady = Boolean(this.db.query('SELECT 1 FROM sqlite_master WHERE type = \'view\' AND name = ?')
|
|
177
|
+
.get(cepViewName(SQLITE_CEP_TABLE_NAME)));
|
|
178
|
+
}
|
|
179
|
+
if (!this.normalizedSchemaReady) {
|
|
180
|
+
throw new DneDatabaseSchemaError('Database schema lacks normalized neighborhoods. Rebuild the database with build --force.');
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Counts all rows in a SQLite table.
|
|
185
|
+
* @param tableName - Existing physical table name.
|
|
186
|
+
* @returns The number of rows reported by SQLite.
|
|
187
|
+
* @throws {DneDatabaseClosedError} If the reader is closed, including for invalid input.
|
|
188
|
+
* @throws {DneDatabaseQueryError} If SQLite cannot prepare or execute the read.
|
|
189
|
+
*/
|
|
190
|
+
rowCount(tableName) {
|
|
191
|
+
return this.readSafely(() => {
|
|
192
|
+
const row = this.db.query(`SELECT count(*) AS count FROM ${quoteIdent(tableName)}`).get();
|
|
193
|
+
return row.count;
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Reads a table's stored CREATE statement without reconstructing it from the declared schema.
|
|
198
|
+
* @param tableName - Physical table name.
|
|
199
|
+
* @returns The catalog SQL, or undefined when no SQL definition is available.
|
|
200
|
+
* @throws {DneDatabaseClosedError} If the reader is closed, including for invalid input.
|
|
201
|
+
* @throws {DneDatabaseQueryError} If SQLite cannot prepare or execute the read.
|
|
202
|
+
*/
|
|
203
|
+
tableSchema(tableName) {
|
|
204
|
+
return this.readSafely(() => {
|
|
205
|
+
const row = this.db.query('SELECT sql FROM sqlite_master WHERE type = \'table\' AND name = ?').get(tableName);
|
|
206
|
+
return row?.sql ?? undefined;
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Executes caller-supplied SQL on the read-only connection, retaining a bounded result.
|
|
211
|
+
* @param sql - A statement accepted by SQLite; this method does not apply the CLI's statement filter.
|
|
212
|
+
* @param limit - Positive maximum number of rows to retain.
|
|
213
|
+
* @returns Rows plus a flag indicating whether at least one additional row was available.
|
|
214
|
+
* @throws {DneDatabaseClosedError} If the reader is closed, including for invalid input.
|
|
215
|
+
* @throws {DneDatabaseQueryError} If SQLite cannot prepare or execute the read.
|
|
216
|
+
*/
|
|
217
|
+
querySql(sql, limit) {
|
|
218
|
+
return this.readSafely(() => {
|
|
219
|
+
const rows = [];
|
|
220
|
+
const statement = this.db.query(sql);
|
|
221
|
+
try {
|
|
222
|
+
for (const value of statement.iterate()) {
|
|
223
|
+
rows.push(value);
|
|
224
|
+
if (rows.length > limit) {
|
|
225
|
+
break;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
finally {
|
|
230
|
+
statement.finalize();
|
|
231
|
+
}
|
|
232
|
+
return {
|
|
233
|
+
rows: rows.slice(0, limit),
|
|
234
|
+
truncated: rows.length > limit,
|
|
235
|
+
};
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
readSafely(read) {
|
|
239
|
+
if (this.closed) {
|
|
240
|
+
throw new DneDatabaseClosedError();
|
|
241
|
+
}
|
|
242
|
+
try {
|
|
243
|
+
return read();
|
|
244
|
+
}
|
|
245
|
+
catch (cause) {
|
|
246
|
+
if (cause instanceof DneDatabaseError) {
|
|
247
|
+
throw cause;
|
|
248
|
+
}
|
|
249
|
+
throw new DneDatabaseQueryError(cause instanceof Error ? cause.message : String(cause), { cause });
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Converts a supported SQLite URL to its path without resolving relative paths.
|
|
255
|
+
* @param value - Plain path, `:memory:`, or a URL beginning with `sqlite:///`.
|
|
256
|
+
* @returns The path after removing the supported URL prefix, without URI decoding.
|
|
257
|
+
* @throws {Error} If a different URL scheme is supplied.
|
|
258
|
+
*/
|
|
259
|
+
export function sqlitePathFromDatabaseUrl(value) {
|
|
260
|
+
if (!value.startsWith('sqlite:///')) {
|
|
261
|
+
if (value.includes('://')) {
|
|
262
|
+
throw new Error('Only sqlite:/// database URLs are supported');
|
|
263
|
+
}
|
|
264
|
+
return value;
|
|
265
|
+
}
|
|
266
|
+
return value.slice('sqlite:///'.length);
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Reads SQLite load metadata using a temporary read-only connection.
|
|
270
|
+
* @param databasePath - Path to the SQLite database.
|
|
271
|
+
* @returns Metadata, or undefined if the file or metadata table is missing.
|
|
272
|
+
* @throws {DneDatabaseIOError} If an existing database cannot be opened or closed.
|
|
273
|
+
* @throws {DneDatabaseQueryError} If its metadata cannot be queried.
|
|
274
|
+
*/
|
|
275
|
+
export async function readDatabaseMetadata(databasePath) {
|
|
276
|
+
if (databasePath !== ':memory:' && !(await Bun.file(databasePath).exists())) {
|
|
277
|
+
return undefined;
|
|
278
|
+
}
|
|
279
|
+
const reader = new DneDatabaseReader(databasePath);
|
|
280
|
+
try {
|
|
281
|
+
return reader.metadata();
|
|
282
|
+
}
|
|
283
|
+
finally {
|
|
284
|
+
reader.close();
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Checks for a SQLite table without creating a missing database.
|
|
289
|
+
* @param databasePath - Database file path; `:memory:` reports false.
|
|
290
|
+
* @param tableName - Physical table name to locate.
|
|
291
|
+
* @returns False for a missing database or table.
|
|
292
|
+
* @throws {DneDatabaseIOError} If an existing database cannot be opened or closed.
|
|
293
|
+
* @throws {DneDatabaseQueryError} If its catalog cannot be queried.
|
|
294
|
+
*/
|
|
295
|
+
export async function hasTable(databasePath, tableName) {
|
|
296
|
+
if (databasePath !== ':memory:' && !(await Bun.file(databasePath).exists())) {
|
|
297
|
+
return false;
|
|
298
|
+
}
|
|
299
|
+
const reader = new DneDatabaseReader(databasePath);
|
|
300
|
+
try {
|
|
301
|
+
return reader.hasTable(tableName);
|
|
302
|
+
}
|
|
303
|
+
finally {
|
|
304
|
+
reader.close();
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
//# sourceMappingURL=sqlite-db-reader.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sqlite-db-reader.js","sourceRoot":"","sources":["../src/sqlite-db-reader.ts"],"names":[],"mappings":"AAAA,OAAO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CAA6C,CAAC,CAAC;QACjE,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IACD,OAAO,KAAK,CAAC,KAAK,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;AAC1C,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,oBAAoB,CAAC,YAAoB;IAC7D,IAAI,YAAY,KAAK,UAAU,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC;QAC5E,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,MAAM,MAAM,GAAG,IAAI,iBAAiB,CAAC,YAAY,CAAC,CAAC;IACnD,IAAI,CAAC;QACH,OAAO,MAAM,CAAC,QAAQ,EAAE,CAAC;IAC3B,CAAC;YAAS,CAAC;QACT,MAAM,CAAC,KAAK,EAAE,CAAC;IACjB,CAAC;AACH,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,QAAQ,CAAC,YAAoB,EAAE,SAAiB;IACpE,IAAI,YAAY,KAAK,UAAU,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC;QAC5E,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,MAAM,GAAG,IAAI,iBAAiB,CAAC,YAAY,CAAC,CAAC;IACnD,IAAI,CAAC;QACH,OAAO,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;IACpC,CAAC;YAAS,CAAC;QACT,MAAM,CAAC,KAAK,EAAE,CAAC;IACjB,CAAC;AACH,CAAC"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { Database } from 'bun:sqlite';
|
|
2
|
+
import { type TableDefinition } from './schema.ts';
|
|
3
|
+
/**
|
|
4
|
+
* Creates a generated table, replacing it when its column names, order, or types differ.
|
|
5
|
+
* Call inside a transaction: replacing the table discards its current contents and indexes.
|
|
6
|
+
* @param db - Writable SQLite connection owned by the caller.
|
|
7
|
+
* @param table - Expected generated table definition.
|
|
8
|
+
* @throws {Error} If catalog inspection or schema creation fails.
|
|
9
|
+
*/
|
|
10
|
+
export declare function prepareTableForLoad(db: Database, table: TableDefinition): void;
|
|
11
|
+
/**
|
|
12
|
+
* Generates a single-line CREATE TABLE IF NOT EXISTS statement, including constraints.
|
|
13
|
+
* @param table - Trusted table and column definitions.
|
|
14
|
+
* @returns SQL using WITHOUT ROWID for a unified table.
|
|
15
|
+
*/
|
|
16
|
+
export declare function createTableSql(table: TableDefinition): string;
|
|
17
|
+
/**
|
|
18
|
+
* Generates a multiline CREATE TABLE statement for display and documentation.
|
|
19
|
+
* @param table - Trusted table and column definitions.
|
|
20
|
+
* @returns The same schema as `createTableSql`, with one definition per line.
|
|
21
|
+
*/
|
|
22
|
+
export declare function createPrettyTableSql(table: TableDefinition): string;
|
|
23
|
+
/**
|
|
24
|
+
* Resolves the address projection that retains the public CEP lookup columns.
|
|
25
|
+
* @param tableName - Physical normalized address table name.
|
|
26
|
+
* @returns The corresponding view name.
|
|
27
|
+
*/
|
|
28
|
+
export declare function cepViewName(tableName: string): string;
|
|
29
|
+
/**
|
|
30
|
+
* Creates the view that resolves neighborhood names and subordinate locality names.
|
|
31
|
+
* @param tableName - Physical normalized address table name.
|
|
32
|
+
* @param bairrosTableName - Physical neighborhood table name.
|
|
33
|
+
* @returns A quoted CREATE VIEW statement with the existing ten public address columns.
|
|
34
|
+
*/
|
|
35
|
+
export declare function createCepViewSql(tableName: string, bairrosTableName?: string): string;
|
|
36
|
+
/**
|
|
37
|
+
* Recreates the owned address, neighborhood, and interval tables inside the caller's transaction.
|
|
38
|
+
* Unrelated tables are retained. The transaction must be rolled back if importing or copying data fails.
|
|
39
|
+
* @param db - Writable SQLite connection with foreign keys enabled.
|
|
40
|
+
* @param schema - Source mappings and persisted table definitions.
|
|
41
|
+
* @throws {Error} If a required table definition is missing or SQLite rejects a schema operation.
|
|
42
|
+
*/
|
|
43
|
+
export declare function prepareDatabaseForLoad(db: Database, schema: readonly TableDefinition[]): void;
|
|
44
|
+
/**
|
|
45
|
+
* Quotes a SQLite identifier, escaping embedded double quotes.
|
|
46
|
+
* @param value - One identifier, not a dotted SQL expression.
|
|
47
|
+
* @returns A double-quoted identifier safe to interpolate into SQL.
|
|
48
|
+
*/
|
|
49
|
+
export declare function quoteIdent(value: string): string;
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { getStoredTables, getUnifiedTable, } from "./schema.js";
|
|
2
|
+
import { SQLITE_BAIRROS_TABLE_NAME } from "./settings.js";
|
|
3
|
+
/**
|
|
4
|
+
* Creates a generated table, replacing it when its column names, order, or types differ.
|
|
5
|
+
* Call inside a transaction: replacing the table discards its current contents and indexes.
|
|
6
|
+
* @param db - Writable SQLite connection owned by the caller.
|
|
7
|
+
* @param table - Expected generated table definition.
|
|
8
|
+
* @throws {Error} If catalog inspection or schema creation fails.
|
|
9
|
+
*/
|
|
10
|
+
export function prepareTableForLoad(db, table) {
|
|
11
|
+
const columns = db.query(`PRAGMA table_info(${quoteIdent(table.name)})`).all();
|
|
12
|
+
const definition = db.query('SELECT sql FROM sqlite_master WHERE type = \'table\' AND name = ?').get(table.name);
|
|
13
|
+
if (columns.length && (columns.length !== table.columns.length
|
|
14
|
+
|| columns.some((column, index) => column.name !== table.columns[index]?.name || column.type !== table.columns[index]?.type)
|
|
15
|
+
|| table.columns.some((column) => column.check && !definition?.sql.includes(`CHECK (${column.check})`)))) {
|
|
16
|
+
db.run(`DROP TABLE ${quoteIdent(table.name)}`);
|
|
17
|
+
}
|
|
18
|
+
db.run(createTableSql(table));
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Generates a single-line CREATE TABLE IF NOT EXISTS statement, including constraints.
|
|
22
|
+
* @param table - Trusted table and column definitions.
|
|
23
|
+
* @returns SQL using WITHOUT ROWID for a unified table.
|
|
24
|
+
*/
|
|
25
|
+
export function createTableSql(table) {
|
|
26
|
+
return createTableSqlWithSeparator(table, ', ');
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Generates a multiline CREATE TABLE statement for display and documentation.
|
|
30
|
+
* @param table - Trusted table and column definitions.
|
|
31
|
+
* @returns The same schema as `createTableSql`, with one definition per line.
|
|
32
|
+
*/
|
|
33
|
+
export function createPrettyTableSql(table) {
|
|
34
|
+
return createTableSqlWithSeparator(table, ',\n ');
|
|
35
|
+
}
|
|
36
|
+
function createTableSqlWithSeparator(table, separator) {
|
|
37
|
+
const primaryKeys = table.columns.filter((column) => column.primaryKey).map((column) => quoteIdent(column.name));
|
|
38
|
+
const definitions = table.columns.map((column) => {
|
|
39
|
+
const parts = [quoteIdent(column.name), column.type];
|
|
40
|
+
if (column.notNull || column.primaryKey) {
|
|
41
|
+
parts.push('NOT NULL');
|
|
42
|
+
}
|
|
43
|
+
if (column.check) {
|
|
44
|
+
parts.push(`CHECK (${column.check})`);
|
|
45
|
+
}
|
|
46
|
+
if (column.references) {
|
|
47
|
+
parts.push(`REFERENCES ${quoteIdent(column.references.table)} (${quoteIdent(column.references.column)})`);
|
|
48
|
+
}
|
|
49
|
+
if (column.comment) {
|
|
50
|
+
parts.push(`/* ${column.comment} */`);
|
|
51
|
+
}
|
|
52
|
+
return parts.join(' ');
|
|
53
|
+
});
|
|
54
|
+
if (primaryKeys.length) {
|
|
55
|
+
definitions.push(`PRIMARY KEY (${primaryKeys.join(', ')})`);
|
|
56
|
+
}
|
|
57
|
+
const withoutRowid = (table.withoutRowid ?? table.unifiedTable) ? ' WITHOUT ROWID' : '';
|
|
58
|
+
if (separator.includes('\n')) {
|
|
59
|
+
return `CREATE TABLE IF NOT EXISTS ${quoteIdent(table.name)} (\n ${definitions.join(separator)}\n)${withoutRowid}`;
|
|
60
|
+
}
|
|
61
|
+
return `CREATE TABLE IF NOT EXISTS ${quoteIdent(table.name)} (${definitions.join(separator)})${withoutRowid}`;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Resolves the address projection that retains the public CEP lookup columns.
|
|
65
|
+
* @param tableName - Physical normalized address table name.
|
|
66
|
+
* @returns The corresponding view name.
|
|
67
|
+
*/
|
|
68
|
+
export function cepViewName(tableName) {
|
|
69
|
+
return `${tableName}_consulta`;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Creates the view that resolves neighborhood names and subordinate locality names.
|
|
73
|
+
* @param tableName - Physical normalized address table name.
|
|
74
|
+
* @param bairrosTableName - Physical neighborhood table name.
|
|
75
|
+
* @returns A quoted CREATE VIEW statement with the existing ten public address columns.
|
|
76
|
+
*/
|
|
77
|
+
export function createCepViewSql(tableName, bairrosTableName = SQLITE_BAIRROS_TABLE_NAME) {
|
|
78
|
+
return `CREATE VIEW ${quoteIdent(cepViewName(tableName))} AS
|
|
79
|
+
SELECT d.cep, d.logradouro, d.complemento, COALESCE(b.nome, d.localidade_nome) AS bairro,
|
|
80
|
+
d.municipio, d.municipio_cod_ibge, d.uf, d.nome, d.localidade_situacao, d.localidade_tipo
|
|
81
|
+
FROM ${quoteIdent(tableName)} d
|
|
82
|
+
LEFT JOIN ${quoteIdent(bairrosTableName)} b ON b.bairro_id = d.bairro_id`;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Recreates the owned address, neighborhood, and interval tables inside the caller's transaction.
|
|
86
|
+
* Unrelated tables are retained. The transaction must be rolled back if importing or copying data fails.
|
|
87
|
+
* @param db - Writable SQLite connection with foreign keys enabled.
|
|
88
|
+
* @param schema - Source mappings and persisted table definitions.
|
|
89
|
+
* @throws {Error} If a required table definition is missing or SQLite rejects a schema operation.
|
|
90
|
+
*/
|
|
91
|
+
export function prepareDatabaseForLoad(db, schema) {
|
|
92
|
+
const cepTable = getUnifiedTable(schema);
|
|
93
|
+
const bairros = schema.find((table) => table.originalName === 'bairros');
|
|
94
|
+
if (!bairros) {
|
|
95
|
+
throw new Error('Neighborhood table definition is missing');
|
|
96
|
+
}
|
|
97
|
+
const stored = getStoredTables(schema);
|
|
98
|
+
db.run(`DROP VIEW IF EXISTS main.${quoteIdent(cepViewName(cepTable.name))}`);
|
|
99
|
+
for (const table of [...stored].reverse()) {
|
|
100
|
+
db.run(`DROP TABLE IF EXISTS main.${quoteIdent(table.name)}`);
|
|
101
|
+
}
|
|
102
|
+
for (const table of stored) {
|
|
103
|
+
db.run(createTableSql(table));
|
|
104
|
+
}
|
|
105
|
+
db.run(createCepViewSql(cepTable.name, bairros.name));
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Quotes a SQLite identifier, escaping embedded double quotes.
|
|
109
|
+
* @param value - One identifier, not a dotted SQL expression.
|
|
110
|
+
* @returns A double-quoted identifier safe to interpolate into SQL.
|
|
111
|
+
*/
|
|
112
|
+
export function quoteIdent(value) {
|
|
113
|
+
return `"${value.replaceAll('"', '""')}"`;
|
|
114
|
+
}
|
|
115
|
+
//# sourceMappingURL=sqlite-db-schema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sqlite-db-schema.js","sourceRoot":"","sources":["../src/sqlite-db-schema.ts"],"names":[],"mappings":"AACA,OAAO,EACL,eAAe,EACf,eAAe,GAEhB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,yBAAyB,EAAE,MAAM,eAAe,CAAC;AAE1D;;;;;;GAMG;AACH,MAAM,UAAU,mBAAmB,CAAC,EAAY,EAAE,KAAsB;IACtE,MAAM,OAAO,GAAG,EAAE,CAAC,KAAK,CAAC,qBAAqB,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAuC,CAAC;IACpH,MAAM,UAAU,GAAG,EAAE,CAAC,KAAK,CAAC,mEAAmE,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAEvG,CAAC;IACT,IACE,OAAO,CAAC,MAAM,IAAI,CAChB,OAAO,CAAC,MAAM,KAAK,KAAK,CAAC,OAAO,CAAC,MAAM;WACpC,OAAO,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