text-to-map 1.0.7 → 1.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.
Files changed (39) hide show
  1. package/dist/bin/clear-all.js +21 -4
  2. package/dist/bin/init-db.d.ts +1 -0
  3. package/dist/bin/init-db.js +18 -0
  4. package/dist/bin/parse-ordinance.js +56 -42
  5. package/dist/bin/schools.js +1 -1
  6. package/dist/db/address-points.d.ts +13 -13
  7. package/dist/db/address-points.js +93 -77
  8. package/dist/db/db.d.ts +19 -10
  9. package/dist/db/db.js +124 -50
  10. package/dist/db/founders.d.ts +7 -7
  11. package/dist/db/founders.js +187 -135
  12. package/dist/db/meta.d.ts +3 -4
  13. package/dist/db/meta.js +23 -16
  14. package/dist/db/migrations/20230704125715_initial.d.ts +3 -0
  15. package/dist/db/migrations/20230704125715_initial.js +251 -0
  16. package/dist/db/regions.d.ts +5 -5
  17. package/dist/db/regions.js +40 -28
  18. package/dist/db/schools.d.ts +3 -2
  19. package/dist/db/schools.js +30 -14
  20. package/dist/db/street-sync.d.ts +4 -4
  21. package/dist/db/street-sync.js +26 -17
  22. package/dist/index.d.ts +3 -2
  23. package/dist/index.js +4 -2
  24. package/dist/open-data-sync/address-points.d.ts +0 -1
  25. package/dist/open-data-sync/address-points.js +35 -25
  26. package/dist/open-data-sync/regions.js +13 -5
  27. package/dist/open-data-sync/schools.js +19 -15
  28. package/dist/open-data-sync/streets.js +46 -33
  29. package/dist/street-markdown/municipality.d.ts +2 -2
  30. package/dist/street-markdown/municipality.js +46 -14
  31. package/dist/street-markdown/smd-line-parser.d.ts +1 -1
  32. package/dist/street-markdown/smd-line-parser.js +21 -8
  33. package/dist/street-markdown/smd.d.ts +8 -5
  34. package/dist/street-markdown/smd.js +100 -86
  35. package/dist/street-markdown/token-definition.js +6 -6
  36. package/dist/street-markdown/types.d.ts +8 -3
  37. package/dist/utils/helpers.d.ts +0 -1
  38. package/dist/utils/helpers.js +1 -8
  39. package/package.json +9 -5
@@ -1,6 +1,23 @@
1
- import { deleteDb } from "../open-data-sync/address-points";
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { clearDb, disconnectKnex } from "../db/db";
2
11
  import { deleteSchoolsXmlFile } from "../open-data-sync/schools";
3
12
  import { defaultBinOptions } from "./constants";
4
- deleteDb(defaultBinOptions);
5
- deleteSchoolsXmlFile(defaultBinOptions);
6
- console.log("Everything cleared, ready for a new sync.");
13
+ function main() {
14
+ return __awaiter(this, void 0, void 0, function* () {
15
+ console.log("Clearing all data...");
16
+ yield clearDb();
17
+ console.log("DB cleared. Now deleting schools XML file...");
18
+ deleteSchoolsXmlFile(defaultBinOptions);
19
+ yield disconnectKnex();
20
+ console.log("Everything cleared, ready for a new sync.");
21
+ });
22
+ }
23
+ main();
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,18 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { disconnectKnex, initDb } from "../db/db";
11
+ function main() {
12
+ return __awaiter(this, void 0, void 0, function* () {
13
+ yield initDb();
14
+ console.log("Database ready to use.");
15
+ yield disconnectKnex();
16
+ });
17
+ }
18
+ main();
@@ -1,45 +1,59 @@
1
- import { readFileSync, writeFileSync } from "fs";
2
- import { getNewMunicipality, parseOrdinanceToAddressPoints } from "../street-markdown/smd";
3
- import { defaultBinOptions } from "./constants";
4
- // take first node argument as a file name
5
- if (process.argv.length < 3) {
6
- console.error("Missing file name argument");
7
- process.exit(1);
8
- }
9
- const fileName = process.argv[2];
10
- const fileContent = readFileSync(fileName);
11
- const lines = fileContent.toString().split("\n");
12
- let errorCount = 0;
13
- const errorLines = [];
14
- let warningCount = 0;
15
- const reportErrors = ({ lineNumber, line, errors, }) => {
16
- errors.forEach(console.error);
17
- console.error(`Invalid street definition on line ${lineNumber}: ${line}`);
18
- errorCount++;
19
- errorLines.push(`line ${lineNumber}: ${line}`);
20
- };
21
- const reportWarnings = ({ lineNumber, errors: warnings, }) => {
22
- warnings.map((error) => {
23
- console.error(`Line ${lineNumber}: ${error}`);
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
24
8
  });
25
- warningCount++;
26
9
  };
27
- console.time("downloadAndImportAllLatestAddressPoints");
28
- const addressPoints = parseOrdinanceToAddressPoints(lines, defaultBinOptions, {
29
- currentMunicipality: getNewMunicipality("Česká Lípa", defaultBinOptions),
30
- }, reportErrors, reportWarnings);
31
- console.timeEnd("downloadAndImportAllLatestAddressPoints");
32
- console.log(`Parsed ${lines.length} lines, ${errorCount} errors, ${warningCount} warnings.`);
33
- if (errorCount > 0) {
34
- console.log("Errors:");
35
- errorLines.forEach((line) => console.log(line));
36
- }
37
- if (process.argv.length >= 4) {
38
- const outputFileName = process.argv[3];
39
- const output = JSON.stringify(addressPoints);
40
- console.log(`Writing output to ${outputFileName}`);
41
- writeFileSync(outputFileName, output);
42
- }
43
- else {
44
- console.log(JSON.stringify(addressPoints));
10
+ import { readFileSync, writeFileSync } from "fs";
11
+ import { getNewMunicipality, parseOrdinanceToAddressPoints, } from "../street-markdown/smd";
12
+ function main() {
13
+ return __awaiter(this, void 0, void 0, function* () {
14
+ // take first node argument as a file name
15
+ if (process.argv.length < 3) {
16
+ console.error("Missing file name argument");
17
+ process.exit(1);
18
+ }
19
+ const fileName = process.argv[2];
20
+ const fileContent = readFileSync(fileName);
21
+ const lines = fileContent.toString().split("\n");
22
+ let errorCount = 0;
23
+ const errorLines = [];
24
+ let warningCount = 0;
25
+ const reportErrors = ({ lineNumber, line, errors, }) => {
26
+ errors.forEach((error) => console.error(error));
27
+ console.error(`Invalid street definition on line ${lineNumber}: ${line}`);
28
+ errorCount++;
29
+ errorLines.push(`line ${lineNumber}: ${line}`);
30
+ };
31
+ const reportWarnings = ({ lineNumber, errors: warnings, }) => {
32
+ warnings.forEach((error) => {
33
+ console.error(`Line ${lineNumber}: ${error.message}`);
34
+ });
35
+ warningCount++;
36
+ };
37
+ console.time("downloadAndImportAllLatestAddressPoints");
38
+ const { municipality } = yield getNewMunicipality("Česká Lípa");
39
+ const addressPoints = yield parseOrdinanceToAddressPoints(lines, {
40
+ // currentMunicipality: municipality,
41
+ }, reportErrors, reportWarnings);
42
+ console.timeEnd("downloadAndImportAllLatestAddressPoints");
43
+ console.log(`Parsed ${lines.length} lines, ${errorCount} errors, ${warningCount} warnings.`);
44
+ if (errorCount > 0) {
45
+ console.log("Errors:");
46
+ errorLines.forEach((line) => console.log(line));
47
+ }
48
+ if (process.argv.length >= 4) {
49
+ const outputFileName = process.argv[3];
50
+ const output = JSON.stringify(addressPoints);
51
+ console.log(`Writing output to ${outputFileName}`);
52
+ writeFileSync(outputFileName, output);
53
+ }
54
+ else {
55
+ console.log(JSON.stringify(addressPoints));
56
+ }
57
+ });
45
58
  }
59
+ main();
@@ -1,6 +1,6 @@
1
1
  import { downloadAndImportSchools } from "../open-data-sync/schools";
2
2
  import { defaultBinOptions } from "./constants";
3
- downloadAndImportSchools(defaultBinOptions, true)
3
+ downloadAndImportSchools(defaultBinOptions)
4
4
  .then(() => {
5
5
  console.log("Completed");
6
6
  })
@@ -1,4 +1,4 @@
1
- import { AddressPoint, FullStreetNumber, RangeSpec, SeriesType, SmdLine, WholeMunicipalitySmdLine } from "../street-markdown/types";
1
+ import { AddressPoint, FullStreetNumber, RangeSpec, SeriesType, SmdError, SmdLine, WholeMunicipalitySmdLine } from "../street-markdown/types";
2
2
  import { Founder, Municipality } from "./types";
3
3
  export declare const Column: {
4
4
  admCode: number;
@@ -21,19 +21,19 @@ export declare const Column: {
21
21
  xCoordinate: number;
22
22
  validFrom: number;
23
23
  };
24
- export declare const importParsedLine: (data: string[]) => number;
25
- export declare const commitAddressPoints: () => number;
26
- export declare const insertCities: (buffer: string[][]) => number;
27
- export declare const insertDistricts: (buffer: string[][]) => number;
28
- export declare const insertMunicipalityParts: (buffer: string[][]) => number;
29
- export declare const insertPragueDistricts: (buffer: string[][]) => number;
30
- export declare const insertStreets: (buffer: string[][]) => number;
31
- export declare const getAddressPointById: (addressPointId: number) => AddressPoint | null;
32
- export declare const checkStreetExists: (streetName: string, founder: Founder) => {
24
+ export declare const commitAddressPoints: (buffer: string[][]) => Promise<number>;
25
+ export declare const insertCities: (buffer: string[][]) => Promise<number>;
26
+ export declare const insertDistricts: (buffer: string[][]) => Promise<number>;
27
+ export declare const insertMunicipalityParts: (buffer: string[][]) => Promise<number>;
28
+ export declare const insertPragueDistricts: (buffer: string[][]) => Promise<number>;
29
+ export declare const insertStreets: (buffer: string[][]) => Promise<number>;
30
+ export declare const areAddressPointsSynced: () => Promise<boolean>;
31
+ export declare const getAddressPointById: (addressPointId: number) => Promise<AddressPoint | null>;
32
+ export declare const checkStreetExists: (streetName: string, founder: Founder) => Promise<{
33
33
  exists: boolean;
34
- errors: string[];
35
- };
36
- export declare const findAddressPoints: (smdLine: SmdLine | WholeMunicipalitySmdLine, municipality: Municipality) => AddressPoint[];
34
+ errors: SmdError[];
35
+ }>;
36
+ export declare const findAddressPoints: (smdLine: SmdLine | WholeMunicipalitySmdLine, municipality: Municipality) => Promise<AddressPoint[]>;
37
37
  export declare const isInRange: (number: number | null, letter: string | null, range: RangeSpec) => boolean;
38
38
  export declare const fitsType: (number: number | null, type: SeriesType) => boolean;
39
39
  export declare const equalsFullStreetNumber: (fullStreetNumber: FullStreetNumber, addressPoint: AddressPoint) => boolean;
@@ -1,12 +1,19 @@
1
- import jtsk2wgs84 from "../utils/jtsk2wgs84";
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
2
10
  import { AddressPointType, createSingleLineAddress } from "czech-address";
3
11
  import { SeriesType, isNegativeSeriesSpec, isRange, isSeriesSpecArray, isWholeMunicipalitySmdLine, } from "../street-markdown/types";
4
12
  import { findClosestString } from "../utils/helpers";
5
- import { extractKeyValuesPairs, generate2DPlaceholders, getDb, insertMultipleRows, nonEmptyOrNull, } from "./db";
13
+ import jtsk2wgs84 from "../utils/jtsk2wgs84";
14
+ import { extractKeyValuesPairs, generate2DPlaceholders, getKnexDb, insertMultipleRows, isSqlite, nonEmptyOrNull } from "./db";
6
15
  import { getFounderCityCode } from "./founders";
7
16
  import { MunicipalityType } from "./types";
8
- const buffer = [];
9
- const MaxBufferSize = 1000;
10
17
  const DescriptiveType = "č.p.";
11
18
  const RegistrationType = "č.ev.";
12
19
  const ObjectTypes = {
@@ -34,27 +41,32 @@ export const Column = {
34
41
  xCoordinate: 17,
35
42
  validFrom: 18,
36
43
  };
37
- export const importParsedLine = (data) => {
38
- buffer.push(data);
39
- if (buffer.length >= MaxBufferSize) {
40
- return commitAddressPoints();
41
- }
42
- return 0;
43
- };
44
- export const commitAddressPoints = () => {
44
+ const columnNames = [
45
+ "id",
46
+ "street_code",
47
+ "object_type_id",
48
+ "descriptive_number",
49
+ "orientational_number",
50
+ "orientational_number_letter",
51
+ "city_code",
52
+ "city_district_code",
53
+ "municipality_part_code",
54
+ "prague_district_code",
55
+ "postal_code",
56
+ "jtsk_x",
57
+ "jtsk_y",
58
+ "wgs84_latitude",
59
+ "wgs84_longitude",
60
+ ];
61
+ export const commitAddressPoints = (buffer) => __awaiter(void 0, void 0, void 0, function* () {
45
62
  if (buffer.length === 0) {
46
63
  return 0;
47
64
  }
48
- insertCities(buffer);
49
- insertDistricts(buffer);
50
- insertMunicipalityParts(buffer);
51
- insertStreets(buffer);
52
- insertPragueDistricts(buffer);
53
- const db = getDb();
54
- const placeHolders = generate2DPlaceholders(15, buffer.length);
55
- const insertStatement = db.prepare(`INSERT OR IGNORE INTO address_point
56
- (id, street_code, object_type_id, descriptive_number, orientational_number, orientational_number_letter, city_code, city_district_code, municipality_part_code, prague_district_code, postal_code, jtsk_x, jtsk_y, wgs84_latitude, wgs84_longitude)
57
- VALUES ${placeHolders}`);
65
+ yield insertCities(buffer);
66
+ yield insertDistricts(buffer);
67
+ yield insertMunicipalityParts(buffer);
68
+ yield insertStreets(buffer);
69
+ yield insertPragueDistricts(buffer);
58
70
  const params = [];
59
71
  buffer.forEach((data) => {
60
72
  let latOrNull, lonOrNull;
@@ -66,34 +78,39 @@ export const commitAddressPoints = () => {
66
78
  }
67
79
  params.push(data[Column.admCode], nonEmptyOrNull(data[Column.streetCode]), ObjectTypes[data[Column.objectType]], nonEmptyOrNull(data[Column.houseNumber]), nonEmptyOrNull(data[Column.orientationalNumber]), nonEmptyOrNull(data[Column.orientationalNumberLetter]), data[Column.cityCode], nonEmptyOrNull(data[Column.districtCode]), nonEmptyOrNull(data[Column.municipalityPartCode]), nonEmptyOrNull(data[Column.pragueDistrictCode]), data[Column.postalCode], nonEmptyOrNull(data[Column.xCoordinate]), nonEmptyOrNull(data[Column.yCoordinate]), latOrNull, lonOrNull);
68
80
  });
69
- buffer.length = 0;
70
- return insertStatement.run(params).changes;
71
- };
72
- export const insertCities = (buffer) => {
73
- return insertMultipleRows(extractKeyValuesPairs(buffer, Column.cityCode, [Column.cityName]), "city", ["code", "name"]);
74
- };
75
- export const insertDistricts = (buffer) => {
76
- return insertMultipleRows(extractKeyValuesPairs(buffer, Column.districtCode, [
81
+ const placeHolders = generate2DPlaceholders(columnNames.length, buffer.length);
82
+ yield getKnexDb().raw(`INSERT INTO address_point (${columnNames.join(",")}) VALUES ${placeHolders} ON CONFLICT (id) DO NOTHING`, params);
83
+ return buffer.length;
84
+ });
85
+ export const insertCities = (buffer) => __awaiter(void 0, void 0, void 0, function* () {
86
+ return yield insertMultipleRows(extractKeyValuesPairs(buffer, Column.cityCode, [Column.cityName]), "city", ["code", "name"]);
87
+ });
88
+ export const insertDistricts = (buffer) => __awaiter(void 0, void 0, void 0, function* () {
89
+ return yield insertMultipleRows(extractKeyValuesPairs(buffer, Column.districtCode, [
77
90
  Column.cityCode,
78
91
  Column.districtName,
79
92
  ]), "city_district", ["code", "city_code", "name"]);
80
- };
81
- export const insertMunicipalityParts = (buffer) => {
82
- return insertMultipleRows(extractKeyValuesPairs(buffer, Column.municipalityPartCode, [
93
+ });
94
+ export const insertMunicipalityParts = (buffer) => __awaiter(void 0, void 0, void 0, function* () {
95
+ return yield insertMultipleRows(extractKeyValuesPairs(buffer, Column.municipalityPartCode, [
83
96
  Column.municipalityPartName,
84
97
  ]), "municipality_part", ["code", "name"]);
85
- };
86
- export const insertPragueDistricts = (buffer) => {
87
- return insertMultipleRows(extractKeyValuesPairs(buffer, Column.pragueDistrictCode, [
98
+ });
99
+ export const insertPragueDistricts = (buffer) => __awaiter(void 0, void 0, void 0, function* () {
100
+ return yield insertMultipleRows(extractKeyValuesPairs(buffer, Column.pragueDistrictCode, [
88
101
  Column.pragueDistrictName,
89
102
  ]), "prague_district", ["code", "name"]);
90
- };
91
- export const insertStreets = (buffer) => {
92
- return insertMultipleRows(extractKeyValuesPairs(buffer, Column.streetCode, [
103
+ });
104
+ export const insertStreets = (buffer) => __awaiter(void 0, void 0, void 0, function* () {
105
+ return yield insertMultipleRows(extractKeyValuesPairs(buffer, Column.streetCode, [
93
106
  Column.cityCode,
94
107
  Column.streetName,
95
108
  ]), "street", ["code", "city_code", "name"]);
96
- };
109
+ });
110
+ export const areAddressPointsSynced = () => __awaiter(void 0, void 0, void 0, function* () {
111
+ const result = yield getKnexDb().count("*", { as: "countAll" }).from("address_point").first();
112
+ return Number(result.countAll) >= 2900000; // total is almost 3 million
113
+ });
97
114
  const addressPointSelect = `
98
115
  SELECT a.id, s.name AS street_name, o.name AS object_type_name, a.descriptive_number,
99
116
  a.orientational_number, a.orientational_number_letter, c.name AS city_name,
@@ -106,29 +123,27 @@ const addressPointSelect = `
106
123
  LEFT JOIN city_district d ON a.city_district_code = d.code
107
124
  LEFT JOIN prague_district p ON a.prague_district_code = p.code
108
125
  LEFT JOIN municipality_part m ON a.municipality_part_code = m.code`;
109
- export const getAddressPointById = (addressPointId) => {
110
- const db = getDb();
111
- const statement = db.prepare(`${addressPointSelect}
112
- WHERE a.id = ?`);
113
- const row = statement.get(addressPointId);
126
+ export const getAddressPointById = (addressPointId) => __awaiter(void 0, void 0, void 0, function* () {
127
+ const knex = getKnexDb();
128
+ const row = yield knex.raw(`${addressPointSelect}
129
+ WHERE a.id = ?`, [addressPointId]);
114
130
  if (!row) {
115
131
  return null;
116
132
  }
117
133
  return rowToAddressPoint(row);
118
- };
134
+ });
119
135
  let lastFounder = null;
120
136
  let allStreets = [];
121
- export const checkStreetExists = (streetName, founder) => {
122
- const db = getDb();
137
+ export const checkStreetExists = (streetName, founder) => __awaiter(void 0, void 0, void 0, function* () {
138
+ const knex = getKnexDb();
123
139
  const errors = [];
124
140
  // we check the whole city
125
- const cityCode = getFounderCityCode(founder);
126
- const statement = db.prepare(`
127
- SELECT name AS street_name
141
+ const cityCode = yield getFounderCityCode(founder);
142
+ const rowList = yield knex.raw(`SELECT name AS street_name
128
143
  FROM street
129
- WHERE city_code = ? AND name = ? COLLATE NOCASE`);
130
- const row = statement.get(cityCode, streetName);
131
- if (row) {
144
+ WHERE city_code = ? AND name = ? ${isSqlite() ? "COLLATE NOCASE" : ""}`, [cityCode, streetName]);
145
+ if (rowList.length > 0) {
146
+ const row = rowList[0];
132
147
  if (row.street_name !== streetName) {
133
148
  // errors.push(
134
149
  // `Street '${streetName}' has wrong case, correct case: '${row.street_name}'.`
@@ -137,7 +152,7 @@ export const checkStreetExists = (streetName, founder) => {
137
152
  return { exists: true, errors };
138
153
  }
139
154
  if (lastFounder !== founder) {
140
- allStreets = getAllStreets(cityCode);
155
+ allStreets = yield getAllStreets(cityCode);
141
156
  lastFounder = founder;
142
157
  }
143
158
  const match = allStreets.find((s) => s.toLocaleLowerCase("cs-CZ") === streetName.toLocaleLowerCase("cs-CZ"));
@@ -153,26 +168,30 @@ export const checkStreetExists = (streetName, founder) => {
153
168
  }
154
169
  else {
155
170
  const closest = findClosestString(streetName, allStreets);
156
- errors.push(`Street '${streetName}' does not exist, did you mean '${closest}'?`);
171
+ errors.push({
172
+ message: `Ulice '${streetName}' v této obci neexistuje, mysleli jste '${closest}'?`,
173
+ startOffset: 0,
174
+ endOffset: streetName.length + 1,
175
+ });
157
176
  }
158
177
  return { exists: false, errors };
159
- };
160
- const getAllStreets = (cityCode) => {
161
- const db = getDb();
162
- const statement = db.prepare(`
163
- SELECT s.name AS street_name
164
- FROM street s
165
- WHERE city_code = ?`);
166
- const rows = statement.all(cityCode);
167
- return rows.map((row) => row.street_name);
168
- };
169
- export const findAddressPoints = (smdLine, municipality) => {
170
- const db = getDb();
178
+ });
179
+ const getAllStreets = (cityCode) => __awaiter(void 0, void 0, void 0, function* () {
180
+ const knex = getKnexDb();
181
+ return yield knex
182
+ .pluck("name")
183
+ .from("street")
184
+ .where("city_code", cityCode);
185
+ });
186
+ export const findAddressPoints = (smdLine, municipality) => __awaiter(void 0, void 0, void 0, function* () {
187
+ const knex = getKnexDb();
188
+ const params = isWholeMunicipalitySmdLine(smdLine)
189
+ ? [municipality.code]
190
+ : [smdLine.street, municipality.code];
171
191
  const streetJoinCondition = isWholeMunicipalitySmdLine(smdLine)
172
192
  ? "LEFT JOIN street s ON a.street_code = s.code"
173
- : "JOIN street s ON a.street_code = s.code AND s.name = ? COLLATE NOCASE";
174
- const statement = db.prepare(`
175
- SELECT a.id, s.name AS street_name, o.name AS object_type_name, a.descriptive_number,
193
+ : `JOIN street s ON a.street_code = s.code AND s.name = ? ${isSqlite() ? "COLLATE NOCASE" : ""}`;
194
+ const queryResult = yield knex.raw(`SELECT a.id, s.name AS street_name, o.name AS object_type_name, a.descriptive_number,
176
195
  a.orientational_number, a.orientational_number_letter, c.name AS city_name,
177
196
  d.name AS district_name, m.name AS municipality_part_name, p.name AS prague_district_name,
178
197
  a.postal_code, a.wgs84_latitude, a.wgs84_longitude
@@ -183,11 +202,8 @@ export const findAddressPoints = (smdLine, municipality) => {
183
202
  LEFT JOIN city_district d ON a.city_district_code = d.code
184
203
  LEFT JOIN municipality_part m ON a.municipality_part_code = m.code
185
204
  LEFT JOIN prague_district p ON a.prague_district_code = p.code
186
- WHERE ${getMunicipalityWhere("a", municipality)}`);
187
- const params = isWholeMunicipalitySmdLine(smdLine)
188
- ? [municipality.code]
189
- : [smdLine.street, municipality.code];
190
- const filteredAddressPoints = statement.all(...params).map(rowToAddressPoint);
205
+ WHERE ${getMunicipalityWhere("a", municipality)}`, params);
206
+ const filteredAddressPoints = queryResult.map(rowToAddressPoint);
191
207
  if (isWholeMunicipalitySmdLine(smdLine)) {
192
208
  return filteredAddressPoints;
193
209
  }
@@ -208,7 +224,7 @@ export const findAddressPoints = (smdLine, municipality) => {
208
224
  result.push(...filteredAddressPoints.filter((addressPoint) => !toExclude.includes(addressPoint)));
209
225
  }
210
226
  return result;
211
- };
227
+ });
212
228
  const filterAddressPointsByRanges = (addressPoints, seriesSpec) => {
213
229
  const result = [];
214
230
  seriesSpec.ranges.forEach((range) => {
package/dist/db/db.d.ts CHANGED
@@ -1,24 +1,33 @@
1
- import Database from "better-sqlite3";
1
+ import { Knex } from "knex";
2
2
  interface DbConfig {
3
- initFilePath?: string;
3
+ dbType: SupportedDbType;
4
+ pgConnectionString?: string;
5
+ initFilePath: string;
4
6
  filePath?: string;
5
- verbose?: boolean;
7
+ verbose: boolean;
6
8
  }
7
- export declare const setDbConfig: (config: DbConfig) => void;
8
- export declare const getDb: (config?: DbConfig) => Database.Database;
9
+ export declare enum SupportedDbType {
10
+ sqlite = "sqlite",
11
+ postgres = "postgres"
12
+ }
13
+ export declare const getKnexDb: (config?: Partial<DbConfig>) => Knex;
14
+ export declare const isPostgres: () => boolean;
15
+ export declare const isSqlite: () => boolean;
16
+ export declare const initDb: (config?: Partial<DbConfig>) => Promise<Knex>;
17
+ export declare const clearDb: (config?: Partial<DbConfig>) => Promise<Knex>;
18
+ export declare const disconnectKnex: () => Promise<void>;
9
19
  export declare const nonEmptyOrNull: (value: string) => string | null;
10
20
  /**
11
21
  * Efficiently insert multiple rows. If preventDuplicatesByFirstColumn is true, the first
12
22
  * column should be unique (PK or UNIQUE).
13
23
  */
14
- export declare const insertMultipleRows: (rows: string[][], table: string, columnNames: string[], preventDuplicatesByFirstColumn?: boolean) => number;
24
+ export declare const insertMultipleRows: (rows: string[][], table: string, columnNames: string[], preventDuplicatesByFirstColumn?: boolean) => Promise<number>;
15
25
  /**
16
26
  * Insert a single row and return the autoincremented ID.
17
27
  */
18
- export declare const insertAutoincrementRow: (row: string[], table: string, columnNames: string[]) => number | null;
19
- export declare const deleteMultipleRows: (keys: string[], table: string, keyColumnName: string) => void;
20
- export declare const clearDuplicates: (rows: string[][], table: string, columnNames: string[]) => string[][];
21
- export declare const disconnect: () => void;
28
+ export declare const insertAutoincrementRow: (row: string[], table: string, columnNames: string[]) => Promise<number | null>;
29
+ export declare const deleteMultipleRowsKnex: (keys: string[], table: string, keyColumnName: string) => Promise<void>;
30
+ export declare const clearDuplicates: (rows: string[][], table: string, columnNames: string[]) => Promise<string[][]>;
22
31
  export declare const generatePlaceholders: (n: number) => string;
23
32
  export declare const generate2DPlaceholders: (inner: number, outer: number) => string;
24
33
  export declare const extractKeyValuesPairs: (array: string[][], keyIndex: number, valuesIndices: number[]) => string[][];