csv-sql-engine 0.0.0 → 0.0.1
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/LICENSE-CC0 +121 -0
- package/LICENSE-MIT +21 -0
- package/README.md +49 -0
- package/dist/augments/trim-lines.d.ts +6 -0
- package/dist/augments/trim-lines.js +12 -0
- package/dist/csv/csv-file.d.ts +70 -0
- package/dist/csv/csv-file.js +98 -0
- package/dist/csv/csv-text.d.ts +52 -0
- package/dist/csv/csv-text.js +79 -0
- package/dist/engine/define-ast-handler.d.ts +27 -0
- package/dist/engine/define-ast-handler.js +8 -0
- package/dist/engine/engine.d.ts +16 -0
- package/dist/engine/engine.js +66 -0
- package/dist/engine/handlers/row-delete.handler.d.ts +6 -0
- package/dist/engine/handlers/row-delete.handler.js +51 -0
- package/dist/engine/handlers/row-insert.handler.d.ts +6 -0
- package/dist/engine/handlers/row-insert.handler.js +54 -0
- package/dist/engine/handlers/row-select.handler.d.ts +6 -0
- package/dist/engine/handlers/row-select.handler.js +46 -0
- package/dist/engine/handlers/row-update.handler.d.ts +6 -0
- package/dist/engine/handlers/row-update.handler.js +61 -0
- package/dist/engine/handlers/table-alter.handler.d.ts +6 -0
- package/dist/engine/handlers/table-alter.handler.js +85 -0
- package/dist/engine/handlers/table-create.handler.d.ts +6 -0
- package/dist/engine/handlers/table-create.handler.js +38 -0
- package/dist/engine/handlers/table-drop.handler.d.ts +6 -0
- package/dist/engine/handlers/table-drop.handler.js +36 -0
- package/dist/engine/params.d.ts +51 -0
- package/dist/engine/params.js +1 -0
- package/dist/engine/where-matcher.d.ts +9 -0
- package/dist/engine/where-matcher.js +52 -0
- package/dist/errors/csv-sql-engine.error.d.ts +9 -0
- package/dist/errors/csv-sql-engine.error.js +9 -0
- package/dist/errors/csv.error.d.ts +57 -0
- package/dist/errors/csv.error.js +68 -0
- package/dist/errors/sql.error.d.ts +45 -0
- package/dist/errors/sql.error.js +64 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +20 -0
- package/dist/sql/ast.d.ts +472 -0
- package/dist/sql/ast.js +266 -0
- package/dist/sql/parse-sql.d.ts +9 -0
- package/dist/sql/parse-sql.js +38 -0
- package/dist/sql/sql.d.ts +24 -0
- package/dist/sql/sql.js +26 -0
- package/package.json +99 -11
package/LICENSE-CC0
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
CC0 1.0 Universal
|
|
2
|
+
|
|
3
|
+
Creative Commons Legal Code
|
|
4
|
+
|
|
5
|
+
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
|
|
6
|
+
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
|
|
7
|
+
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
|
|
8
|
+
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
|
|
9
|
+
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
|
|
10
|
+
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
|
|
11
|
+
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
|
|
12
|
+
HEREUNDER.
|
|
13
|
+
|
|
14
|
+
Statement of Purpose
|
|
15
|
+
|
|
16
|
+
The laws of most jurisdictions throughout the world automatically confer
|
|
17
|
+
exclusive Copyright and Related Rights (defined below) upon the creator
|
|
18
|
+
and subsequent owner(s) (each and all, an "owner") of an original work of
|
|
19
|
+
authorship and/or a database (each, a "Work").
|
|
20
|
+
|
|
21
|
+
Certain owners wish to permanently relinquish those rights to a Work for
|
|
22
|
+
the purpose of contributing to a commons of creative, cultural and
|
|
23
|
+
scientific works ("Commons") that the public can reliably and without fear
|
|
24
|
+
of later claims of infringement build upon, modify, incorporate in other
|
|
25
|
+
works, reuse and redistribute as freely as possible in any form whatsoever
|
|
26
|
+
and for any purposes, including without limitation commercial purposes.
|
|
27
|
+
These owners may contribute to the Commons to promote the ideal of a free
|
|
28
|
+
culture and the further production of creative, cultural and scientific
|
|
29
|
+
works, or to gain reputation or greater distribution for their Work in
|
|
30
|
+
part through the use and efforts of others.
|
|
31
|
+
|
|
32
|
+
For these and/or other purposes and motivations, and without any
|
|
33
|
+
expectation of additional consideration or compensation, the person
|
|
34
|
+
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
|
|
35
|
+
is an owner of Copyright and Related Rights in the Work, voluntarily
|
|
36
|
+
elects to apply CC0 to the Work and publicly distribute the Work under its
|
|
37
|
+
terms, with knowledge of his or her Copyright and Related Rights in the
|
|
38
|
+
Work and the meaning and intended legal effect of CC0 on those rights.
|
|
39
|
+
|
|
40
|
+
1. Copyright and Related Rights. A Work made available under CC0 may be
|
|
41
|
+
protected by copyright and related or neighboring rights ("Copyright and
|
|
42
|
+
Related Rights"). Copyright and Related Rights include, but are not
|
|
43
|
+
limited to, the following:
|
|
44
|
+
|
|
45
|
+
i. the right to reproduce, adapt, distribute, perform, display,
|
|
46
|
+
communicate, and translate a Work;
|
|
47
|
+
ii. moral rights retained by the original author(s) and/or performer(s);
|
|
48
|
+
iii. publicity and privacy rights pertaining to a person's image or
|
|
49
|
+
likeness depicted in a Work;
|
|
50
|
+
iv. rights protecting against unfair competition in regards to a Work,
|
|
51
|
+
subject to the limitations in paragraph 4(a), below;
|
|
52
|
+
v. rights protecting the extraction, dissemination, use and reuse of data
|
|
53
|
+
in a Work;
|
|
54
|
+
vi. database rights (such as those arising under Directive 96/9/EC of the
|
|
55
|
+
European Parliament and of the Council of 11 March 1996 on the legal
|
|
56
|
+
protection of databases, and under any national implementation
|
|
57
|
+
thereof, including any amended or successor version of such
|
|
58
|
+
directive); and
|
|
59
|
+
vii. other similar, equivalent or corresponding rights throughout the
|
|
60
|
+
world based on applicable law or treaty, and any national
|
|
61
|
+
implementations thereof.
|
|
62
|
+
|
|
63
|
+
2. Waiver. To the greatest extent permitted by, but not in contravention
|
|
64
|
+
of, applicable law, Affirmer hereby overtly, fully, permanently,
|
|
65
|
+
irrevocably and unconditionally waives, abandons, and surrenders all of
|
|
66
|
+
Affirmer's Copyright and Related Rights and associated claims and causes
|
|
67
|
+
of action, whether now known or unknown (including existing as well as
|
|
68
|
+
future claims and causes of action), in the Work (i) in all territories
|
|
69
|
+
worldwide, (ii) for the maximum duration provided by applicable law or
|
|
70
|
+
treaty (including future time extensions), (iii) in any current or future
|
|
71
|
+
medium and for any number of copies, and (iv) for any purpose whatsoever,
|
|
72
|
+
including without limitation commercial, advertising or promotional
|
|
73
|
+
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
|
|
74
|
+
member of the public at large and to the detriment of Affirmer's heirs and
|
|
75
|
+
successors, fully intending that such Waiver shall not be subject to
|
|
76
|
+
revocation, rescission, cancellation, termination, or any other legal or
|
|
77
|
+
equitable action to disrupt the quiet enjoyment of the Work by the public
|
|
78
|
+
as contemplated by Affirmer's express Statement of Purpose.
|
|
79
|
+
|
|
80
|
+
3. Public License Fallback. Should any part of the Waiver for any reason
|
|
81
|
+
be judged legally invalid or ineffective under applicable law, then the
|
|
82
|
+
Waiver shall be preserved to the maximum extent permitted taking into
|
|
83
|
+
account Affirmer's express Statement of Purpose. In addition, to the
|
|
84
|
+
extent the Waiver is so judged Affirmer hereby grants to each affected
|
|
85
|
+
person a royalty-free, non transferable, non sublicensable, non exclusive,
|
|
86
|
+
irrevocable and unconditional license to exercise Affirmer's Copyright and
|
|
87
|
+
Related Rights in the Work (i) in all territories worldwide, (ii) for the
|
|
88
|
+
maximum duration provided by applicable law or treaty (including future
|
|
89
|
+
time extensions), (iii) in any current or future medium and for any number
|
|
90
|
+
of copies, and (iv) for any purpose whatsoever, including without
|
|
91
|
+
limitation commercial, advertising or promotional purposes (the
|
|
92
|
+
"License"). The License shall be deemed effective as of the date CC0 was
|
|
93
|
+
applied by Affirmer to the Work. Should any part of the License for any
|
|
94
|
+
reason be judged legally invalid or ineffective under applicable law, such
|
|
95
|
+
partial invalidity or ineffectiveness shall not invalidate the remainder
|
|
96
|
+
of the License, and in such case Affirmer hereby affirms that he or she
|
|
97
|
+
will not (i) exercise any of his or her remaining Copyright and Related
|
|
98
|
+
Rights in the Work or (ii) assert any associated claims and causes of
|
|
99
|
+
action with respect to the Work, in either case contrary to Affirmer's
|
|
100
|
+
express Statement of Purpose.
|
|
101
|
+
|
|
102
|
+
4. Limitations and Disclaimers.
|
|
103
|
+
|
|
104
|
+
a. No trademark or patent rights held by Affirmer are waived, abandoned,
|
|
105
|
+
surrendered, licensed or otherwise affected by this document.
|
|
106
|
+
b. Affirmer offers the Work as-is and makes no representations or
|
|
107
|
+
warranties of any kind concerning the Work, express, implied,
|
|
108
|
+
statutory or otherwise, including without limitation warranties of
|
|
109
|
+
title, merchantability, fitness for a particular purpose, non
|
|
110
|
+
infringement, or the absence of latent or other defects, accuracy, or
|
|
111
|
+
the present or absence of errors, whether or not discoverable, all to
|
|
112
|
+
the greatest extent permissible under applicable law.
|
|
113
|
+
c. Affirmer disclaims responsibility for clearing rights of other persons
|
|
114
|
+
that may apply to the Work or any use thereof, including without
|
|
115
|
+
limitation any person's Copyright and Related Rights in the Work.
|
|
116
|
+
Further, Affirmer disclaims responsibility for obtaining any necessary
|
|
117
|
+
consents, permissions or other rights required for any use of the
|
|
118
|
+
Work.
|
|
119
|
+
d. Affirmer understands and acknowledges that Creative Commons is not a
|
|
120
|
+
party to this document and has no duty or obligation with respect to
|
|
121
|
+
this CC0 or use of the Work.
|
package/LICENSE-MIT
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 electrovir
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# csv-sql-engine
|
|
2
|
+
|
|
3
|
+
An API for executing SQL statements on a collection of CSV files. Handles SQLite syntax.
|
|
4
|
+
|
|
5
|
+
Supports only basic version of the following operations:
|
|
6
|
+
|
|
7
|
+
- creating tables
|
|
8
|
+
- dropping tables
|
|
9
|
+
- adding columns
|
|
10
|
+
- dropping columns
|
|
11
|
+
- renaming columns
|
|
12
|
+
- inserting rows
|
|
13
|
+
- deleting rows
|
|
14
|
+
- updating rows
|
|
15
|
+
- selecting data
|
|
16
|
+
|
|
17
|
+
Caveats:
|
|
18
|
+
|
|
19
|
+
- Default column values are only applied when adding a _new column_ to an existing table. (Not when adding new rows.)
|
|
20
|
+
- Database constraints (column data types, relational ids, not null, etc.) are not enforced on read or write.
|
|
21
|
+
- Auto-incrementing ids do not auto increment.
|
|
22
|
+
- Every value is written and read as a string.
|
|
23
|
+
- Probably not performant on large CSV files.
|
|
24
|
+
- Joins are not yet supported.
|
|
25
|
+
|
|
26
|
+
## Install
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
npm i csv-sql-engine
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Examples
|
|
33
|
+
|
|
34
|
+
<!-- example-link: ./src/engine/engine.example.ts -->
|
|
35
|
+
|
|
36
|
+
```TypeScript
|
|
37
|
+
import {executeSql, sql} from 'csv-sql-engine';
|
|
38
|
+
|
|
39
|
+
/** Creates a new file at `./my-csv-files/users.csv`. */
|
|
40
|
+
await executeSql(
|
|
41
|
+
sql`
|
|
42
|
+
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT);
|
|
43
|
+
INSERT INTO users VALUES (1, "example@example.com", "example");
|
|
44
|
+
`,
|
|
45
|
+
{
|
|
46
|
+
csvDirPath: './my-csv-files/',
|
|
47
|
+
},
|
|
48
|
+
);
|
|
49
|
+
```
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { check } from '@augment-vir/assert';
|
|
2
|
+
import { filterMap } from '@augment-vir/common';
|
|
3
|
+
/**
|
|
4
|
+
* Trims every line in the given string.
|
|
5
|
+
*
|
|
6
|
+
* @category Internal
|
|
7
|
+
*/
|
|
8
|
+
export function trimLines(value) {
|
|
9
|
+
return filterMap(value.trim().split('\n'), (line) => line.trim(), check.isTruthy)
|
|
10
|
+
.join('\n')
|
|
11
|
+
.trim();
|
|
12
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { type RequireExactlyOne } from 'type-fest';
|
|
2
|
+
/**
|
|
3
|
+
* The extension used for reading and writing to CSV files.
|
|
4
|
+
*
|
|
5
|
+
* @category Internal
|
|
6
|
+
*/
|
|
7
|
+
export declare const csvExtension = ".csv";
|
|
8
|
+
/**
|
|
9
|
+
* A parsed CSV file's contents.
|
|
10
|
+
*
|
|
11
|
+
* @category Internal
|
|
12
|
+
*/
|
|
13
|
+
export type CsvFile = string[][];
|
|
14
|
+
/**
|
|
15
|
+
* Appends multiple rows to a CSV file.
|
|
16
|
+
*
|
|
17
|
+
* @category CSV
|
|
18
|
+
*/
|
|
19
|
+
export declare function appendCsvRows(valueMatrix: ReadonlyArray<ReadonlyArray<string>>, csvFilePath: string): Promise<void>;
|
|
20
|
+
/**
|
|
21
|
+
* Appends a single row to a CSV file.
|
|
22
|
+
*
|
|
23
|
+
* @category CSV
|
|
24
|
+
*/
|
|
25
|
+
export declare function appendCsvRow(row: ReadonlyArray<string>, csvFilePath: string): Promise<void>;
|
|
26
|
+
/**
|
|
27
|
+
* Creates a sanitized table name and file path for the given SQL table name.
|
|
28
|
+
*
|
|
29
|
+
* @category CSV
|
|
30
|
+
*/
|
|
31
|
+
export declare function nameCsvTableFile({ csvDirPath, tableName, }: {
|
|
32
|
+
csvDirPath: string;
|
|
33
|
+
tableName: string;
|
|
34
|
+
}): {
|
|
35
|
+
tableFilePath: string;
|
|
36
|
+
sanitizedTableName: string;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Reads a CSV from a file path and converts its contents into multiple rows of strings.
|
|
40
|
+
*
|
|
41
|
+
* @category CSV
|
|
42
|
+
*/
|
|
43
|
+
export declare function readCsvFile(filePath: string): Promise<CsvFile>;
|
|
44
|
+
/**
|
|
45
|
+
* Replaces a CSV file's complete contents with the new given contents. If the file does not exist,
|
|
46
|
+
* it and its directories are created.
|
|
47
|
+
*
|
|
48
|
+
* @category CSV
|
|
49
|
+
*/
|
|
50
|
+
export declare function writeCsvFile(filePath: string, contents: ReadonlyArray<ReadonlyArray<string>>): Promise<void>;
|
|
51
|
+
/**
|
|
52
|
+
* Reads headers from a CSV file or already-parsed CSV contents.
|
|
53
|
+
*
|
|
54
|
+
* @category CSV
|
|
55
|
+
*/
|
|
56
|
+
export declare function readCsvHeaders(params: Readonly<RequireExactlyOne<{
|
|
57
|
+
csvFilePath: string;
|
|
58
|
+
csvContents: Readonly<CsvFile>;
|
|
59
|
+
}> & {
|
|
60
|
+
sanitizedTableName: string;
|
|
61
|
+
}>): Promise<string[]>;
|
|
62
|
+
/**
|
|
63
|
+
* Maps CSV headers to their indexes.
|
|
64
|
+
*
|
|
65
|
+
* @category CSV
|
|
66
|
+
*/
|
|
67
|
+
export declare function createCsvHeaderMaps(csvHeaders: ReadonlyArray<string>): {
|
|
68
|
+
byName: Record<string, number>;
|
|
69
|
+
byIndex: Record<number, string>;
|
|
70
|
+
};
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { addSuffix, awaitedForEach, removeSuffix } from '@augment-vir/common';
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { dirname, join } from 'node:path';
|
|
5
|
+
import { CsvFileMissingHeadersError } from '../errors/csv.error.js';
|
|
6
|
+
import { convertRowsToCsv, convertRowToCsv, parseCsvContents } from './csv-text.js';
|
|
7
|
+
/**
|
|
8
|
+
* The extension used for reading and writing to CSV files.
|
|
9
|
+
*
|
|
10
|
+
* @category Internal
|
|
11
|
+
*/
|
|
12
|
+
export const csvExtension = '.csv';
|
|
13
|
+
/**
|
|
14
|
+
* Appends multiple rows to a CSV file.
|
|
15
|
+
*
|
|
16
|
+
* @category CSV
|
|
17
|
+
*/
|
|
18
|
+
export async function appendCsvRows(valueMatrix, csvFilePath) {
|
|
19
|
+
await awaitedForEach(valueMatrix, async (values) => {
|
|
20
|
+
await appendCsvRow(values, csvFilePath);
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Appends a single row to a CSV file.
|
|
25
|
+
*
|
|
26
|
+
* @category CSV
|
|
27
|
+
*/
|
|
28
|
+
export async function appendCsvRow(row, csvFilePath) {
|
|
29
|
+
await appendFile(csvFilePath, convertRowToCsv(row) + '\n');
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Creates a sanitized table name and file path for the given SQL table name.
|
|
33
|
+
*
|
|
34
|
+
* @category CSV
|
|
35
|
+
*/
|
|
36
|
+
export function nameCsvTableFile({ csvDirPath, tableName, }) {
|
|
37
|
+
const sanitizedTableName = removeSuffix({ value: tableName, suffix: csvExtension }).replaceAll(/[./\\]/g, '');
|
|
38
|
+
const newCsvFileName = addSuffix({ value: sanitizedTableName, suffix: csvExtension });
|
|
39
|
+
return {
|
|
40
|
+
tableFilePath: join(csvDirPath, newCsvFileName),
|
|
41
|
+
sanitizedTableName,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Reads a CSV from a file path and converts its contents into multiple rows of strings.
|
|
46
|
+
*
|
|
47
|
+
* @category CSV
|
|
48
|
+
*/
|
|
49
|
+
export async function readCsvFile(filePath) {
|
|
50
|
+
const fileContents = await readFile(filePath, 'utf-8');
|
|
51
|
+
return parseCsvContents(fileContents);
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Replaces a CSV file's complete contents with the new given contents. If the file does not exist,
|
|
55
|
+
* it and its directories are created.
|
|
56
|
+
*
|
|
57
|
+
* @category CSV
|
|
58
|
+
*/
|
|
59
|
+
export async function writeCsvFile(filePath, contents) {
|
|
60
|
+
if (!existsSync(filePath)) {
|
|
61
|
+
await mkdir(dirname(filePath), {
|
|
62
|
+
recursive: true,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
const fileContents = convertRowsToCsv(contents);
|
|
66
|
+
await writeFile(filePath, fileContents);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Reads headers from a CSV file or already-parsed CSV contents.
|
|
70
|
+
*
|
|
71
|
+
* @category CSV
|
|
72
|
+
*/
|
|
73
|
+
export async function readCsvHeaders(params) {
|
|
74
|
+
const headers = params.csvContents
|
|
75
|
+
? params.csvContents[0]
|
|
76
|
+
: (await readCsvFile(params.csvFilePath))[0];
|
|
77
|
+
if (!headers) {
|
|
78
|
+
throw new CsvFileMissingHeadersError(params.sanitizedTableName);
|
|
79
|
+
}
|
|
80
|
+
return headers;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Maps CSV headers to their indexes.
|
|
84
|
+
*
|
|
85
|
+
* @category CSV
|
|
86
|
+
*/
|
|
87
|
+
export function createCsvHeaderMaps(csvHeaders) {
|
|
88
|
+
const byName = {};
|
|
89
|
+
const byIndex = {};
|
|
90
|
+
csvHeaders.forEach((name, index) => {
|
|
91
|
+
byName[name] = index;
|
|
92
|
+
byIndex[index] = name;
|
|
93
|
+
});
|
|
94
|
+
return {
|
|
95
|
+
byIndex,
|
|
96
|
+
byName,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { type RequireExactlyOne } from 'type-fest';
|
|
2
|
+
/**
|
|
3
|
+
* Converts multiple rows of values into a CSV file string.
|
|
4
|
+
*
|
|
5
|
+
* @category CSV
|
|
6
|
+
*/
|
|
7
|
+
export declare function convertRowsToCsv(rows: ReadonlyArray<ReadonlyArray<string>>): string;
|
|
8
|
+
/**
|
|
9
|
+
* Converts a single row of values into a CSV file string.
|
|
10
|
+
*
|
|
11
|
+
* @category CSV
|
|
12
|
+
*/
|
|
13
|
+
export declare function convertRowToCsv(row: ReadonlyArray<string>): string;
|
|
14
|
+
/**
|
|
15
|
+
* Sorts values for CSV insertion or reading.
|
|
16
|
+
*
|
|
17
|
+
* @category CSV
|
|
18
|
+
*/
|
|
19
|
+
export declare function sortValues({ csvFileHeaderOrder, sqlQueryHeaderOrder, from, }: Readonly<{
|
|
20
|
+
csvFileHeaderOrder: ReadonlyArray<string>;
|
|
21
|
+
sqlQueryHeaderOrder: ReadonlyArray<string>;
|
|
22
|
+
from: RequireExactlyOne<{
|
|
23
|
+
/** When a CSV value array is provided, they are sorted to the SQL header order. */
|
|
24
|
+
csvFile: ReadonlyArray<string>;
|
|
25
|
+
/** When a SQL value array is provided, they are sorted to the CSV header order. */
|
|
26
|
+
sqlQuery: ReadonlyArray<string>;
|
|
27
|
+
}>;
|
|
28
|
+
}>): string[];
|
|
29
|
+
/**
|
|
30
|
+
* Reads a CSV file contents string and converts it into multiple rows of strings.
|
|
31
|
+
*
|
|
32
|
+
* @category CSV
|
|
33
|
+
*/
|
|
34
|
+
export declare function parseCsvContents(csvContents: string): string[][];
|
|
35
|
+
/**
|
|
36
|
+
* A tagged template creator that simply returns a string. All leading and trailing whitespace on
|
|
37
|
+
* each line is trimmed, allowing you to format the CSV contents however you like without affecting
|
|
38
|
+
* content.
|
|
39
|
+
*
|
|
40
|
+
* @category CSV
|
|
41
|
+
* @example
|
|
42
|
+
*
|
|
43
|
+
* ```ts
|
|
44
|
+
* import {csv} from 'csv-sql-engine';
|
|
45
|
+
*
|
|
46
|
+
* export myCsv = csv`
|
|
47
|
+
* a,b,c,d
|
|
48
|
+
* 1,2,3,4
|
|
49
|
+
* `;
|
|
50
|
+
* ```
|
|
51
|
+
*/
|
|
52
|
+
export declare function csv(strings: ReadonlyArray<string>, ...values: Array<string>): string;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { wrapString } from '@augment-vir/common';
|
|
2
|
+
import { csvParseRows } from 'd3-dsv';
|
|
3
|
+
import { trimLines } from '../augments/trim-lines.js';
|
|
4
|
+
/**
|
|
5
|
+
* Converts multiple rows of values into a CSV file string.
|
|
6
|
+
*
|
|
7
|
+
* @category CSV
|
|
8
|
+
*/
|
|
9
|
+
export function convertRowsToCsv(rows) {
|
|
10
|
+
return rows.map((row) => convertRowToCsv(row)).join('\n');
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Converts a single row of values into a CSV file string.
|
|
14
|
+
*
|
|
15
|
+
* @category CSV
|
|
16
|
+
*/
|
|
17
|
+
export function convertRowToCsv(row) {
|
|
18
|
+
return row
|
|
19
|
+
.map((value) => {
|
|
20
|
+
if (value) {
|
|
21
|
+
return wrapString({ value, wrapper: '"' });
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
return '""';
|
|
25
|
+
}
|
|
26
|
+
})
|
|
27
|
+
.join(',');
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Sorts values for CSV insertion or reading.
|
|
31
|
+
*
|
|
32
|
+
* @category CSV
|
|
33
|
+
*/
|
|
34
|
+
export function sortValues({ csvFileHeaderOrder, sqlQueryHeaderOrder, from, }) {
|
|
35
|
+
const fromOrder = from.sqlQuery ? sqlQueryHeaderOrder : csvFileHeaderOrder;
|
|
36
|
+
const toOrder = (from.sqlQuery ? csvFileHeaderOrder : sqlQueryHeaderOrder).flatMap((header) => {
|
|
37
|
+
if (header === '*') {
|
|
38
|
+
return csvFileHeaderOrder;
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
return header;
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
const values = from.csvFile || from.sqlQuery;
|
|
45
|
+
return toOrder.map((header) => {
|
|
46
|
+
const sourceIndex = fromOrder.indexOf(header);
|
|
47
|
+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
48
|
+
return values[sourceIndex];
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Reads a CSV file contents string and converts it into multiple rows of strings.
|
|
53
|
+
*
|
|
54
|
+
* @category CSV
|
|
55
|
+
*/
|
|
56
|
+
export function parseCsvContents(csvContents) {
|
|
57
|
+
return csvParseRows(csvContents);
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* A tagged template creator that simply returns a string. All leading and trailing whitespace on
|
|
61
|
+
* each line is trimmed, allowing you to format the CSV contents however you like without affecting
|
|
62
|
+
* content.
|
|
63
|
+
*
|
|
64
|
+
* @category CSV
|
|
65
|
+
* @example
|
|
66
|
+
*
|
|
67
|
+
* ```ts
|
|
68
|
+
* import {csv} from 'csv-sql-engine';
|
|
69
|
+
*
|
|
70
|
+
* export myCsv = csv`
|
|
71
|
+
* a,b,c,d
|
|
72
|
+
* 1,2,3,4
|
|
73
|
+
* `;
|
|
74
|
+
* ```
|
|
75
|
+
*/
|
|
76
|
+
export function csv(strings, ...values) {
|
|
77
|
+
const fullString = strings.reduce((acc, str, i) => acc + str + (values[i] ?? ''), '');
|
|
78
|
+
return trimLines(fullString);
|
|
79
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type MaybePromise } from '@augment-vir/common';
|
|
2
|
+
import { type AstHandlerParams } from './params.js';
|
|
3
|
+
/**
|
|
4
|
+
* Output from a handler that handled a SQL query.
|
|
5
|
+
*
|
|
6
|
+
* @category Internal
|
|
7
|
+
*/
|
|
8
|
+
export type AstHandlerResult = string[][];
|
|
9
|
+
/**
|
|
10
|
+
* An AST / SQL handler.
|
|
11
|
+
*
|
|
12
|
+
* @category Internal
|
|
13
|
+
*/
|
|
14
|
+
export type AstHandler = {
|
|
15
|
+
name: string;
|
|
16
|
+
/**
|
|
17
|
+
* Return `undefined` to mark this AST as not-handled. That means that other handlers should be
|
|
18
|
+
* used instead.
|
|
19
|
+
*/
|
|
20
|
+
handler: (params: Readonly<AstHandlerParams>) => MaybePromise<AstHandlerResult | undefined>;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Used to define new handlers.
|
|
24
|
+
*
|
|
25
|
+
* @category Internal
|
|
26
|
+
*/
|
|
27
|
+
export declare function defineAstHandler(params: AstHandler): AstHandler;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type Sql } from '../sql/sql.js';
|
|
2
|
+
import { type AstHandler, type AstHandlerResult } from './define-ast-handler.js';
|
|
3
|
+
import { type ExecuteSqlParams } from './params.js';
|
|
4
|
+
/**
|
|
5
|
+
* All current SQL handlers.
|
|
6
|
+
*
|
|
7
|
+
* @category Internal
|
|
8
|
+
*/
|
|
9
|
+
export declare const allAstHandlers: ReadonlyArray<Readonly<AstHandler>>;
|
|
10
|
+
/**
|
|
11
|
+
* The main entry point to this package. Run SQLite-compatible SQL commands on a collection of CSV
|
|
12
|
+
* files.
|
|
13
|
+
*
|
|
14
|
+
* @category Main
|
|
15
|
+
*/
|
|
16
|
+
export declare function executeSql(sqlInput: Sql | string, params: Readonly<ExecuteSqlParams>): Promise<AstHandlerResult[]>;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { check } from '@augment-vir/assert';
|
|
2
|
+
import { awaitedBlockingMap, ensureErrorAndPrependMessage } from '@augment-vir/common';
|
|
3
|
+
import { mkdir } from 'node:fs/promises';
|
|
4
|
+
import { SqlUnsupportedOperationError } from '../errors/sql.error.js';
|
|
5
|
+
import { parseSql } from '../sql/parse-sql.js';
|
|
6
|
+
import { rawSql } from '../sql/sql.js';
|
|
7
|
+
import { rowDeleteHandler } from './handlers/row-delete.handler.js';
|
|
8
|
+
import { rowInsertHandler } from './handlers/row-insert.handler.js';
|
|
9
|
+
import { rowSelectHandler } from './handlers/row-select.handler.js';
|
|
10
|
+
import { rowUpdateHandler } from './handlers/row-update.handler.js';
|
|
11
|
+
import { tableAlterHandler } from './handlers/table-alter.handler.js';
|
|
12
|
+
import { tableCreateHandler } from './handlers/table-create.handler.js';
|
|
13
|
+
import { tableDropHandler } from './handlers/table-drop.handler.js';
|
|
14
|
+
/**
|
|
15
|
+
* All current SQL handlers.
|
|
16
|
+
*
|
|
17
|
+
* @category Internal
|
|
18
|
+
*/
|
|
19
|
+
export const allAstHandlers = [
|
|
20
|
+
tableAlterHandler,
|
|
21
|
+
tableCreateHandler,
|
|
22
|
+
rowInsertHandler,
|
|
23
|
+
tableDropHandler,
|
|
24
|
+
rowDeleteHandler,
|
|
25
|
+
rowUpdateHandler,
|
|
26
|
+
rowSelectHandler,
|
|
27
|
+
];
|
|
28
|
+
/**
|
|
29
|
+
* The main entry point to this package. Run SQLite-compatible SQL commands on a collection of CSV
|
|
30
|
+
* files.
|
|
31
|
+
*
|
|
32
|
+
* @category Main
|
|
33
|
+
*/
|
|
34
|
+
export async function executeSql(sqlInput, params) {
|
|
35
|
+
// eslint-disable-next-line @typescript-eslint/no-deprecated
|
|
36
|
+
const sql = check.isString(sqlInput) ? rawSql(sqlInput) : sqlInput;
|
|
37
|
+
const astResults = parseSql(sql, params);
|
|
38
|
+
await mkdir(params.csvDirPath, {
|
|
39
|
+
recursive: true,
|
|
40
|
+
});
|
|
41
|
+
return await awaitedBlockingMap(astResults, async (ast) => {
|
|
42
|
+
return await executeIndividualCommand({
|
|
43
|
+
...params,
|
|
44
|
+
ast,
|
|
45
|
+
sql,
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
async function executeIndividualCommand(params) {
|
|
50
|
+
try {
|
|
51
|
+
for (const handler of allAstHandlers) {
|
|
52
|
+
const output = await handler.handler(params);
|
|
53
|
+
if (output) {
|
|
54
|
+
return output;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/** If nothing handled the query, then we don't support it. */
|
|
58
|
+
if (params.rejectUnsupportedOperations) {
|
|
59
|
+
throw new SqlUnsupportedOperationError(params.sql, undefined);
|
|
60
|
+
}
|
|
61
|
+
return [];
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
throw ensureErrorAndPrependMessage(error, `Failed to execute '${params.ast.type}' command.`);
|
|
65
|
+
}
|
|
66
|
+
}
|