@konstit/dne 0.0.2 → 0.2.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.
Files changed (62) hide show
  1. package/README.md +87 -159
  2. package/data/dne.bin +0 -0
  3. package/dist/bairro-runs.d.ts +20 -0
  4. package/dist/bairro-runs.js +202 -0
  5. package/dist/bairro-runs.js.map +1 -0
  6. package/dist/bairro.d.ts +27 -0
  7. package/dist/bairro.js +9 -0
  8. package/dist/bairro.js.map +1 -0
  9. package/dist/binary-db-errors.d.ts +56 -0
  10. package/dist/binary-db-errors.js +68 -0
  11. package/dist/binary-db-errors.js.map +1 -0
  12. package/dist/binary-db-format.d.ts +200 -0
  13. package/dist/binary-db-format.js +258 -0
  14. package/dist/binary-db-format.js.map +1 -0
  15. package/dist/binary-db-integrity.d.ts +4 -0
  16. package/dist/binary-db-integrity.js +20 -0
  17. package/dist/binary-db-integrity.js.map +1 -0
  18. package/dist/binary-db-reader.d.ts +126 -0
  19. package/dist/binary-db-reader.js +556 -0
  20. package/dist/binary-db-reader.js.map +1 -0
  21. package/dist/binary-db-validator.d.ts +13 -0
  22. package/dist/binary-db-validator.js +712 -0
  23. package/dist/binary-db-validator.js.map +1 -0
  24. package/dist/cep.d.ts +50 -0
  25. package/dist/cep.js +184 -0
  26. package/dist/cep.js.map +1 -0
  27. package/dist/errors.d.ts +14 -0
  28. package/dist/errors.js +21 -0
  29. package/dist/errors.js.map +1 -0
  30. package/dist/fsst.d.ts +18 -0
  31. package/dist/fsst.js +117 -0
  32. package/dist/fsst.js.map +1 -0
  33. package/dist/index.js +55 -33
  34. package/dist/index.js.map +36 -16
  35. package/dist/library.d.ts +10 -0
  36. package/dist/library.js +8 -0
  37. package/dist/library.js.map +1 -0
  38. package/dist/locality-runs.d.ts +18 -0
  39. package/dist/locality-runs.js +108 -0
  40. package/dist/locality-runs.js.map +1 -0
  41. package/dist/packed-bits.d.ts +6 -0
  42. package/dist/packed-bits.js +41 -0
  43. package/dist/packed-bits.js.map +1 -0
  44. package/dist/schema.d.ts +88 -0
  45. package/dist/schema.js +233 -0
  46. package/dist/schema.js.map +1 -0
  47. package/dist/settings.d.ts +34 -0
  48. package/dist/settings.js +35 -0
  49. package/dist/settings.js.map +1 -0
  50. package/dist/sqlite-db-errors.d.ts +40 -0
  51. package/dist/sqlite-db-errors.js +54 -0
  52. package/dist/sqlite-db-errors.js.map +1 -0
  53. package/dist/sqlite-db-reader.d.ts +130 -0
  54. package/dist/sqlite-db-reader.js +307 -0
  55. package/dist/sqlite-db-reader.js.map +1 -0
  56. package/dist/sqlite-db-schema.d.ts +49 -0
  57. package/dist/sqlite-db-schema.js +115 -0
  58. package/dist/sqlite-db-schema.js.map +1 -0
  59. package/dist/types.d.ts +90 -0
  60. package/dist/types.js +49 -0
  61. package/dist/types.js.map +1 -0
  62. package/package.json +18 -5
@@ -0,0 +1,40 @@
1
+ /** Stable categories exposed by the SQLite reader for programmatic error handling. */
2
+ export type DneDatabaseErrorCode = 'IO_ERROR' | 'INVALID_SCHEMA' | 'INVALID_DATA' | 'QUERY_ERROR' | 'READER_CLOSED';
3
+ /** Base class for failures exposed by the SQLite reader and its file helpers. */
4
+ export declare abstract class DneDatabaseError extends Error {
5
+ /** Identifies the failure without requiring callers to parse its message. */
6
+ abstract readonly code: DneDatabaseErrorCode;
7
+ /** Preserves the original SQLite or filesystem failure in `cause`, when provided. */
8
+ protected constructor(message: string, options?: ErrorOptions);
9
+ }
10
+ /** A SQLite connection could not be opened, configured, or closed. */
11
+ export declare class DneDatabaseIOError extends DneDatabaseError {
12
+ readonly path: string;
13
+ readonly code = "IO_ERROR";
14
+ /** Creates an access error for the caller's database path. */
15
+ constructor(path: string, options?: ErrorOptions);
16
+ }
17
+ /** The database lacks the schema required for normalized address lookup. */
18
+ export declare class DneDatabaseSchemaError extends DneDatabaseError {
19
+ readonly code = "INVALID_SCHEMA";
20
+ /** Describes the missing schema feature and how to rebuild the database. */
21
+ constructor(message: string, options?: ErrorOptions);
22
+ }
23
+ /** A stored address contains invalid locality indicators. */
24
+ export declare class DneDatabaseDataError extends DneDatabaseError {
25
+ readonly code = "INVALID_DATA";
26
+ /** Describes invalid stored data, preserving a decoding cause when available. */
27
+ constructor(message: string, options?: ErrorOptions);
28
+ }
29
+ /** SQLite could not prepare or execute a read operation. */
30
+ export declare class DneDatabaseQueryError extends DneDatabaseError {
31
+ readonly code = "QUERY_ERROR";
32
+ /** Preserves the diagnostic message and native SQLite failure in `cause`. */
33
+ constructor(message: string, options?: ErrorOptions);
34
+ }
35
+ /** An operation was attempted after the reader closed its connection. */
36
+ export declare class DneDatabaseClosedError extends DneDatabaseError {
37
+ readonly code = "READER_CLOSED";
38
+ /** Creates an error for any read operation attempted after `close()`. */
39
+ constructor();
40
+ }
@@ -0,0 +1,54 @@
1
+ /** Base class for failures exposed by the SQLite reader and its file helpers. */
2
+ export class DneDatabaseError extends Error {
3
+ /** Preserves the original SQLite or filesystem failure in `cause`, when provided. */
4
+ constructor(message, options) {
5
+ super(message, options);
6
+ this.name = new.target.name;
7
+ }
8
+ }
9
+ /** A SQLite connection could not be opened, configured, or closed. */
10
+ export class DneDatabaseIOError extends DneDatabaseError {
11
+ path;
12
+ code = 'IO_ERROR';
13
+ /** Creates an access error for the caller's database path. */
14
+ constructor(path, options) {
15
+ super(`Unable to access SQLite database: ${path}`, options);
16
+ this.path = path;
17
+ }
18
+ }
19
+ /** The database lacks the schema required for normalized address lookup. */
20
+ export class DneDatabaseSchemaError extends DneDatabaseError {
21
+ code = 'INVALID_SCHEMA';
22
+ /** Describes the missing schema feature and how to rebuild the database. */
23
+ // biome-ignore lint/complexity/noUselessConstructor: Exposes the protected base constructor as a public API.
24
+ constructor(message, options) {
25
+ super(message, options);
26
+ }
27
+ }
28
+ /** A stored address contains invalid locality indicators. */
29
+ export class DneDatabaseDataError extends DneDatabaseError {
30
+ code = 'INVALID_DATA';
31
+ /** Describes invalid stored data, preserving a decoding cause when available. */
32
+ // biome-ignore lint/complexity/noUselessConstructor: Exposes the protected base constructor as a public API.
33
+ constructor(message, options) {
34
+ super(message, options);
35
+ }
36
+ }
37
+ /** SQLite could not prepare or execute a read operation. */
38
+ export class DneDatabaseQueryError extends DneDatabaseError {
39
+ code = 'QUERY_ERROR';
40
+ /** Preserves the diagnostic message and native SQLite failure in `cause`. */
41
+ // biome-ignore lint/complexity/noUselessConstructor: Exposes the protected base constructor as a public API.
42
+ constructor(message, options) {
43
+ super(message, options);
44
+ }
45
+ }
46
+ /** An operation was attempted after the reader closed its connection. */
47
+ export class DneDatabaseClosedError extends DneDatabaseError {
48
+ code = 'READER_CLOSED';
49
+ /** Creates an error for any read operation attempted after `close()`. */
50
+ constructor() {
51
+ super('SQLite database is closed');
52
+ }
53
+ }
54
+ //# sourceMappingURL=sqlite-db-errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlite-db-errors.js","sourceRoot":"","sources":["../src/sqlite-db-errors.ts"],"names":[],"mappings":"AAGA,iFAAiF;AACjF,MAAM,OAAgB,gBAAiB,SAAQ,KAAK;IAIlD,qFAAqF;IACrF,YAAsB,OAAe,EAAE,OAAsB;QAC3D,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC;IAC9B,CAAC;CACF;AAED,sEAAsE;AACtE,MAAM,OAAO,kBAAmB,SAAQ,gBAAgB;IAIjC;IAHZ,IAAI,GAAG,UAAU,CAAC;IAE3B,8DAA8D;IAC9D,YAAqB,IAAY,EAAE,OAAsB;QACvD,KAAK,CAAC,qCAAqC,IAAI,EAAE,EAAE,OAAO,CAAC,CAAC;QADzC,SAAI,GAAJ,IAAI,CAAQ;IAEjC,CAAC;CACF;AAED,4EAA4E;AAC5E,MAAM,OAAO,sBAAuB,SAAQ,gBAAgB;IACjD,IAAI,GAAG,gBAAgB,CAAC;IAEjC,4EAA4E;IAC5E,6GAA6G;IAC7G,YAAY,OAAe,EAAE,OAAsB;QACjD,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC1B,CAAC;CACF;AAED,6DAA6D;AAC7D,MAAM,OAAO,oBAAqB,SAAQ,gBAAgB;IAC/C,IAAI,GAAG,cAAc,CAAC;IAE/B,iFAAiF;IACjF,6GAA6G;IAC7G,YAAY,OAAe,EAAE,OAAsB;QACjD,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC1B,CAAC;CACF;AAED,4DAA4D;AAC5D,MAAM,OAAO,qBAAsB,SAAQ,gBAAgB;IAChD,IAAI,GAAG,aAAa,CAAC;IAE9B,6EAA6E;IAC7E,6GAA6G;IAC7G,YAAY,OAAe,EAAE,OAAsB;QACjD,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC1B,CAAC;CACF;AAED,yEAAyE;AACzE,MAAM,OAAO,sBAAuB,SAAQ,gBAAgB;IACjD,IAAI,GAAG,eAAe,CAAC;IAEhC,yEAAyE;IACzE;QACE,KAAK,CAAC,2BAA2B,CAAC,CAAC;IACrC,CAAC;CACF"}
@@ -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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KAAK,CAAC,6CAA6C,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;