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
package/dist/db/db.js CHANGED
@@ -1,30 +1,108 @@
1
- import Database from "better-sqlite3";
2
- import { existsSync, copyFileSync } from "fs";
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 { configDotenv } from "dotenv";
11
+ import knex from "knex";
3
12
  import { dirname, join } from "path";
4
13
  import { fileURLToPath } from "url";
5
- let _db;
6
14
  const __filename = fileURLToPath(import.meta.url);
7
15
  const __dirname = dirname(__filename);
16
+ export var SupportedDbType;
17
+ (function (SupportedDbType) {
18
+ SupportedDbType["sqlite"] = "sqlite";
19
+ SupportedDbType["postgres"] = "postgres";
20
+ })(SupportedDbType || (SupportedDbType = {}));
8
21
  const defaults = {
22
+ dbType: SupportedDbType.sqlite,
9
23
  filePath: "address_points.db",
10
24
  initFilePath: join(__dirname, "..", "address_points_init.db"),
11
25
  verbose: false,
12
26
  };
13
- export const setDbConfig = (config) => {
14
- _db = undefined;
15
- getDb(config);
27
+ let _knexDb = undefined;
28
+ let _knexDbConfig = undefined;
29
+ export const getKnexDb = (config = {}) => {
30
+ if (_knexDb === undefined) {
31
+ _knexDbConfig = Object.assign(Object.assign(Object.assign({}, defaults), getEnvConfig()), config);
32
+ if (_knexDbConfig.dbType === SupportedDbType.sqlite) {
33
+ _knexDb = knex({
34
+ client: "better-sqlite3",
35
+ connection: {
36
+ filename: _knexDbConfig.filePath,
37
+ },
38
+ useNullAsDefault: true,
39
+ debug: _knexDbConfig.verbose,
40
+ });
41
+ }
42
+ else if (_knexDbConfig.dbType === SupportedDbType.postgres) {
43
+ _knexDb = knex({
44
+ client: "pg",
45
+ connection: _knexDbConfig.pgConnectionString,
46
+ useNullAsDefault: true,
47
+ });
48
+ }
49
+ else {
50
+ throw new Error(`Unsupported DB type: ${_knexDbConfig.dbType}`);
51
+ }
52
+ }
53
+ return _knexDb;
54
+ };
55
+ export const isPostgres = () => {
56
+ return isDbType(SupportedDbType.postgres);
57
+ };
58
+ export const isSqlite = () => {
59
+ return isDbType(SupportedDbType.sqlite);
60
+ };
61
+ const isDbType = (type) => {
62
+ if (_knexDbConfig === undefined) {
63
+ throw new Error("DB not initialized");
64
+ }
65
+ return _knexDbConfig.dbType === type;
66
+ };
67
+ const getMigrationConfig = () => {
68
+ return { directory: join(__dirname, "migrations") };
16
69
  };
17
- export const getDb = (config = {}) => {
18
- const options = Object.assign(Object.assign({}, defaults), config);
19
- if (typeof _db === "undefined") {
20
- if (!existsSync(options.filePath)) {
21
- copyFileSync(options.initFilePath, options.filePath);
70
+ export const initDb = (config = {}) => __awaiter(void 0, void 0, void 0, function* () {
71
+ const knex = getKnexDb(config);
72
+ yield knex.migrate.latest(getMigrationConfig());
73
+ return knex;
74
+ });
75
+ export const clearDb = (config = {}) => __awaiter(void 0, void 0, void 0, function* () {
76
+ const knex = getKnexDb(config);
77
+ yield knex.migrate.rollback(getMigrationConfig(), true);
78
+ yield knex.migrate.latest(getMigrationConfig());
79
+ return knex;
80
+ });
81
+ export const disconnectKnex = () => __awaiter(void 0, void 0, void 0, function* () {
82
+ if (_knexDb) {
83
+ yield _knexDb.destroy();
84
+ _knexDb = undefined;
85
+ }
86
+ });
87
+ const getEnvConfig = () => {
88
+ configDotenv({ path: ".env.local" });
89
+ const envConfig = {};
90
+ if (process.env.TEXTTOMAP_DB_TYPE &&
91
+ Object.values(SupportedDbType).includes(process.env.TEXTTOMAP_DB_TYPE)) {
92
+ envConfig.dbType = process.env.TEXTTOMAP_DB_TYPE;
93
+ if (envConfig.dbType === SupportedDbType.postgres) {
94
+ if (!process.env.TEXTTOMAP_PG_CONNECTION_STRING) {
95
+ throw new Error("Environmental variable 'TEXTTOMAP_PG_CONNECTION_STRING' must be set for PostgreSQL.");
96
+ }
97
+ envConfig.pgConnectionString = process.env.TEXTTOMAP_PG_CONNECTION_STRING;
98
+ }
99
+ else if (envConfig.dbType === SupportedDbType.sqlite) {
100
+ if (process.env.TEXTTOMAP_SQLITE_PATH) {
101
+ envConfig.filePath = process.env.TEXTTOMAP_SQLITE_PATH;
102
+ }
22
103
  }
23
- const dbSettings = options.verbose ? { verbose: console.log } : {};
24
- _db = new Database(options.filePath, dbSettings);
25
- _db.pragma("journal_mode = WAL");
26
104
  }
27
- return _db;
105
+ return envConfig;
28
106
  };
29
107
  export const nonEmptyOrNull = (value) => {
30
108
  return value ? value : null;
@@ -33,50 +111,46 @@ export const nonEmptyOrNull = (value) => {
33
111
  * Efficiently insert multiple rows. If preventDuplicatesByFirstColumn is true, the first
34
112
  * column should be unique (PK or UNIQUE).
35
113
  */
36
- export const insertMultipleRows = (rows, table, columnNames, preventDuplicatesByFirstColumn = true) => {
37
- const db = getDb();
114
+ export const insertMultipleRows = (rows, table, columnNames, preventDuplicatesByFirstColumn = true) => __awaiter(void 0, void 0, void 0, function* () {
38
115
  if (rows.length === 0) {
39
116
  return 0;
40
117
  }
41
- if (preventDuplicatesByFirstColumn) {
42
- rows = clearDuplicates(rows, table, columnNames);
43
- if (rows.length === 0) {
44
- return 0;
45
- }
46
- }
47
- const insertPlaceholders = generateRepetitiveString(`(${generatePlaceholders(columnNames.length)})`, ",", rows.length);
48
- const insertStatement = db.prepare(`INSERT INTO ${table} (${columnNames.join(",")}) VALUES ${insertPlaceholders}`);
49
- return insertStatement.run(rows.flat()).changes;
50
- };
118
+ // if (preventDuplicatesByFirstColumn) {
119
+ // rows = await clearDuplicates(rows, table, columnNames);
120
+ // if (rows.length === 0) {
121
+ // return 0;
122
+ // }
123
+ // }
124
+ const insertPlaceholders = generate2DPlaceholders(columnNames.length, rows.length);
125
+ const onConfict = preventDuplicatesByFirstColumn ? `ON CONFLICT (${columnNames[0]}) DO NOTHING` : '';
126
+ yield getKnexDb().raw(`INSERT INTO ${table} (${columnNames.join(",")}) VALUES ${insertPlaceholders} ${onConfict}`, rows.flat());
127
+ return rows.length;
128
+ });
51
129
  /**
52
130
  * Insert a single row and return the autoincremented ID.
53
131
  */
54
- export const insertAutoincrementRow = (row, table, columnNames) => {
55
- const db = getDb();
56
- const insertStatement = db.prepare(`INSERT INTO ${table} (${columnNames.join(",")}) VALUES (${generatePlaceholders(columnNames.length)})`);
57
- const result = insertStatement.run(row);
58
- return result.changes === 1 ? Number(result.lastInsertRowid) : null;
59
- };
60
- export const deleteMultipleRows = (keys, table, keyColumnName) => {
61
- const db = getDb();
132
+ export const insertAutoincrementRow = (row, table, columnNames) => __awaiter(void 0, void 0, void 0, function* () {
133
+ const data = columnNames.reduce((obj, columnName, index) => {
134
+ obj[columnName] = row[index];
135
+ return obj;
136
+ }, {});
137
+ const result = yield getKnexDb().insert(data).into(table);
138
+ return result ? Number(result) : null;
139
+ });
140
+ export const deleteMultipleRowsKnex = (keys, table, keyColumnName) => __awaiter(void 0, void 0, void 0, function* () {
62
141
  if (keys.length === 0) {
63
142
  return;
64
143
  }
65
- db.prepare(`DELETE FROM ${table} WHERE ${keyColumnName} IN (${generatePlaceholders(keys.length)})`).run(keys);
66
- };
67
- export const clearDuplicates = (rows, table, columnNames) => {
68
- const db = getDb();
69
- const selectPlaceholders = generatePlaceholders(rows.length);
70
- const selectStatement = db.prepare(`SELECT ${columnNames[0]} FROM ${table} WHERE ${columnNames[0]} IN (${selectPlaceholders})`);
71
- const existing = selectStatement
72
- .pluck()
73
- .all(rows.map((row) => row[0]))
74
- .map((key) => key.toString());
75
- return rows.filter((row) => !existing.includes(row[0]));
76
- };
77
- export const disconnect = () => {
78
- getDb().close();
79
- };
144
+ yield getKnexDb().from(table).whereIn(keyColumnName, keys).del();
145
+ });
146
+ export const clearDuplicates = (rows, table, columnNames) => __awaiter(void 0, void 0, void 0, function* () {
147
+ const existing = yield getKnexDb()
148
+ .select(columnNames[0])
149
+ .from(table)
150
+ .whereIn(columnNames[0], rows.map((row) => row[0]));
151
+ const keys = existing.map((row) => row[columnNames[0]].toString());
152
+ return rows.filter((row) => !keys.includes(row[0]));
153
+ });
80
154
  const generateRepetitiveString = (value, glue, n) => {
81
155
  return new Array(n).fill(value).join(glue);
82
156
  };
@@ -1,9 +1,9 @@
1
+ import { DbMunicipalityResult, SmdError } from "../street-markdown/types";
1
2
  import { Founder, MunicipalityType } from "./types";
2
- import { DbMunicipalityResult } from "../street-markdown/types";
3
- export declare const insertFounders: (founders: Founder[]) => number;
4
- export declare const findFounder: (name: string) => {
3
+ export declare const insertFounders: (founders: Founder[]) => Promise<number>;
4
+ export declare const findFounder: (nameWithHashtag: string) => Promise<{
5
5
  founder: Founder;
6
- errors: string[];
7
- };
8
- export declare const getFounderCityCode: (founder: Founder) => number;
9
- export declare const findMunicipalityByNameAndType: (name: string, type: MunicipalityType) => DbMunicipalityResult;
6
+ errors: SmdError[];
7
+ }>;
8
+ export declare const getFounderCityCode: (founder: Founder) => Promise<number>;
9
+ export declare const findMunicipalityByNameAndType: (name: string, type: MunicipalityType) => Promise<DbMunicipalityResult>;