csv-to-pg 0.6.2 → 2.0.2

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/parser.js ADDED
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Parser = void 0;
4
+ // @ts-nocheck
5
+ const fs_1 = require("fs");
6
+ const index_1 = require("./index");
7
+ const pgsql_deparser_1 = require("pgsql-deparser");
8
+ const utils_1 = require("./utils");
9
+ class Parser {
10
+ constructor(config) {
11
+ this.config = config;
12
+ }
13
+ async parse(data) {
14
+ const config = this.config;
15
+ const { schema, table, singleStmts, conflict, headers, delimeter } = config;
16
+ const opts = {};
17
+ if (headers)
18
+ opts.headers = headers;
19
+ if (delimeter)
20
+ opts.separator = delimeter;
21
+ let records;
22
+ if (typeof data === 'undefined') {
23
+ if (config.json || config.input.endsWith('.json')) {
24
+ records = JSON.parse((0, fs_1.readFileSync)(config.input, 'utf-8'));
25
+ }
26
+ else {
27
+ records = await (0, index_1.parse)(config.input, opts);
28
+ }
29
+ }
30
+ else {
31
+ if (!Array.isArray(data)) {
32
+ throw new Error('data is not an array');
33
+ }
34
+ records = data;
35
+ }
36
+ if (config.debug) {
37
+ console.log(records);
38
+ return;
39
+ }
40
+ const types = (0, index_1.parseTypes)(config);
41
+ if (singleStmts) {
42
+ const stmts = records.map((record) => (0, utils_1.InsertOne)({
43
+ schema,
44
+ table,
45
+ types,
46
+ record,
47
+ conflict
48
+ }));
49
+ return (0, pgsql_deparser_1.deparse)(stmts);
50
+ }
51
+ else {
52
+ const stmt = (0, utils_1.InsertMany)({
53
+ schema,
54
+ table,
55
+ types,
56
+ records,
57
+ conflict
58
+ });
59
+ return (0, pgsql_deparser_1.deparse)([stmt]);
60
+ }
61
+ }
62
+ }
63
+ exports.Parser = Parser;
package/utils.d.ts ADDED
@@ -0,0 +1,135 @@
1
+ export declare const normalizePath: (path: any, cwd: any) => any;
2
+ export declare const makeLocation: (longitude: any, latitude: any) => {
3
+ Null: {};
4
+ } | {
5
+ FuncCall: {};
6
+ };
7
+ export declare const makeBoundingBox: (bbox: any) => {
8
+ FuncCall: {};
9
+ };
10
+ export declare const InsertOne: ({ schema, table, types, record, conflict }: {
11
+ schema?: string;
12
+ table: any;
13
+ types: any;
14
+ record: any;
15
+ conflict: any;
16
+ }) => {
17
+ RawStmt: {
18
+ stmt: {
19
+ InsertStmt: {
20
+ relation: {
21
+ RangeVar: {
22
+ schemaname: string;
23
+ relname: any;
24
+ inh: boolean;
25
+ relpersistence: string;
26
+ };
27
+ };
28
+ cols: {
29
+ ResTarget: {};
30
+ }[];
31
+ selectStmt: {
32
+ SelectStmt: {
33
+ valuesLists: any[][];
34
+ op: number;
35
+ };
36
+ };
37
+ onConflictClause: {
38
+ OnConflictClause: {
39
+ action: number;
40
+ infer: {
41
+ InferClause: {
42
+ indexElems: any;
43
+ };
44
+ };
45
+ targetList: any;
46
+ };
47
+ } | {
48
+ OnConflictClause: {
49
+ action: number;
50
+ infer: {
51
+ InferClause: {
52
+ indexElems: any;
53
+ };
54
+ };
55
+ targetList?: undefined;
56
+ };
57
+ };
58
+ override: number;
59
+ };
60
+ };
61
+ stmt_len: number;
62
+ };
63
+ };
64
+ export declare const InsertMany: ({ schema, table, types, records, conflict }: {
65
+ schema?: string;
66
+ table: any;
67
+ types: any;
68
+ records: any;
69
+ conflict: any;
70
+ }) => {
71
+ RawStmt: {
72
+ stmt: {
73
+ InsertStmt: {
74
+ relation: {
75
+ RangeVar: {
76
+ schemaname: string;
77
+ relname: any;
78
+ inh: boolean;
79
+ relpersistence: string;
80
+ };
81
+ };
82
+ cols: {
83
+ ResTarget: {};
84
+ }[];
85
+ selectStmt: {
86
+ SelectStmt: {
87
+ valuesLists: any;
88
+ op: number;
89
+ };
90
+ };
91
+ onConflictClause: {
92
+ OnConflictClause: {
93
+ action: number;
94
+ infer: {
95
+ InferClause: {
96
+ indexElems: any;
97
+ };
98
+ };
99
+ targetList: any;
100
+ };
101
+ } | {
102
+ OnConflictClause: {
103
+ action: number;
104
+ infer: {
105
+ InferClause: {
106
+ indexElems: any;
107
+ };
108
+ };
109
+ targetList?: undefined;
110
+ };
111
+ };
112
+ override: number;
113
+ };
114
+ };
115
+ stmt_len: number;
116
+ };
117
+ };
118
+ export declare const wrapValue: (val: any, { wrap, wrapAst, cast }?: {
119
+ wrap: any;
120
+ wrapAst: any;
121
+ cast: any;
122
+ }) => any;
123
+ export declare const getRelatedField: ({ schema, table, refType, refKey, refField, wrap, wrapAst, cast, record, parse, from }: {
124
+ schema?: string;
125
+ table: any;
126
+ refType: any;
127
+ refKey: any;
128
+ refField: any;
129
+ wrap: any;
130
+ wrapAst: any;
131
+ cast: any;
132
+ record: any;
133
+ parse: any;
134
+ from: any;
135
+ }) => any;
package/utils.js ADDED
@@ -0,0 +1,300 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.getRelatedField = exports.wrapValue = exports.InsertMany = exports.InsertOne = exports.makeBoundingBox = exports.makeLocation = exports.normalizePath = void 0;
27
+ // @ts-nocheck
28
+ const ast = __importStar(require("pg-ast"));
29
+ const path_1 = require("path");
30
+ const normalizePath = (path, cwd) => path.startsWith('/') ? path : (0, path_1.resolve)((0, path_1.join)(cwd ? cwd : process.cwd(), path));
31
+ exports.normalizePath = normalizePath;
32
+ const lstr = (bbox) => {
33
+ const [lng1, lat1, lng2, lat2] = bbox.split(',').map((a) => a.trim());
34
+ return `LINESTRING(${lng1} ${lat1}, ${lng1} ${lat2}, ${lng2} ${lat2}, ${lng2} ${lat1}, ${lng1} ${lat1})`;
35
+ };
36
+ const funcCall = (name, args) => {
37
+ return ast.FuncCall({
38
+ funcname: [ast.String({ str: name })],
39
+ args
40
+ });
41
+ };
42
+ const aflt = (num) => ast.A_Const({ val: ast.Float({ str: num }) });
43
+ const aint = (num) => ast.A_Const({ val: ast.Integer({ ival: num }) });
44
+ const makeLocation = (longitude, latitude) => {
45
+ if (!longitude || !latitude) {
46
+ return ast.Null();
47
+ }
48
+ return funcCall('st_setsrid', [
49
+ funcCall('st_makepoint', [aflt(longitude), aflt(latitude)]),
50
+ aint(4326)
51
+ ]);
52
+ };
53
+ exports.makeLocation = makeLocation;
54
+ // a string in the form of lon,lat,lon,lat
55
+ // -118.587533,34.024999,-118.495177,34.13165
56
+ const makeBoundingBox = (bbox) => {
57
+ return funcCall('st_setsrid', [
58
+ funcCall('st_makepolygon', [
59
+ funcCall('st_geomfromtext', [
60
+ ast.A_Const({ val: ast.String({ str: lstr(bbox) }) })
61
+ ])
62
+ ]),
63
+ aint(4326)
64
+ ]);
65
+ };
66
+ exports.makeBoundingBox = makeBoundingBox;
67
+ const ValuesLists = ({ types, record }) => Object.entries(types).map(([field, type]) => {
68
+ if (typeof type === 'function') {
69
+ return type(record);
70
+ }
71
+ throw new Error('coercion function missing');
72
+ });
73
+ const makeCast = (arg, type) => ({
74
+ TypeCast: {
75
+ arg,
76
+ typeName: {
77
+ TypeName: {
78
+ names: [
79
+ {
80
+ String: {
81
+ str: type
82
+ }
83
+ }
84
+ ],
85
+ typemod: -1
86
+ }
87
+ }
88
+ }
89
+ });
90
+ const ref = (name) => ({
91
+ ResTarget: {
92
+ name,
93
+ val: {
94
+ ColumnRef: {
95
+ fields: [
96
+ {
97
+ String: {
98
+ str: 'excluded'
99
+ }
100
+ },
101
+ {
102
+ String: {
103
+ str: name
104
+ }
105
+ }
106
+ ]
107
+ }
108
+ }
109
+ }
110
+ });
111
+ const indexElem = (name) => ({
112
+ IndexElem: {
113
+ name,
114
+ ordering: 0,
115
+ nulls_ordering: 0
116
+ }
117
+ });
118
+ const makeConflictClause = (conflictElems, fields) => {
119
+ if (!conflictElems || !conflictElems.length)
120
+ return undefined;
121
+ const setElems = fields.filter((el) => !conflictElems.includes(el));
122
+ if (setElems.length) {
123
+ return {
124
+ OnConflictClause: {
125
+ action: 2,
126
+ infer: {
127
+ InferClause: {
128
+ indexElems: conflictElems.map((a) => indexElem(a))
129
+ }
130
+ },
131
+ targetList: setElems.map((a) => ref(a))
132
+ }
133
+ };
134
+ }
135
+ else {
136
+ return {
137
+ OnConflictClause: {
138
+ action: 1,
139
+ infer: {
140
+ InferClause: {
141
+ indexElems: conflictElems.map((a) => indexElem(a))
142
+ }
143
+ }
144
+ }
145
+ };
146
+ }
147
+ };
148
+ const InsertOne = ({ schema = 'public', table, types, record, conflict }) => ({
149
+ RawStmt: {
150
+ stmt: {
151
+ InsertStmt: {
152
+ relation: {
153
+ RangeVar: {
154
+ schemaname: schema,
155
+ relname: table,
156
+ inh: true,
157
+ relpersistence: 'p'
158
+ }
159
+ },
160
+ cols: Object.keys(types).map((field) => ast.ResTarget({ name: field })),
161
+ selectStmt: {
162
+ SelectStmt: {
163
+ valuesLists: [ValuesLists({ types, record })],
164
+ op: 0
165
+ }
166
+ },
167
+ onConflictClause: makeConflictClause(conflict, Object.keys(types)),
168
+ override: 0
169
+ }
170
+ },
171
+ stmt_len: 1
172
+ }
173
+ });
174
+ exports.InsertOne = InsertOne;
175
+ const InsertMany = ({ schema = 'public', table, types, records, conflict }) => ({
176
+ RawStmt: {
177
+ stmt: {
178
+ InsertStmt: {
179
+ relation: {
180
+ RangeVar: {
181
+ schemaname: schema,
182
+ relname: table,
183
+ inh: true,
184
+ relpersistence: 'p'
185
+ }
186
+ },
187
+ cols: Object.keys(types).map((field) => ast.ResTarget({ name: field })),
188
+ selectStmt: {
189
+ SelectStmt: {
190
+ valuesLists: records.map((record) => ValuesLists({ types, record })),
191
+ op: 0
192
+ }
193
+ },
194
+ onConflictClause: makeConflictClause(conflict, Object.keys(types)),
195
+ override: 0
196
+ }
197
+ },
198
+ stmt_len: 1
199
+ }
200
+ });
201
+ exports.InsertMany = InsertMany;
202
+ const wrapValue = (val, { wrap, wrapAst, cast } = {}) => {
203
+ if (Array.isArray(wrap)) {
204
+ val = ast.FuncCall({
205
+ funcname: wrap.map((n) => ast.String({ str: n })),
206
+ args: [val]
207
+ });
208
+ }
209
+ if (wrapAst)
210
+ return wrapAst(val);
211
+ if (cast)
212
+ return makeCast(val, cast);
213
+ return val;
214
+ };
215
+ exports.wrapValue = wrapValue;
216
+ const getRelatedField = ({ schema = 'public', table, refType, refKey, refField, wrap, wrapAst, cast, record, parse, from }) => {
217
+ let val;
218
+ const value = parse(record[from[0]]);
219
+ if (typeof value === 'undefined') {
220
+ return ast.Null({});
221
+ }
222
+ switch (refType) {
223
+ case 'int':
224
+ val = ast.A_Const({ val: ast.Integer({ ival: value }) });
225
+ break;
226
+ case 'float':
227
+ val = ast.A_Const({ val: ast.Float({ str: value }) });
228
+ break;
229
+ case 'boolean':
230
+ case 'bool':
231
+ val = ast.String({ str: value ? 'TRUE' : 'FALSE' });
232
+ break;
233
+ case 'text':
234
+ default:
235
+ val = ast.A_Const({ val: ast.String({ str: value }) });
236
+ }
237
+ val = (0, exports.wrapValue)(val, { wrap, wrapAst });
238
+ return (0, exports.wrapValue)({
239
+ SubLink: {
240
+ subLinkType: 4,
241
+ subselect: {
242
+ SelectStmt: {
243
+ targetList: [
244
+ {
245
+ ResTarget: {
246
+ val: {
247
+ ColumnRef: {
248
+ fields: [
249
+ {
250
+ String: {
251
+ str: refKey
252
+ }
253
+ }
254
+ ]
255
+ }
256
+ }
257
+ }
258
+ }
259
+ ],
260
+ fromClause: [
261
+ {
262
+ RangeVar: {
263
+ schemaname: schema,
264
+ relname: table,
265
+ inh: true,
266
+ relpersistence: 'p'
267
+ }
268
+ }
269
+ ],
270
+ whereClause: {
271
+ A_Expr: {
272
+ kind: 0,
273
+ name: [
274
+ {
275
+ String: {
276
+ str: '='
277
+ }
278
+ }
279
+ ],
280
+ lexpr: {
281
+ ColumnRef: {
282
+ fields: [
283
+ {
284
+ String: {
285
+ str: refField
286
+ }
287
+ }
288
+ ]
289
+ }
290
+ },
291
+ rexpr: val
292
+ }
293
+ },
294
+ op: 0
295
+ }
296
+ }
297
+ }
298
+ }, { cast });
299
+ };
300
+ exports.getRelatedField = getRelatedField;
package/main/cli.js DELETED
@@ -1,96 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
-
4
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
5
-
6
- var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
7
-
8
- var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
9
-
10
- var _prompt = require("@pyramation/prompt");
11
-
12
- var _parse = require("./parse");
13
-
14
- var _parser = require("./parser");
15
-
16
- var _utils = require("./utils");
17
-
18
- var _path = require("path");
19
-
20
- var _fs = require("fs");
21
-
22
- var argv = process.argv.slice(2);
23
- (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
24
- var _yield$prompt, config, dir, results, outFile, parser, sql;
25
-
26
- return _regenerator["default"].wrap(function _callee$(_context) {
27
- while (1) {
28
- switch (_context.prev = _context.next) {
29
- case 0:
30
- _context.next = 2;
31
- return (0, _prompt.prompt)([{
32
- _: true,
33
- name: 'config',
34
- type: 'config',
35
- required: true
36
- }], argv);
37
-
38
- case 2:
39
- _yield$prompt = _context.sent;
40
- config = _yield$prompt.config;
41
- config = (0, _utils.normalizePath)(config);
42
- dir = (0, _path.dirname)(config);
43
- config = (0, _parse.readConfig)(config);
44
-
45
- if (config.input) {
46
- if (!argv.includes('--input')) {
47
- argv.push('--input');
48
- config.input = (0, _utils.normalizePath)(config.input, dir);
49
- argv.push(config.input);
50
- }
51
- }
52
-
53
- if (config.output) {
54
- if (!argv.includes('--output')) {
55
- argv.push('--output');
56
- config.output = (0, _utils.normalizePath)(config.output, dir);
57
- argv.push(config.output);
58
- }
59
- }
60
-
61
- _context.next = 11;
62
- return (0, _prompt.prompt)([{
63
- name: 'input',
64
- type: 'path',
65
- required: true
66
- }, {
67
- name: 'output',
68
- type: 'path',
69
- required: true
70
- }], argv);
71
-
72
- case 11:
73
- results = _context.sent;
74
- config.input = results.input;
75
- outFile = results.output;
76
- if (!outFile.endsWith('.sql')) outFile = outFile + '.sql';
77
-
78
- if (argv.includes('--debug')) {
79
- config.debug = true;
80
- }
81
-
82
- parser = new _parser.Parser(config);
83
- _context.next = 19;
84
- return parser.parse();
85
-
86
- case 19:
87
- sql = _context.sent;
88
- (0, _fs.writeFileSync)(config.output, sql);
89
-
90
- case 21:
91
- case "end":
92
- return _context.stop();
93
- }
94
- }
95
- }, _callee);
96
- }))();
package/main/index.js DELETED
@@ -1,29 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
-
7
- var _parse = require("./parse");
8
-
9
- Object.keys(_parse).forEach(function (key) {
10
- if (key === "default" || key === "__esModule") return;
11
- Object.defineProperty(exports, key, {
12
- enumerable: true,
13
- get: function get() {
14
- return _parse[key];
15
- }
16
- });
17
- });
18
-
19
- var _parser = require("./parser");
20
-
21
- Object.keys(_parser).forEach(function (key) {
22
- if (key === "default" || key === "__esModule") return;
23
- Object.defineProperty(exports, key, {
24
- enumerable: true,
25
- get: function get() {
26
- return _parser[key];
27
- }
28
- });
29
- });