@tmlmobilidade/utils 20250827.1349.36 → 20250827.1513.21

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/dist/index.d.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  export * from './src/batching/index.js';
2
2
  export * from './src/convert-object.js';
3
3
  export * from './src/css/index.js';
4
- export * from './src/databases/index.js';
5
4
  export * from './src/dates/index.js';
6
5
  export * from './src/files/files.js';
7
6
  export * from './src/generic/index.js';
package/dist/index.js CHANGED
@@ -1,7 +1,6 @@
1
1
  export * from './src/batching/index.js';
2
2
  export * from './src/convert-object.js';
3
3
  export * from './src/css/index.js';
4
- export * from './src/databases/index.js';
5
4
  export * from './src/dates/index.js';
6
5
  export * from './src/files/files.js';
7
6
  export * from './src/generic/index.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tmlmobilidade/utils",
3
- "version": "20250827.1349.36",
3
+ "version": "20250827.1513.21",
4
4
  "author": "João de Vasconcelos & Jusi Monteiro",
5
5
  "license": "AGPL-3.0-or-later",
6
6
  "homepage": "https://github.com/tmlmobilidade/services#readme",
@@ -41,7 +41,6 @@
41
41
  "dependencies": {
42
42
  "@tmlmobilidade/lib": "*",
43
43
  "@turf/turf": "7.2.0",
44
- "better-sqlite3": "12.2.0",
45
44
  "extract-zip": "2.0.1",
46
45
  "geojson": "0.5.0",
47
46
  "jszip": "3.10.1",
@@ -54,7 +53,6 @@
54
53
  "@carrismetropolitana/eslint": "20250622.1204.50",
55
54
  "@tmlmobilidade/tsconfig": "*",
56
55
  "@tmlmobilidade/types": "*",
57
- "@types/better-sqlite3": "7.6.13",
58
56
  "@types/luxon": "3.7.1",
59
57
  "@types/node": "24.3.0",
60
58
  "@types/papaparse": "5.3.16",
@@ -1,2 +0,0 @@
1
- export * from './sqlite-map.js';
2
- export * from './sqlite-writer.js';
@@ -1,2 +0,0 @@
1
- export * from './sqlite-map.js';
2
- export * from './sqlite-writer.js';
@@ -1,57 +0,0 @@
1
- /**
2
- * A map-like structure backed by SQLite for persistent key-value storage.
3
- * Use it to store and retrieve data across sessions without memory constraints.
4
- * The API is similar to the native javascript Map object.
5
- */
6
- export declare class SQLiteMap<K extends string, V> {
7
- /**
8
- * Returns the number of entries in the map.
9
- */
10
- get size(): number;
11
- private databaseInstance;
12
- constructor();
13
- /**
14
- * Clears all entries from the map.
15
- */
16
- clear(): void;
17
- /**
18
- * Deletes a key-value pair from the map.
19
- * @param key The key of the entry to delete.
20
- * @returns True if the entry was deleted, false if it didn't exist.
21
- */
22
- delete(key: K): boolean;
23
- /**
24
- * Returns an iterator over the entries in the map.
25
- */
26
- entries(): IterableIterator<[K, V]>;
27
- /**
28
- * Retrieves the value associated with the given key.
29
- * @param key The key of the entry to retrieve.
30
- * @returns The value associated with the key, or undefined if it doesn't exist.
31
- */
32
- get(key: K): undefined | V;
33
- /**
34
- * Checks if the map contains a value for the given key.
35
- * @param key The key to check.
36
- * @returns True if the key exists, false otherwise.
37
- */
38
- has(key: K): boolean;
39
- /**
40
- * Returns an iterator over the keys in the map.
41
- */
42
- keys(): IterableIterator<K>;
43
- /**
44
- * Sets the value for the given key.
45
- * @param key The key of the entry to set.
46
- * @param value The value to associate with the key.
47
- */
48
- set(key: K, value: V): void;
49
- /**
50
- * Returns an iterator over the entries in the map.
51
- */
52
- [Symbol.iterator](): IterableIterator<[K, V]>;
53
- /**
54
- * Returns an iterator over the values in the map.
55
- */
56
- values(): IterableIterator<V>;
57
- }
@@ -1,121 +0,0 @@
1
- /* * */
2
- import { generateRandomString } from '../random/generate-random-string.js';
3
- import BSQLite3 from 'better-sqlite3';
4
- /* * */
5
- /**
6
- * A map-like structure backed by SQLite for persistent key-value storage.
7
- * Use it to store and retrieve data across sessions without memory constraints.
8
- * The API is similar to the native javascript Map object.
9
- */
10
- export class SQLiteMap {
11
- //
12
- /**
13
- * Returns the number of entries in the map.
14
- */
15
- get size() {
16
- const row = this.databaseInstance
17
- .prepare(`SELECT COUNT(*) as count FROM map`)
18
- .get();
19
- return row.count;
20
- }
21
- databaseInstance;
22
- constructor() {
23
- //
24
- //
25
- // Set up a new database instance
26
- const databaseFileName = generateRandomString();
27
- this.databaseInstance = new BSQLite3(`/tmp/${databaseFileName}.db`);
28
- //
29
- // Create a new table if it doesn't exist
30
- this.databaseInstance.pragma('journal_mode = WAL');
31
- this.databaseInstance.pragma('synchronous = NORMAL');
32
- this.databaseInstance
33
- .prepare(`CREATE TABLE IF NOT EXISTS map (key TEXT PRIMARY KEY, value TEXT NOT NULL)`)
34
- .run();
35
- //
36
- }
37
- /**
38
- * Clears all entries from the map.
39
- */
40
- clear() {
41
- this.databaseInstance
42
- .prepare(`DELETE FROM map`)
43
- .run();
44
- }
45
- /**
46
- * Deletes a key-value pair from the map.
47
- * @param key The key of the entry to delete.
48
- * @returns True if the entry was deleted, false if it didn't exist.
49
- */
50
- delete(key) {
51
- const result = this.databaseInstance
52
- .prepare(`DELETE FROM map WHERE key = ?`)
53
- .run(key);
54
- return result.changes > 0;
55
- }
56
- /**
57
- * Returns an iterator over the entries in the map.
58
- */
59
- *entries() {
60
- const statement = this.databaseInstance.prepare(`SELECT key, value FROM map`);
61
- for (const row of statement.iterate()) {
62
- yield [JSON.parse(row.key), JSON.parse(row.value)];
63
- }
64
- }
65
- /**
66
- * Retrieves the value associated with the given key.
67
- * @param key The key of the entry to retrieve.
68
- * @returns The value associated with the key, or undefined if it doesn't exist.
69
- */
70
- get(key) {
71
- const row = this.databaseInstance
72
- .prepare(`SELECT value FROM map WHERE key = ?`)
73
- .get(key);
74
- return row ? JSON.parse(row.value) : undefined;
75
- }
76
- /**
77
- * Checks if the map contains a value for the given key.
78
- * @param key The key to check.
79
- * @returns True if the key exists, false otherwise.
80
- */
81
- has(key) {
82
- const row = this.databaseInstance
83
- .prepare(`SELECT 1 FROM map WHERE key = ?`)
84
- .get(key);
85
- return !!row;
86
- }
87
- /**
88
- * Returns an iterator over the keys in the map.
89
- */
90
- *keys() {
91
- const statement = this.databaseInstance.prepare(`SELECT key FROM map`);
92
- for (const row of statement.iterate()) {
93
- yield JSON.parse(row.key);
94
- }
95
- }
96
- /**
97
- * Sets the value for the given key.
98
- * @param key The key of the entry to set.
99
- * @param value The value to associate with the key.
100
- */
101
- set(key, value) {
102
- this.databaseInstance
103
- .prepare(`INSERT OR REPLACE INTO map (key, value) VALUES (?, ?)`)
104
- .run(key, JSON.stringify(value));
105
- }
106
- /**
107
- * Returns an iterator over the entries in the map.
108
- */
109
- [Symbol.iterator]() {
110
- return this.entries();
111
- }
112
- /**
113
- * Returns an iterator over the values in the map.
114
- */
115
- *values() {
116
- const statement = this.databaseInstance.prepare(`SELECT value FROM map`);
117
- for (const row of statement.iterate()) {
118
- yield JSON.parse(row.value);
119
- }
120
- }
121
- }
@@ -1,63 +0,0 @@
1
- interface SQLiteWriterColumn<T> {
2
- indexed?: boolean;
3
- name: Extract<keyof T, string>;
4
- not_null?: boolean;
5
- primary_key?: boolean;
6
- type: 'BLOB' | 'INTEGER' | 'REAL' | 'TEXT';
7
- }
8
- export interface SQLiteWriterParams<T> {
9
- /**
10
- * The maximum number of items to hold in memory
11
- * before flushing to the database.
12
- * @default 3000
13
- */
14
- batch_size?: number;
15
- /**
16
- * Columns in the table.
17
- * Order matters for INSERT.
18
- * Must be keys of T or custom names.
19
- */
20
- columns: SQLiteWriterColumn<T>[];
21
- }
22
- export declare class SQLiteWriter<T> {
23
- /**
24
- * Get the number of rows in the table.
25
- * @returns The number of rows.
26
- */
27
- get size(): number;
28
- private batch;
29
- private batchSize;
30
- private columns;
31
- private databaseInstance;
32
- private insertStatement;
33
- private instanceName;
34
- constructor(params: SQLiteWriterParams<T>);
35
- all(whereClause?: string, params?: (boolean | number | string)[]): T[];
36
- /**
37
- * Clears all entries from the map.
38
- */
39
- clear(): void;
40
- /**
41
- * Flush current buffer into DB synchronously.
42
- */
43
- flush(): void;
44
- /**
45
- * Get a single row by column value.
46
- * @param col The column to filter by.
47
- * @param value The value to match.
48
- * @returns The matching row, or undefined if not found.
49
- */
50
- get<K extends keyof T>(col: K, value: T[K]): T | undefined;
51
- /**
52
- * Check if a row exists by column value.
53
- * @param col The column to filter by.
54
- * @param value The value to match.
55
- * @returns True if the row exists, false otherwise.
56
- */
57
- has<K extends keyof T>(col: K, value: T[K]): boolean;
58
- /**
59
- * Add one item to buffer, flush automatically when batchSize reached.
60
- */
61
- write(item: T): void;
62
- }
63
- export {};
@@ -1,127 +0,0 @@
1
- /* * */
2
- import { generateRandomString } from '../random/generate-random-string.js';
3
- import BSQLite3 from 'better-sqlite3';
4
- /* * */
5
- export class SQLiteWriter {
6
- //
7
- /**
8
- * Get the number of rows in the table.
9
- * @returns The number of rows.
10
- */
11
- get size() {
12
- const sql = `SELECT COUNT(*) as count FROM ${this.instanceName}`;
13
- const row = this.databaseInstance.prepare(sql).get();
14
- return row.count;
15
- }
16
- batch = [];
17
- batchSize = 3000;
18
- columns;
19
- databaseInstance;
20
- insertStatement;
21
- instanceName;
22
- constructor(params) {
23
- //
24
- //
25
- // Set up options
26
- this.batchSize = params.batch_size ?? 3000;
27
- this.columns = params.columns;
28
- this.instanceName = generateRandomString({ type: 'alphabetic' });
29
- //
30
- // Create a new SQLite instance
31
- this.databaseInstance = new BSQLite3(`/tmp/${this.instanceName}.db`);
32
- //
33
- // Setup table columns from params
34
- const preparedColumns = [];
35
- const preparedIndexes = [];
36
- for (const columnSpec of this.columns) {
37
- // Extract column definition
38
- const parts = [`"${columnSpec.name}"`, columnSpec.type];
39
- // Set column preferences
40
- if (columnSpec.not_null)
41
- parts.push('NOT NULL');
42
- if (columnSpec.primary_key)
43
- parts.push('PRIMARY KEY');
44
- // Save the column definition
45
- preparedColumns.push(parts.join(' '));
46
- // Save the index definition
47
- if (columnSpec.indexed)
48
- preparedIndexes.push(`CREATE INDEX IF NOT EXISTS idx_${this.instanceName}_${columnSpec.name} ON ${this.instanceName}("${columnSpec.name}")`);
49
- }
50
- //
51
- // Create the table with the prepared columns and indexes
52
- this.databaseInstance.pragma('journal_mode = WAL');
53
- this.databaseInstance.pragma('synchronous = OFF');
54
- this.databaseInstance.pragma('temp_store = MEMORY');
55
- this.databaseInstance
56
- .prepare(`CREATE TABLE IF NOT EXISTS ${this.instanceName} (${preparedColumns.join(',\n')})`)
57
- .run();
58
- preparedIndexes.forEach(i => this.databaseInstance.exec(i));
59
- //
60
- // Prepare insert statement
61
- const placeholders = this.columns.map(() => '?').join(', ');
62
- const insertSQL = `INSERT INTO ${this.instanceName} (${this.columns.map(c => `"${c.name}"`).join(', ')}) VALUES (${placeholders})`;
63
- this.insertStatement = this.databaseInstance.prepare(insertSQL);
64
- //
65
- }
66
- all(whereClause = '', params = []) {
67
- const sql = `SELECT * FROM ${this.instanceName} ${whereClause}`;
68
- return this.databaseInstance.prepare(sql).all(...params);
69
- }
70
- /**
71
- * Clears all entries from the map.
72
- */
73
- clear() {
74
- this.databaseInstance
75
- .prepare(`DELETE FROM ${this.instanceName}`)
76
- .run();
77
- }
78
- /**
79
- * Flush current buffer into DB synchronously.
80
- */
81
- flush() {
82
- // Skip if batch is empty
83
- if (this.batch.length === 0)
84
- return;
85
- // Prepare the operation
86
- const insertManyOperation = this.databaseInstance.transaction((rows) => {
87
- rows.forEach((row) => {
88
- // Populate the columns with the row values
89
- // to ensure the order of placeholders is preserved
90
- const rowValues = this.columns.map(col => row[col.name]);
91
- this.insertStatement.run(rowValues);
92
- });
93
- });
94
- // Run the operation
95
- insertManyOperation(this.batch);
96
- // Empty batch
97
- this.batch = [];
98
- }
99
- /**
100
- * Get a single row by column value.
101
- * @param col The column to filter by.
102
- * @param value The value to match.
103
- * @returns The matching row, or undefined if not found.
104
- */
105
- get(col, value) {
106
- const sql = `SELECT * FROM ${this.instanceName} WHERE ${String(col)} = ? LIMIT 1`;
107
- return this.databaseInstance.prepare(sql).get(value);
108
- }
109
- /**
110
- * Check if a row exists by column value.
111
- * @param col The column to filter by.
112
- * @param value The value to match.
113
- * @returns True if the row exists, false otherwise.
114
- */
115
- has(col, value) {
116
- const sql = `SELECT 1 FROM ${this.instanceName} WHERE ${String(col)} = ? LIMIT 1`;
117
- return !!this.databaseInstance.prepare(sql).get(value);
118
- }
119
- /**
120
- * Add one item to buffer, flush automatically when batchSize reached.
121
- */
122
- write(item) {
123
- this.batch.push(item);
124
- if (this.batch.length >= this.batchSize)
125
- this.flush();
126
- }
127
- }