@apso/cli 0.57.0 → 0.57.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.
@@ -11,6 +11,11 @@
11
11
  * - target table name = snakeCase(entity name) = snakeCase(source table name)
12
12
  * - single-column FK = renamed to the platform's camelCase `<ref>Id`
13
13
  * - every other column = copied under its original name
14
+ *
15
+ * Values travel as the text Postgres prints for them and are parsed again by
16
+ * the target column, so an array, a timestamp's microseconds, an interval or a
17
+ * bytea arrive as they left. Reading them into JavaScript values first lost
18
+ * the microseconds and broke every array column.
14
19
  */
15
20
  import { IntrospectedSchema, IntrospectedTable } from "./types";
16
21
  export interface ColumnMapping {
@@ -24,6 +29,8 @@ export interface TableCopyPlan {
24
29
  sourceColumns: string[];
25
30
  /** Target column names, parallel to sourceColumns. */
26
31
  targetColumns: string[];
32
+ /** The SQL that reads each source column as text, parallel to sourceColumns. */
33
+ sourceExpressions?: string[];
27
34
  /** Source PK column used to order paged reads (null when there is no PK). */
28
35
  orderBy: string | null;
29
36
  /** Target PK column whose sequence to reset after copy (null if not serial). */
@@ -60,9 +67,18 @@ export declare function topoSortTables(tables: IntrospectedTable[]): {
60
67
  * column is missing are dropped (and reported); source tables with no target
61
68
  * table are skipped entirely.
62
69
  */
63
- export declare function planCopy(source: IntrospectedSchema, targetColumnsByTable: Map<string, Set<string>>, tableFilter?: string[]): CopyPlan;
64
- /** Coerce a value read from pg into something safe to bind on insert. */
70
+ export declare function planCopy(source: IntrospectedSchema, targetColumnsByTable: Map<string, Set<string> | Map<string, string>>, tableFilter?: string[]): CopyPlan;
71
+ /**
72
+ * Coerce a value into something safe to bind on insert. The copy reads every
73
+ * column as text, so it sees strings and nulls; the other branches serve a
74
+ * reader that returns JavaScript values.
75
+ */
65
76
  export declare function coerceValue(value: unknown): unknown;
77
+ /**
78
+ * Build the paged SELECT that reads a batch of source rows. Each column comes
79
+ * back under its own name; `expressions` says how to read it.
80
+ */
81
+ export declare function buildSelectSql(table: string, columns: string[], orderBy: string | null, schema?: string, expressions?: string[]): string;
66
82
  /** Build a parameterized multi-row INSERT statement for a batch. */
67
83
  export declare function buildInsertSql(table: string, columns: string[], rows: unknown[][], schema?: string): {
68
84
  text: string;
@@ -70,7 +86,9 @@ export declare function buildInsertSql(table: string, columns: string[], rows: u
70
86
  };
71
87
  export interface SourceReader {
72
88
  totalRows(table: string): Promise<number>;
73
- readBatch(table: string, columns: string[], orderBy: string | null, offset: number, limit: number): Promise<unknown[][]>;
89
+ readBatch(table: string, columns: string[], orderBy: string | null, offset: number, limit: number,
90
+ /** The SQL that reads each column, parallel to columns. Defaults to the column itself. */
91
+ expressions?: string[]): Promise<unknown[][]>;
74
92
  }
75
93
  export interface TargetWriter {
76
94
  rowCount(table: string): Promise<number>;
@@ -102,5 +120,5 @@ export interface ExecuteOptions {
102
120
  * on the target, so a failure rolls everything back.
103
121
  */
104
122
  export declare function executeCopy(plan: CopyPlan, source: SourceReader, target: TargetWriter, options?: ExecuteOptions): Promise<CopyResult>;
105
- /** Build the target column lookup used by planCopy from an introspected target. */
106
- export declare function targetColumnsFromSchema(target: IntrospectedSchema): Map<string, Set<string>>;
123
+ /** Build the target lookup used by planCopy from an introspected target: each table's columns and their types. */
124
+ export declare function targetColumnsFromSchema(target: IntrospectedSchema): Map<string, Map<string, string>>;
@@ -12,9 +12,14 @@
12
12
  * - target table name = snakeCase(entity name) = snakeCase(source table name)
13
13
  * - single-column FK = renamed to the platform's camelCase `<ref>Id`
14
14
  * - every other column = copied under its original name
15
+ *
16
+ * Values travel as the text Postgres prints for them and are parsed again by
17
+ * the target column, so an array, a timestamp's microseconds, an interval or a
18
+ * bytea arrive as they left. Reading them into JavaScript values first lost
19
+ * the microseconds and broke every array column.
15
20
  */
16
21
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.targetColumnsFromSchema = exports.executeCopy = exports.buildInsertSql = exports.coerceValue = exports.planCopy = exports.topoSortTables = exports.buildColumnMapping = exports.targetTableName = void 0;
22
+ exports.targetColumnsFromSchema = exports.executeCopy = exports.buildInsertSql = exports.buildSelectSql = exports.coerceValue = exports.planCopy = exports.topoSortTables = exports.buildColumnMapping = exports.targetTableName = void 0;
18
23
  const casing_1 = require("../utils/casing");
19
24
  const relationships_1 = require("../utils/relationships");
20
25
  const pg_to_apsorc_1 = require("./pg-to-apsorc");
@@ -98,7 +103,7 @@ exports.topoSortTables = topoSortTables;
98
103
  * table are skipped entirely.
99
104
  */
100
105
  function planCopy(source, targetColumnsByTable, tableFilter) {
101
- var _a;
106
+ var _a, _b;
102
107
  const filter = tableFilter && tableFilter.length > 0 ? new Set(tableFilter) : null;
103
108
  const consideredTables = source.tables.filter((t) => !filter || filter.has(t.name));
104
109
  const { order, cyclic } = topoSortTables(consideredTables);
@@ -117,6 +122,8 @@ function planCopy(source, targetColumnsByTable, tableFilter) {
117
122
  const mapping = buildColumnMapping(table);
118
123
  const keptSource = [];
119
124
  const keptTarget = [];
125
+ const expressions = [];
126
+ const sourceTypes = new Map(table.columns.map((c) => [c.name, c.udtName]));
120
127
  for (const m of mapping) {
121
128
  // An import keeps foreign key column names ("joinColumnName"); a project
122
129
  // imported by an older CLI has the generated camelCase name instead.
@@ -125,6 +132,14 @@ function planCopy(source, targetColumnsByTable, tableFilter) {
125
132
  if (targetColumns.has(m.targetColumn)) {
126
133
  keptSource.push(m.sourceColumn);
127
134
  keptTarget.push(m.targetColumn);
135
+ // An array whose target column is json (the field was changed to
136
+ // jsonb after the import) is sent as a JSON array.
137
+ const targetType = targetColumns instanceof Map ? targetColumns.get(m.targetColumn) : "";
138
+ const arrayToJson = ((_a = sourceTypes.get(m.sourceColumn)) === null || _a === void 0 ? void 0 : _a.startsWith("_")) &&
139
+ (targetType === "json" || targetType === "jsonb");
140
+ expressions.push(arrayToJson
141
+ ? `to_jsonb("${m.sourceColumn}")::text`
142
+ : `"${m.sourceColumn}"::text`);
128
143
  }
129
144
  else {
130
145
  skippedColumns.push({
@@ -141,7 +156,7 @@ function planCopy(source, targetColumnsByTable, tableFilter) {
141
156
  const pkCol = table.primaryKey[0];
142
157
  orderBy = pkCol;
143
158
  const pk = table.columns.find((c) => c.name === pkCol);
144
- const targetPk = (_a = mapping.find((m) => m.sourceColumn === pkCol)) === null || _a === void 0 ? void 0 : _a.targetColumn;
159
+ const targetPk = (_b = mapping.find((m) => m.sourceColumn === pkCol)) === null || _b === void 0 ? void 0 : _b.targetColumn;
145
160
  if (pk && targetPk && INTEGER_PK_UDTS.has(pk.udtName)) {
146
161
  serialPkColumn = targetPk;
147
162
  }
@@ -151,6 +166,7 @@ function planCopy(source, targetColumnsByTable, tableFilter) {
151
166
  targetTable,
152
167
  sourceColumns: keptSource,
153
168
  targetColumns: keptTarget,
169
+ sourceExpressions: expressions,
154
170
  orderBy,
155
171
  serialPkColumn,
156
172
  });
@@ -158,7 +174,11 @@ function planCopy(source, targetColumnsByTable, tableFilter) {
158
174
  return { tables, skippedColumns, missingTargetTables, cyclicTables: cyclic };
159
175
  }
160
176
  exports.planCopy = planCopy;
161
- /** Coerce a value read from pg into something safe to bind on insert. */
177
+ /**
178
+ * Coerce a value into something safe to bind on insert. The copy reads every
179
+ * column as text, so it sees strings and nulls; the other branches serve a
180
+ * reader that returns JavaScript values.
181
+ */
162
182
  function coerceValue(value) {
163
183
  if (value === null || value === undefined)
164
184
  return null;
@@ -171,6 +191,21 @@ function coerceValue(value) {
171
191
  return value;
172
192
  }
173
193
  exports.coerceValue = coerceValue;
194
+ /**
195
+ * Build the paged SELECT that reads a batch of source rows. Each column comes
196
+ * back under its own name; `expressions` says how to read it.
197
+ */
198
+ function buildSelectSql(table, columns, orderBy, schema, expressions) {
199
+ const tableRef = schema ? `"${schema}"."${table}"` : `"${table}"`;
200
+ const cols = columns
201
+ .map((c, i) => { var _a; return `${(_a = expressions === null || expressions === void 0 ? void 0 : expressions[i]) !== null && _a !== void 0 ? _a : `"${c}"`} AS "${c}"`; })
202
+ .join(", ");
203
+ // Qualified, so the order is the column's own (and its index is used), not
204
+ // the text alias of the same name: as text, id 10 sorts before id 9.
205
+ const order = orderBy ? ` ORDER BY ${tableRef}."${orderBy}"` : "";
206
+ return `SELECT ${cols} FROM ${tableRef}${order} OFFSET $1 LIMIT $2`;
207
+ }
208
+ exports.buildSelectSql = buildSelectSql;
174
209
  /** Build a parameterized multi-row INSERT statement for a batch. */
175
210
  function buildInsertSql(table, columns, rows, schema) {
176
211
  const tableRef = schema ? `"${schema}"."${table}"` : `"${table}"`;
@@ -233,7 +268,7 @@ async function executeCopy(plan, source, target, options = {}) {
233
268
  // eslint-disable-next-line no-constant-condition
234
269
  while (true) {
235
270
  // eslint-disable-next-line no-await-in-loop
236
- const rows = await source.readBatch(t.sourceTable, t.sourceColumns, t.orderBy, offset, batchSize);
271
+ const rows = await source.readBatch(t.sourceTable, t.sourceColumns, t.orderBy, offset, batchSize, t.sourceExpressions);
237
272
  if (rows.length === 0)
238
273
  break;
239
274
  // eslint-disable-next-line no-await-in-loop
@@ -265,8 +300,11 @@ async function executeCopy(plan, source, target, options = {}) {
265
300
  };
266
301
  }
267
302
  exports.executeCopy = executeCopy;
268
- /** Build the target column lookup used by planCopy from an introspected target. */
303
+ /** Build the target lookup used by planCopy from an introspected target: each table's columns and their types. */
269
304
  function targetColumnsFromSchema(target) {
270
- return new Map(target.tables.map((t) => [t.name, new Set(t.columns.map((c) => c.name))]));
305
+ return new Map(target.tables.map((t) => [
306
+ t.name,
307
+ new Map(t.columns.map((c) => [c.name, c.udtName])),
308
+ ]));
271
309
  }
272
310
  exports.targetColumnsFromSchema = targetColumnsFromSchema;
@@ -2,6 +2,6 @@ export * from "./types";
2
2
  export { pgToApsorc, findUnknownEmittedTypes } from "./pg-to-apsorc";
3
3
  export type { ApsorcImportOutput, ApsorcImportEntityOutput, ApsorcImportFieldOutput, ApsorcImportRelationshipOutput, } from "./pg-to-apsorc";
4
4
  export { PgIntrospector, redactConnectionString, buildSchema, SYSTEM_SCHEMAS } from "./introspect";
5
- export { planCopy, executeCopy, buildColumnMapping, topoSortTables, targetTableName, targetColumnsFromSchema, buildInsertSql, coerceValue, } from "./copy-data";
5
+ export { planCopy, executeCopy, buildColumnMapping, topoSortTables, targetTableName, targetColumnsFromSchema, buildInsertSql, buildSelectSql, coerceValue, } from "./copy-data";
6
6
  export type { CopyPlan, CopyResult, TableCopyPlan, ColumnMapping, SourceReader, TargetWriter, ExecuteOptions, } from "./copy-data";
7
7
  export { PgSourceReader, PgTargetWriter } from "./pg-data";
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PgTargetWriter = exports.PgSourceReader = exports.coerceValue = exports.buildInsertSql = exports.targetColumnsFromSchema = exports.targetTableName = exports.topoSortTables = exports.buildColumnMapping = exports.executeCopy = exports.planCopy = exports.SYSTEM_SCHEMAS = exports.buildSchema = exports.redactConnectionString = exports.PgIntrospector = exports.findUnknownEmittedTypes = exports.pgToApsorc = void 0;
3
+ exports.PgTargetWriter = exports.PgSourceReader = exports.coerceValue = exports.buildSelectSql = exports.buildInsertSql = exports.targetColumnsFromSchema = exports.targetTableName = exports.topoSortTables = exports.buildColumnMapping = exports.executeCopy = exports.planCopy = exports.SYSTEM_SCHEMAS = exports.buildSchema = exports.redactConnectionString = exports.PgIntrospector = exports.findUnknownEmittedTypes = exports.pgToApsorc = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  tslib_1.__exportStar(require("./types"), exports);
6
6
  var pg_to_apsorc_1 = require("./pg-to-apsorc");
@@ -19,6 +19,7 @@ Object.defineProperty(exports, "topoSortTables", { enumerable: true, get: functi
19
19
  Object.defineProperty(exports, "targetTableName", { enumerable: true, get: function () { return copy_data_1.targetTableName; } });
20
20
  Object.defineProperty(exports, "targetColumnsFromSchema", { enumerable: true, get: function () { return copy_data_1.targetColumnsFromSchema; } });
21
21
  Object.defineProperty(exports, "buildInsertSql", { enumerable: true, get: function () { return copy_data_1.buildInsertSql; } });
22
+ Object.defineProperty(exports, "buildSelectSql", { enumerable: true, get: function () { return copy_data_1.buildSelectSql; } });
22
23
  Object.defineProperty(exports, "coerceValue", { enumerable: true, get: function () { return copy_data_1.coerceValue; } });
23
24
  var pg_data_1 = require("./pg-data");
24
25
  Object.defineProperty(exports, "PgSourceReader", { enumerable: true, get: function () { return pg_data_1.PgSourceReader; } });
@@ -14,7 +14,7 @@ export declare class PgSourceReader implements SourceReader {
14
14
  private constructor();
15
15
  static connect(connectionString: string, schema: string): Promise<PgSourceReader>;
16
16
  totalRows(table: string): Promise<number>;
17
- readBatch(table: string, columns: string[], orderBy: string | null, offset: number, limit: number): Promise<unknown[][]>;
17
+ readBatch(table: string, columns: string[], orderBy: string | null, offset: number, limit: number, expressions?: string[]): Promise<unknown[][]>;
18
18
  close(): Promise<void>;
19
19
  }
20
20
  /** Writes rows into the target database within a single transaction. */
@@ -53,16 +53,21 @@ class PgSourceReader {
53
53
  this.schema = schema;
54
54
  }
55
55
  static async connect(connectionString, schema) {
56
- return new PgSourceReader(await createClient(connectionString), schema);
56
+ const client = await createClient(connectionString);
57
+ // Values are read as text, so the text must mean the same on the target:
58
+ // ISO dates whatever the source's DateStyle (with "SQL, DMY" the day and
59
+ // month would swap), and every digit of a float.
60
+ await client.query("SET datestyle = 'ISO'");
61
+ await client.query("SET extra_float_digits = 3");
62
+ return new PgSourceReader(client, schema);
57
63
  }
58
64
  async totalRows(table) {
59
65
  const res = await this.client.query(`SELECT count(*)::int AS n FROM ${qualified(this.schema, table)}`);
60
66
  return res.rows[0].n;
61
67
  }
62
- async readBatch(table, columns, orderBy, offset, limit) {
63
- const cols = columns.map((c) => `"${c}"`).join(", ");
64
- const order = orderBy ? ` ORDER BY "${orderBy}"` : "";
65
- const res = await this.client.query(`SELECT ${cols} FROM ${qualified(this.schema, table)}${order} OFFSET $1 LIMIT $2`, [offset, limit]);
68
+ async readBatch(table, columns, orderBy, offset, limit, expressions) {
69
+ const { buildSelectSql } = await Promise.resolve().then(() => __importStar(require("./copy-data")));
70
+ const res = await this.client.query(buildSelectSql(table, columns, orderBy, this.schema, expressions), [offset, limit]);
66
71
  return res.rows.map((row) => columns.map((c) => row[c]));
67
72
  }
68
73
  async close() {
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@apso/cli",
3
- "version": "0.57.0",
3
+ "version": "0.57.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@apso/cli",
9
- "version": "0.57.0",
9
+ "version": "0.57.1",
10
10
  "license": "Apache-2.0",
11
11
  "dependencies": {
12
12
  "@apso/schema-tools": "^0.2.3",
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.57.0",
2
+ "version": "0.57.1",
3
3
  "commands": {
4
4
  "config": {
5
5
  "id": "config",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@apso/cli",
3
- "version": "0.57.0",
3
+ "version": "0.57.1",
4
4
  "mcpName": "io.github.apsoai/apso",
5
5
  "description": "Apso CLI",
6
6
  "author": "Apso by Mavric - @mavric",