@yandjin-mikro-orm/postgresql 6.1.4-rc-sti-changes-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.
@@ -0,0 +1,314 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.PostgreSqlPlatform = void 0;
7
+ const pg_1 = require("pg");
8
+ const postgres_date_1 = __importDefault(require("postgres-date"));
9
+ const postgres_interval_1 = __importDefault(require("postgres-interval"));
10
+ const core_1 = require("@yandjin-mikro-orm/core");
11
+ const knex_1 = require("@yandjin-mikro-orm/knex");
12
+ const PostgreSqlSchemaHelper_1 = require("./PostgreSqlSchemaHelper");
13
+ const PostgreSqlExceptionConverter_1 = require("./PostgreSqlExceptionConverter");
14
+ const FullTextType_1 = require("./types/FullTextType");
15
+ class PostgreSqlPlatform extends knex_1.AbstractSqlPlatform {
16
+ schemaHelper = new PostgreSqlSchemaHelper_1.PostgreSqlSchemaHelper(this);
17
+ exceptionConverter = new PostgreSqlExceptionConverter_1.PostgreSqlExceptionConverter();
18
+ usesReturningStatement() {
19
+ return true;
20
+ }
21
+ usesCascadeStatement() {
22
+ return true;
23
+ }
24
+ supportsNativeEnums() {
25
+ return true;
26
+ }
27
+ supportsCustomPrimaryKeyNames() {
28
+ return true;
29
+ }
30
+ /**
31
+ * Postgres will complain if we try to batch update uniquely constrained property (moving the value from one entity to another).
32
+ * This flag will result in postponing 1:1 updates (removing them from the batched query).
33
+ * @see https://stackoverflow.com/questions/5403437/atomic-multi-row-update-with-a-unique-constraint
34
+ */
35
+ allowsUniqueBatchUpdates() {
36
+ return false;
37
+ }
38
+ getCurrentTimestampSQL(length) {
39
+ return `current_timestamp(${length})`;
40
+ }
41
+ getDateTimeTypeDeclarationSQL(column) {
42
+ /* istanbul ignore next */
43
+ return "timestamptz" + (column.length != null ? `(${column.length})` : "");
44
+ }
45
+ getDefaultDateTimeLength() {
46
+ return 6; // timestamptz actually means timestamptz(6)
47
+ }
48
+ convertIntervalToJSValue(value) {
49
+ return (0, postgres_interval_1.default)(value);
50
+ }
51
+ convertIntervalToDatabaseValue(value) {
52
+ if (core_1.Utils.isObject(value) &&
53
+ "toPostgres" in value &&
54
+ typeof value.toPostgres === "function") {
55
+ return value.toPostgres();
56
+ }
57
+ return value;
58
+ }
59
+ getTimeTypeDeclarationSQL() {
60
+ return "time(0)";
61
+ }
62
+ getIntegerTypeDeclarationSQL(column) {
63
+ if (column.autoincrement && !column.generated) {
64
+ return `serial`;
65
+ }
66
+ return `int`;
67
+ }
68
+ getBigIntTypeDeclarationSQL(column) {
69
+ /* istanbul ignore next */
70
+ if (column.autoincrement) {
71
+ return `bigserial`;
72
+ }
73
+ return "bigint";
74
+ }
75
+ getTinyIntTypeDeclarationSQL(column) {
76
+ return "smallint";
77
+ }
78
+ getUuidTypeDeclarationSQL(column) {
79
+ return `uuid`;
80
+ }
81
+ getFullTextWhereClause(prop) {
82
+ if (prop.customType instanceof FullTextType_1.FullTextType) {
83
+ return `:column: @@ plainto_tsquery('${prop.customType.regconfig}', :query)`;
84
+ }
85
+ if (prop.columnTypes[0] === "tsvector") {
86
+ return `:column: @@ plainto_tsquery('simple', :query)`;
87
+ }
88
+ return `to_tsvector('simple', :column:) @@ plainto_tsquery('simple', :query)`;
89
+ }
90
+ supportsCreatingFullTextIndex() {
91
+ return true;
92
+ }
93
+ getFullTextIndexExpression(indexName, schemaName, tableName, columns) {
94
+ /* istanbul ignore next */
95
+ const quotedTableName = this.quoteIdentifier(schemaName ? `${schemaName}.${tableName}` : tableName);
96
+ const quotedColumnNames = columns.map((c) => this.quoteIdentifier(c.name));
97
+ const quotedIndexName = this.quoteIdentifier(indexName);
98
+ if (columns.length === 1 && columns[0].type === "tsvector") {
99
+ return `create index ${quotedIndexName} on ${quotedTableName} using gin(${quotedColumnNames[0]})`;
100
+ }
101
+ return `create index ${quotedIndexName} on ${quotedTableName} using gin(to_tsvector('simple', ${quotedColumnNames.join(` || ' ' || `)}))`;
102
+ }
103
+ getMappedType(type) {
104
+ switch (this.extractSimpleType(type)) {
105
+ case "tsvector":
106
+ return core_1.Type.getType(FullTextType_1.FullTextType);
107
+ default:
108
+ return super.getMappedType(type);
109
+ }
110
+ }
111
+ getRegExpOperator(val, flags) {
112
+ if ((val instanceof RegExp && val.flags.includes("i")) ||
113
+ flags?.includes("i")) {
114
+ return "~*";
115
+ }
116
+ return "~";
117
+ }
118
+ getRegExpValue(val) {
119
+ /* istanbul ignore else */
120
+ if (val.flags.includes("i")) {
121
+ return { $re: val.source, $flags: val.flags };
122
+ }
123
+ /* istanbul ignore next */
124
+ return { $re: val.source };
125
+ }
126
+ isBigIntProperty(prop) {
127
+ return (super.isBigIntProperty(prop) ||
128
+ ["bigserial", "int8"].includes(prop.columnTypes?.[0]));
129
+ }
130
+ getArrayDeclarationSQL() {
131
+ return "text[]";
132
+ }
133
+ getFloatDeclarationSQL() {
134
+ return "real";
135
+ }
136
+ getDoubleDeclarationSQL() {
137
+ return "double precision";
138
+ }
139
+ getEnumTypeDeclarationSQL(column) {
140
+ if (column.nativeEnumName) {
141
+ return column.nativeEnumName;
142
+ }
143
+ if (column.items?.every((item) => core_1.Utils.isString(item))) {
144
+ return "text";
145
+ }
146
+ return `smallint`;
147
+ }
148
+ supportsMultipleStatements() {
149
+ return true;
150
+ }
151
+ marshallArray(values) {
152
+ const quote = (v) => v === "" || v.match(/["{},\\]/) ? JSON.stringify(v) : v;
153
+ return `{${values.map((v) => quote("" + v)).join(",")}}`;
154
+ }
155
+ unmarshallArray(value) {
156
+ if (value === "{}") {
157
+ return [];
158
+ }
159
+ /* istanbul ignore next */
160
+ return value
161
+ .substring(1, value.length - 1)
162
+ .split(",")
163
+ .map((v) => (v === `""` ? "" : v));
164
+ }
165
+ getBlobDeclarationSQL() {
166
+ return "bytea";
167
+ }
168
+ getJsonDeclarationSQL() {
169
+ return "jsonb";
170
+ }
171
+ getSearchJsonPropertyKey(path, type, aliased, value) {
172
+ const first = path.shift();
173
+ const last = path.pop();
174
+ const root = this.quoteIdentifier(aliased ? `${core_1.ALIAS_REPLACEMENT}.${first}` : first);
175
+ type =
176
+ typeof type === "string"
177
+ ? this.getMappedType(type).runtimeType
178
+ : String(type);
179
+ const types = {
180
+ number: "float8",
181
+ bigint: "int8",
182
+ boolean: "bool",
183
+ };
184
+ const cast = (key) => (0, core_1.raw)(type in types ? `(${key})::${types[type]}` : key);
185
+ let lastOperator = "->>";
186
+ // force `->` for operator payloads with array values
187
+ if (core_1.Utils.isPlainObject(value) &&
188
+ Object.keys(value).every((key) => core_1.Utils.isArrayOperator(key) && Array.isArray(value[key]))) {
189
+ lastOperator = "->";
190
+ }
191
+ if (path.length === 0) {
192
+ return cast(`${root}${lastOperator}'${last}'`);
193
+ }
194
+ return cast(`${root}->${path.map((a) => this.quoteValue(a)).join("->")}${lastOperator}'${last}'`);
195
+ }
196
+ getJsonIndexDefinition(index) {
197
+ return index.columnNames.map((column) => {
198
+ const path = column.split(".");
199
+ const first = path.shift();
200
+ const last = path.pop();
201
+ if (path.length === 0) {
202
+ return `${this.quoteIdentifier(first)}->>${this.quoteValue(last)}`;
203
+ }
204
+ return `${this.quoteIdentifier(first)}->${path.map((c) => this.quoteValue(c)).join("->")}->>${this.quoteValue(last)}`;
205
+ });
206
+ }
207
+ quoteIdentifier(id, quote = '"') {
208
+ return `${quote}${id.replace(".", `${quote}.${quote}`)}${quote}`;
209
+ }
210
+ quoteValue(value) {
211
+ /* istanbul ignore if */
212
+ if (core_1.Utils.isPlainObject(value) || value?.[core_1.JsonProperty]) {
213
+ value = JSON.stringify(value);
214
+ }
215
+ if (typeof value === "string") {
216
+ return pg_1.Client.prototype.escapeLiteral(value);
217
+ }
218
+ if (value instanceof Date) {
219
+ return `'${value.toISOString()}'`;
220
+ }
221
+ if (ArrayBuffer.isView(value)) {
222
+ return `E'\\\\x${value.toString("hex")}'`;
223
+ }
224
+ return super.quoteValue(value);
225
+ }
226
+ indexForeignKeys() {
227
+ return false;
228
+ }
229
+ getDefaultMappedType(type) {
230
+ const normalizedType = this.extractSimpleType(type);
231
+ const map = {
232
+ int2: "smallint",
233
+ smallserial: "smallint",
234
+ int: "integer",
235
+ int4: "integer",
236
+ serial: "integer",
237
+ serial4: "integer",
238
+ int8: "bigint",
239
+ bigserial: "bigint",
240
+ serial8: "bigint",
241
+ numeric: "decimal",
242
+ bool: "boolean",
243
+ real: "float",
244
+ float4: "float",
245
+ float8: "double",
246
+ timestamp: "datetime",
247
+ timestamptz: "datetime",
248
+ bytea: "blob",
249
+ jsonb: "json",
250
+ "character varying": "varchar",
251
+ };
252
+ return super.getDefaultMappedType(map[normalizedType] ?? type);
253
+ }
254
+ supportsSchemas() {
255
+ return true;
256
+ }
257
+ getDefaultSchemaName() {
258
+ return "public";
259
+ }
260
+ /**
261
+ * Returns the default name of index for the given columns
262
+ * cannot go past 64 character length for identifiers in MySQL
263
+ */
264
+ getIndexName(tableName, columns, type) {
265
+ const indexName = super.getIndexName(tableName, columns, type);
266
+ if (indexName.length > 64) {
267
+ return `${indexName.substring(0, 56 - type.length)}_${core_1.Utils.hash(indexName, 5)}_${type}`;
268
+ }
269
+ return indexName;
270
+ }
271
+ getDefaultPrimaryName(tableName, columns) {
272
+ const indexName = `${tableName}_pkey`;
273
+ if (indexName.length > 64) {
274
+ return `${indexName.substring(0, 56 - "primary".length)}_${core_1.Utils.hash(indexName, 5)}_primary`;
275
+ }
276
+ return indexName;
277
+ }
278
+ /**
279
+ * @inheritDoc
280
+ */
281
+ castColumn(prop) {
282
+ switch (prop?.columnTypes?.[0]) {
283
+ case this.getUuidTypeDeclarationSQL({}):
284
+ return "::text";
285
+ case this.getBooleanTypeDeclarationSQL():
286
+ return "::int";
287
+ default:
288
+ return "";
289
+ }
290
+ }
291
+ /**
292
+ * @inheritDoc
293
+ */
294
+ castJsonValue(prop) {
295
+ if (prop?.columnTypes?.[0] === "json") {
296
+ return "::text";
297
+ }
298
+ return "";
299
+ }
300
+ /**
301
+ * @inheritDoc
302
+ */
303
+ parseDate(value) {
304
+ // postgres-date returns `null` for a JS ISO string which has the `T` separator
305
+ if (typeof value === "string" && value.charAt(10) === "T") {
306
+ return new Date(value);
307
+ }
308
+ if (typeof value === "number") {
309
+ return new Date(value);
310
+ }
311
+ return (0, postgres_date_1.default)(value);
312
+ }
313
+ }
314
+ exports.PostgreSqlPlatform = PostgreSqlPlatform;
@@ -0,0 +1,44 @@
1
+ import { type Dictionary } from "@yandjin-mikro-orm/core";
2
+ import { SchemaHelper, type AbstractSqlConnection, type CheckDef, type Column, type DatabaseSchema, type DatabaseTable, type ForeignKey, type IndexDef, type Table, type TableDifference, type Knex } from "@yandjin-mikro-orm/knex";
3
+ export declare class PostgreSqlSchemaHelper extends SchemaHelper {
4
+ static readonly DEFAULT_VALUES: {
5
+ "now()": string[];
6
+ "current_timestamp(?)": string[];
7
+ "('now'::text)::timestamp(?) with time zone": string[];
8
+ "('now'::text)::timestamp(?) without time zone": string[];
9
+ "null::character varying": string[];
10
+ "null::timestamp with time zone": string[];
11
+ "null::timestamp without time zone": string[];
12
+ };
13
+ getSchemaBeginning(charset: string): string;
14
+ getListTablesSQL(): string;
15
+ getNamespaces(connection: AbstractSqlConnection): Promise<string[]>;
16
+ private getIgnoredNamespacesConditionSQL;
17
+ loadInformationSchema(schema: DatabaseSchema, connection: AbstractSqlConnection, tables: Table[], schemas?: string[]): Promise<void>;
18
+ getAllIndexes(connection: AbstractSqlConnection, tables: Table[]): Promise<Dictionary<IndexDef[]>>;
19
+ getAllColumns(connection: AbstractSqlConnection, tables: Table[], nativeEnums?: Dictionary<string[]>): Promise<Dictionary<Column[]>>;
20
+ getAllChecks(connection: AbstractSqlConnection, tables: Table[]): Promise<Dictionary<CheckDef[]>>;
21
+ getAllForeignKeys(connection: AbstractSqlConnection, tables: Table[]): Promise<Dictionary<Dictionary<ForeignKey>>>;
22
+ getNativeEnumDefinitions(connection: AbstractSqlConnection, schemas: string[]): Promise<Dictionary<string[]>>;
23
+ getDropNativeEnumSQL(name: string, schema?: string): string;
24
+ getAlterNativeEnumSQL(name: string, schema?: string, value?: string): string;
25
+ getEnumDefinitions(connection: AbstractSqlConnection, checks: CheckDef[], tableName?: string, schemaName?: string): Promise<Dictionary<string[]>>;
26
+ createTableColumn(table: Knex.TableBuilder, column: Column, fromTable: DatabaseTable, changedProperties?: Set<string>, alter?: boolean): Knex.ColumnBuilder;
27
+ configureColumn(column: Column, col: Knex.ColumnBuilder, knex: Knex, changedProperties?: Set<string>): Knex.ColumnBuilder;
28
+ getPreAlterTable(tableDiff: TableDifference, safe: boolean): string;
29
+ getPostAlterTable(tableDiff: TableDifference, safe: boolean): string;
30
+ getAlterColumnAutoincrement(tableName: string, column: Column, schemaName?: string): string;
31
+ getChangeColumnCommentSQL(tableName: string, to: Column, schemaName?: string): string;
32
+ normalizeDefaultValue(defaultValue: string, length: number): string | number;
33
+ getDatabaseExistsSQL(name: string): string;
34
+ getDatabaseNotExistsError(dbName: string): string;
35
+ getManagementDbName(): string;
36
+ disableForeignKeysSQL(): string;
37
+ enableForeignKeysSQL(): string;
38
+ getRenameIndexSQL(tableName: string, index: IndexDef, oldIndexName: string): string;
39
+ private getIndexesSQL;
40
+ private getChecksSQL;
41
+ getChecks(connection: AbstractSqlConnection, tableName: string, schemaName: string, columns?: Column[]): Promise<CheckDef[]>;
42
+ getColumns(connection: AbstractSqlConnection, tableName: string, schemaName?: string): Promise<Column[]>;
43
+ getIndexes(connection: AbstractSqlConnection, tableName: string, schemaName?: string): Promise<IndexDef[]>;
44
+ }