json-rest-api 1.0.29 → 2.0.0
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 +10 -670
- package/LICENSE-GPL-3.0 +674 -0
- package/LICENSE-MIT +21 -0
- package/README.md +39 -30
- package/docs/API.md +744 -1273
- package/docs/GUIDE/01-getting-started.md +338 -0
- package/docs/GUIDE/02-resources-and-relationships.md +33 -0
- package/docs/GUIDE/03-running-example.md +87 -0
- package/docs/GUIDE/04-creating-and-querying.md +181 -0
- package/docs/GUIDE/05-belongs-to.md +177 -0
- package/docs/GUIDE/06-has-many.md +184 -0
- package/docs/GUIDE/07-polymorphic-relationships.md +191 -0
- package/docs/GUIDE/08-many-to-many.md +184 -0
- package/docs/GUIDE/09-pagination-and-sorting.md +149 -0
- package/docs/GUIDE/10-put-and-patch.md +174 -0
- package/docs/GUIDE/11-relationship-endpoints.md +174 -0
- package/docs/GUIDE/12-field-transformations.md +287 -0
- package/docs/GUIDE/13-hooks-and-lifecycle.md +479 -0
- package/docs/GUIDE/14-custom-resource-methods.md +125 -0
- package/docs/GUIDE/15-query-projections.md +266 -0
- package/docs/GUIDE/{GUIDE_X_Autofiltering.md → 16-autofiltering.md} +77 -15
- package/docs/GUIDE/{GUIDE_X_Row_Policies.md → 17-row-policies.md} +137 -44
- package/docs/GUIDE/18-labels.md +86 -0
- package/docs/GUIDE/19-managed-transactions.md +179 -0
- package/docs/GUIDE/20-transaction-outcomes.md +207 -0
- package/docs/GUIDE/21-schema-and-migrations.md +634 -0
- package/docs/GUIDE/22-version-field-migrations.md +208 -0
- package/docs/GUIDE/23-fastify.md +179 -0
- package/docs/GUIDE/24-cors.md +172 -0
- package/docs/GUIDE/{GUIDE_X_URL_Management.md → 25-url-management.md} +7 -1
- package/docs/GUIDE/26-file-uploads.md +278 -0
- package/docs/GUIDE/27-bulk-operations.md +277 -0
- package/docs/GUIDE/28-socketio.md +325 -0
- package/docs/GUIDE/29-writing-plugins.md +278 -0
- package/docs/GUIDE/30-backend-capabilities.md +100 -0
- package/docs/GUIDE/31-positioning.md +181 -0
- package/docs/GUIDE/{GUIDE_Y_Appendices.md → 32-date-and-time.md} +74 -30
- package/docs/GUIDE/33-migrating-to-v2.md +3827 -0
- package/docs/GUIDE/index.md +51 -59
- package/docs/QUICKSTART.md +120 -287
- package/docs/architecture.md +75 -0
- package/docs/contributing.md +178 -0
- package/index.d.ts +36 -0
- package/index.js +1 -22
- package/lib/enhanced-logger.js +91 -85
- package/lib/error-context.js +445 -5
- package/lib/error-formatter.js +219 -59
- package/lib/knex-transaction.js +64 -0
- package/lib/logger-types.d.ts +22 -0
- package/lib/missing-package.js +4 -0
- package/lib/rest-api-errors.js +103 -8
- package/lib/runtime/json-rest-api.js +172 -0
- package/lib/transaction-types.d.ts +59 -0
- package/package.json +97 -27
- package/plugins/core/bulk-operations-plugin.js +191 -184
- package/plugins/core/connectors/express-plugin.js +148 -219
- package/plugins/core/connectors/fastify-plugin.js +125 -82
- package/plugins/core/connectors/lib/busboy-detector.js +74 -156
- package/plugins/core/connectors/lib/connector-core.js +144 -20
- package/plugins/core/connectors/lib/formidable-detector.js +63 -120
- package/plugins/core/connectors/lib/http-validators.js +77 -0
- package/plugins/core/connectors/lib/multipart-helpers.js +18 -0
- package/plugins/core/connectors/lib/request-helpers.js +10 -1
- package/plugins/core/connectors/lib/transport-http-helpers.js +89 -8
- package/plugins/core/connectors/lib/transport-route-schemas.js +7 -4
- package/plugins/core/file-handling-plugin.js +87 -177
- package/plugins/core/lib/anyapi/anyapi-registry.js +213 -164
- package/plugins/core/lib/anyapi/canonical-link-store.js +507 -0
- package/plugins/core/lib/anyapi/canonical-relationship-reader.js +598 -0
- package/plugins/core/lib/anyapi/schema-utils.js +25 -16
- package/plugins/core/lib/anyapi/utils/descriptor-helpers.js +0 -64
- package/plugins/core/lib/dbIntrospection.js +228 -21
- package/plugins/core/lib/dbTablesOperations.js +409 -92
- package/plugins/core/lib/fractional-positioning.js +12 -48
- package/plugins/core/lib/querying/identifier-query.js +19 -0
- package/plugins/core/lib/querying/include-query-helpers.js +364 -0
- package/plugins/core/lib/querying/include-to-many.js +428 -0
- package/plugins/core/lib/querying/include-to-one.js +579 -0
- package/plugins/core/lib/querying/knex-cross-table-search.js +31 -307
- package/plugins/core/lib/querying/knex-json-api-transformers-querying.js +99 -401
- package/plugins/core/lib/querying/knex-pagination-helpers.js +48 -317
- package/plugins/core/lib/querying/knex-process-includes.js +5 -110
- package/plugins/core/lib/querying/knex-query-helpers-base.js +21 -56
- package/plugins/core/lib/querying/knex-query-helpers.js +298 -448
- package/plugins/core/lib/querying/knex-relationship-includes.js +120 -2138
- package/plugins/core/lib/querying/knex-window-queries.js +62 -253
- package/plugins/core/lib/querying/query-builder-utils.js +44 -4
- package/plugins/core/lib/querying/query-constraint.d.ts +12 -0
- package/plugins/core/lib/querying/query-constraint.js +27 -0
- package/plugins/core/lib/querying/query-field-sort-helpers.js +134 -37
- package/plugins/core/lib/querying/relationship-identifiers.js +208 -0
- package/plugins/core/lib/querying/sort-helpers.js +13 -1
- package/plugins/core/lib/querying/storage-adapter-utils.js +13 -5
- package/plugins/core/lib/querying/url-helpers.js +11 -4
- package/plugins/core/lib/querying-writing/compile-schemas.js +148 -249
- package/plugins/core/lib/querying-writing/connectors-query-parser.js +33 -118
- package/plugins/core/lib/querying-writing/database-capabilities.js +149 -223
- package/plugins/core/lib/querying-writing/database-value-normalizers.js +179 -194
- package/plugins/core/lib/querying-writing/default-data-helpers.js +15 -45
- package/plugins/core/lib/querying-writing/field-selection-types.d.ts +43 -0
- package/plugins/core/lib/querying-writing/field-utils.js +113 -92
- package/plugins/core/lib/querying-writing/knex-constants.d.ts +18 -0
- package/plugins/core/lib/querying-writing/knex-constants.js +2 -26
- package/plugins/core/lib/querying-writing/knex-field-helpers.js +100 -290
- package/plugins/core/lib/querying-writing/knex-json-api-transformers.js +31 -120
- package/plugins/core/lib/querying-writing/query-field-helpers.js +108 -32
- package/plugins/core/lib/querying-writing/query-field-types.d.ts +60 -0
- package/plugins/core/lib/querying-writing/relationship-contracts.js +33 -13
- package/plugins/core/lib/querying-writing/request-contracts.js +93 -38
- package/plugins/core/lib/querying-writing/resource-id-normalization.js +23 -5
- package/plugins/core/lib/querying-writing/response-options.js +35 -0
- package/plugins/core/lib/querying-writing/schema-helpers.js +203 -324
- package/plugins/core/lib/querying-writing/scope-validations.js +92 -290
- package/plugins/core/lib/querying-writing/simplified-helpers.js +113 -712
- package/plugins/core/lib/storage/canonical-data-helpers.js +683 -0
- package/plugins/core/lib/storage/canonical-storage-mapping.js +51 -20
- package/plugins/core/lib/storage/ordinary-data-helpers.js +710 -0
- package/plugins/core/lib/storage/storage-adapter.js +128 -62
- package/plugins/core/lib/storage/storage-mapping.js +78 -28
- package/plugins/core/lib/storage/storage-types.d.ts +502 -0
- package/plugins/core/lib/writing/many-to-many-manipulations.js +114 -284
- package/plugins/core/lib/writing/relationship-processor.js +94 -158
- package/plugins/core/lib/writing/resource-version.js +172 -0
- package/plugins/core/lib/writing/reverse-relationship-manipulations.js +110 -0
- package/plugins/core/rest-api-anyapi-knex-plugin.js +116 -2485
- package/plugins/core/rest-api-autofilter-plugin.js +17 -19
- package/plugins/core/rest-api-cors-plugin.js +52 -205
- package/plugins/core/rest-api-knex-plugin.js +45 -1077
- package/plugins/core/rest-api-label-plugin.js +25 -38
- package/plugins/core/rest-api-plugin-hooks/register-relationship-routes.js +5 -5
- package/plugins/core/rest-api-plugin-hooks/register-scope-routes.js +9 -6
- package/plugins/core/rest-api-plugin-hooks/turn-scope-init-into-vars.js +7 -26
- package/plugins/core/rest-api-plugin-hooks/validate-include-configurations.js +20 -26
- package/plugins/core/rest-api-plugin-methods/add-route.js +4 -6
- package/plugins/core/rest-api-plugin-methods/apply-query-filters.js +42 -13
- package/plugins/core/rest-api-plugin-methods/check-permissions.js +11 -5
- package/plugins/core/rest-api-plugin-methods/common.js +291 -395
- package/plugins/core/rest-api-plugin-methods/delete-relationship.js +49 -47
- package/plugins/core/rest-api-plugin-methods/delete.js +31 -25
- package/plugins/core/rest-api-plugin-methods/enrich-attributes.js +108 -148
- package/plugins/core/rest-api-plugin-methods/get-related.js +113 -305
- package/plugins/core/rest-api-plugin-methods/get-relationship.js +25 -18
- package/plugins/core/rest-api-plugin-methods/get.js +36 -68
- package/plugins/core/rest-api-plugin-methods/lifecycle-types.d.ts +225 -0
- package/plugins/core/rest-api-plugin-methods/patch-relationship.js +28 -25
- package/plugins/core/rest-api-plugin-methods/patch.js +46 -99
- package/plugins/core/rest-api-plugin-methods/post-relationship.js +49 -53
- package/plugins/core/rest-api-plugin-methods/post.js +51 -51
- package/plugins/core/rest-api-plugin-methods/put.js +69 -148
- package/plugins/core/rest-api-plugin-methods/query.js +37 -81
- package/plugins/core/rest-api-plugin-methods/release.js +2 -1
- package/plugins/core/rest-api-plugin.js +32 -46
- package/plugins/core/rest-api-positioning-plugin.js +183 -628
- package/plugins/core/rest-api-query-projections-plugin.js +19 -102
- package/plugins/core/rest-api-row-policy-plugin.js +3 -3
- package/plugins/core/socketio-plugin.js +364 -344
- package/plugins/storage/local-storage.js +40 -36
- package/types/autofilter.d.ts +57 -0
- package/types/bulk-methods.d.ts +63 -0
- package/types/errors.d.ts +118 -0
- package/types/fastify-options.d.ts +19 -0
- package/types/file-detectors.d.ts +33 -0
- package/types/file-storage.d.ts +48 -0
- package/types/hook-context.d.ts +180 -0
- package/types/plugin-options.d.ts +53 -0
- package/types/relationship-methods.d.ts +74 -0
- package/types/representations.d.ts +50 -0
- package/types/resource-methods.d.ts +95 -0
- package/types/resource-schema.d.ts +157 -0
- package/types/row-policy.d.ts +31 -0
- package/types/runtime.d.ts +132 -0
- package/types/transactions.d.ts +21 -0
- package/.claude/agents/library-guide-expert.md +0 -30
- package/.claude/agents/rest-api-internals-expert.md +0 -54
- package/.claude/settings.local.json +0 -70
- package/AGENTS.md +0 -34
- package/CLAUDE.md +0 -160
- package/CRUSH.md +0 -55
- package/JSKIT_BACKEND_MIGRATION_TRACKER.txt +0 -180
- package/SINGLE_VALIDATION_CONTRACT_TODO.txt +0 -172
- package/TODO.todo +0 -13
- package/connectors_ideas/fastify.js +0 -217
- package/connectors_ideas/koa-plugin.js +0 -112
- package/docs/.bundle/config +0 -2
- package/docs/COMPARISON.md +0 -433
- package/docs/GUIDE/GUIDE_1_Initial_Setup.md +0 -1057
- package/docs/GUIDE/GUIDE_2_1_The_Starting_Point.md +0 -88
- package/docs/GUIDE/GUIDE_2_2_Manipulating_And_Searching_Tables.md +0 -808
- package/docs/GUIDE/GUIDE_2_3_BelongsTo_Relationships.md +0 -491
- package/docs/GUIDE/GUIDE_2_4_HasMany_Records.md +0 -398
- package/docs/GUIDE/GUIDE_2_5_HasMany_Polymorphic.md +0 -898
- package/docs/GUIDE/GUIDE_2_6_Many_To_Many.md +0 -712
- package/docs/GUIDE/GUIDE_2_7_Pagination_And_Ordering.md +0 -1247
- package/docs/GUIDE/GUIDE_2_8_Effects_of_PUT_and_PATCH.md +0 -748
- package/docs/GUIDE/GUIDE_2_9_Relationships_Urls.md +0 -517
- package/docs/GUIDE/GUIDE_2_Data_And_Relations.md +0 -66
- package/docs/GUIDE/GUIDE_3_Field_Transformations.md +0 -1252
- package/docs/GUIDE/GUIDE_5_Non-Db_Resources.md +0 -1107
- package/docs/GUIDE/GUIDE_6_Positioning.md +0 -692
- package/docs/GUIDE/GUIDE_7_Hooks_Data_Management_And_Plugins.md +0 -1491
- package/docs/GUIDE/GUIDE_X_Bulk_Operations.md +0 -732
- package/docs/GUIDE/GUIDE_X_Cors.md +0 -1957
- package/docs/GUIDE/GUIDE_X_Fastify.md +0 -78
- package/docs/GUIDE/GUIDE_X_File_Uploads.md +0 -729
- package/docs/GUIDE/GUIDE_X_Knex_Schema_And_Migrations.md +0 -370
- package/docs/GUIDE/GUIDE_X_Query_Projections.md +0 -159
- package/docs/GUIDE/GUIDE_X_SocketIO.md +0 -1040
- package/docs/GUIDE/GUIDE_X_Writing_Plugins.md +0 -201
- package/docs/Gemfile +0 -6
- package/docs/Gemfile.lock +0 -308
- package/docs/ONBOARDING.md +0 -315
- package/docs/_config.yml +0 -36
- package/docs/_layouts/default.html +0 -123
- package/docs/apple-touch-icon.svg +0 -4
- package/docs/assets/css/style.scss +0 -392
- package/docs/favicon.svg +0 -4
- package/docs/index.md +0 -164
- package/docs/mini-guides/file-uploads-complete.md +0 -161
- package/eslint.config.js +0 -13
- package/examples/url-override-example.js +0 -137
- package/fixing_plan.md +0 -112
- package/plugins/core/lib/anyapi/query/anyapi-query-adapter.js +0 -657
- package/plugins/core/lib/querying-writing/return-record-settings.js +0 -47
- package/plugins/core/lib/writing/knex-json-api-transformers-writing.js +0 -110
- package/plugins/storage/s3-storage.js +0 -93
- package/quickTest.js +0 -136
- package/scripts/debug-anyapi-review-filter.mjs +0 -63
- package/scripts/inspect-anyapi-descriptor-country.mjs +0 -19
- package/scripts/inspect-anyapi-descriptor.mjs +0 -19
- package/scripts/run-docs.js +0 -133
- package/test-debug.js +0 -59
- package/tests/README.md +0 -202
- package/tests/TEST_TEMPLATE.test.js +0 -178
- package/tests/anyapi-basic.test.js +0 -105
- package/tests/anyapi-cursor-pagination.test.js +0 -148
- package/tests/anyapi-custom-idproperty.test.js +0 -163
- package/tests/autofilter.test.js +0 -463
- package/tests/bulk-operations.test.js +0 -657
- package/tests/computed-fields.test.js +0 -586
- package/tests/cors.test.js +0 -834
- package/tests/curl.test.js +0 -467
- package/tests/custom-id-mysql-returning-fallback.test.js +0 -128
- package/tests/custom-id-simplified-post.test.js +0 -75
- package/tests/custom-idproperty-relationships.test.js +0 -932
- package/tests/db-introspection.test.js +0 -521
- package/tests/db-table-operations.test.js +0 -798
- package/tests/fastify-plugin.test.js +0 -184
- package/tests/field-getters.test.js +0 -370
- package/tests/field-setters.test.js +0 -306
- package/tests/file-handling.test.js +0 -155
- package/tests/fixtures/api-configs.js +0 -2566
- package/tests/full-jsonapi-belongsto-linkage.test.js +0 -150
- package/tests/helpers/fake-fastify.js +0 -99
- package/tests/helpers/storage-mode.js +0 -65
- package/tests/helpers/test-utils.js +0 -203
- package/tests/http-connectors-parity.test.js +0 -395
- package/tests/id-normalization.test.js +0 -444
- package/tests/include-depth-validation.test.js +0 -331
- package/tests/includes.test.js +0 -427
- package/tests/local-storage.test.js +0 -96
- package/tests/logical-id-write-validation.test.js +0 -151
- package/tests/nested-includes.test.js +0 -617
- package/tests/pagination-boundaries.test.js +0 -154
- package/tests/pagination-contract.test.js +0 -122
- package/tests/pagination-cursor-multifield.test.js +0 -641
- package/tests/pagination-enhanced.test.js +0 -563
- package/tests/polymorphic-relationships.test.js +0 -347
- package/tests/polymorphic-simple.test.js +0 -148
- package/tests/positioning-advanced.test.js +0 -692
- package/tests/positioning-extended.test.js +0 -915
- package/tests/positioning-multifilter.test.js +0 -699
- package/tests/positioning.test.js +0 -560
- package/tests/post-commit-hooks.test.js +0 -120
- package/tests/projected-fields.test.js +0 -319
- package/tests/public-exports.test.js +0 -15
- package/tests/put-create-parity.test.js +0 -216
- package/tests/queries.test.js +0 -521
- package/tests/query-limits.test.js +0 -584
- package/tests/relationship-endpoints.test.js +0 -620
- package/tests/relationship-include-storage-adapter.test.js +0 -56
- package/tests/relationships.test.js +0 -681
- package/tests/rest-api.test.js +0 -337
- package/tests/return-record-settings.test.js +0 -184
- package/tests/row-policy.test.js +0 -489
- package/tests/s3-storage.test.js +0 -38
- package/tests/searchschema-knex-behavior.test.js +0 -187
- package/tests/searchschema-merge.test.js +0 -151
- package/tests/socketio.test.js +0 -860
- package/tests/storage-mapping.test.js +0 -362
- package/tests/temporal-boundaries.test.js +0 -208
- package/tests/test-development-guide.md +0 -370
- package/tests/virtual-fields.test.js +0 -404
|
@@ -1,798 +0,0 @@
|
|
|
1
|
-
import { describe, it, before, after, beforeEach, afterEach } from 'node:test'
|
|
2
|
-
import assert from 'node:assert/strict'
|
|
3
|
-
import knexLib from 'knex'
|
|
4
|
-
import { Api } from 'hooked-api'
|
|
5
|
-
import { RestApiPlugin, RestApiKnexPlugin } from '../index.js'
|
|
6
|
-
import {
|
|
7
|
-
createKnexTable,
|
|
8
|
-
addKnexFields,
|
|
9
|
-
alterKnexFields,
|
|
10
|
-
generateKnexMigration,
|
|
11
|
-
generateKnexMigrationDiff
|
|
12
|
-
} from '../plugins/core/lib/dbTablesOperations.js'
|
|
13
|
-
import { introspectKnexTableSnapshot } from '../plugins/core/lib/dbIntrospection.js'
|
|
14
|
-
|
|
15
|
-
function makeSchemaInfo (tableName, idProperty = 'id') {
|
|
16
|
-
return { tableName, idProperty }
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
function makeTableSchema (structure, metadata = {}) {
|
|
20
|
-
return { structure, ...metadata }
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
let db
|
|
24
|
-
|
|
25
|
-
describe('dbTablesOperations.createKnexTable', () => {
|
|
26
|
-
beforeEach(() => {
|
|
27
|
-
db = knexLib({
|
|
28
|
-
client: 'better-sqlite3',
|
|
29
|
-
connection: {
|
|
30
|
-
filename: ':memory:'
|
|
31
|
-
},
|
|
32
|
-
useNullAsDefault: true
|
|
33
|
-
})
|
|
34
|
-
})
|
|
35
|
-
|
|
36
|
-
afterEach(async () => {
|
|
37
|
-
await db.destroy()
|
|
38
|
-
})
|
|
39
|
-
|
|
40
|
-
it('creates a simple table with string fields', async () => {
|
|
41
|
-
const schema = makeTableSchema({
|
|
42
|
-
name: { type: 'string', required: true, maxLength: 100 },
|
|
43
|
-
email: { type: 'string', unique: true },
|
|
44
|
-
bio: { type: 'string', nullable: true }
|
|
45
|
-
})
|
|
46
|
-
|
|
47
|
-
await createKnexTable(db, makeSchemaInfo('users'), schema)
|
|
48
|
-
|
|
49
|
-
const exists = await db.schema.hasTable('users')
|
|
50
|
-
assert.equal(exists, true)
|
|
51
|
-
|
|
52
|
-
const info = await db('users').columnInfo()
|
|
53
|
-
assert.ok(info.id)
|
|
54
|
-
assert.ok(info.name)
|
|
55
|
-
assert.ok(info.email)
|
|
56
|
-
assert.ok(info.bio)
|
|
57
|
-
|
|
58
|
-
await db('users').insert({
|
|
59
|
-
name: 'Test User',
|
|
60
|
-
email: 'test@example.com',
|
|
61
|
-
bio: null
|
|
62
|
-
})
|
|
63
|
-
|
|
64
|
-
const users = await db('users').select()
|
|
65
|
-
assert.equal(users.length, 1)
|
|
66
|
-
assert.equal(users[0].name, 'Test User')
|
|
67
|
-
})
|
|
68
|
-
|
|
69
|
-
it('handles number fields with precision and defaults', async () => {
|
|
70
|
-
const schema = makeTableSchema({
|
|
71
|
-
price: { type: 'number', precision: 10, scale: 2 },
|
|
72
|
-
quantity: { type: 'number', defaultTo: 0 },
|
|
73
|
-
rating: { type: 'number', nullable: true }
|
|
74
|
-
})
|
|
75
|
-
|
|
76
|
-
await createKnexTable(db, makeSchemaInfo('products'), schema)
|
|
77
|
-
|
|
78
|
-
await db('products').insert({
|
|
79
|
-
price: 99.99,
|
|
80
|
-
rating: 4.5
|
|
81
|
-
})
|
|
82
|
-
|
|
83
|
-
const products = await db('products').select()
|
|
84
|
-
assert.equal(products[0].price, 99.99)
|
|
85
|
-
assert.equal(products[0].quantity, 0)
|
|
86
|
-
assert.equal(products[0].rating, 4.5)
|
|
87
|
-
})
|
|
88
|
-
|
|
89
|
-
it('adds timestamps when requested', async () => {
|
|
90
|
-
const schema = makeTableSchema({
|
|
91
|
-
title: { type: 'string' }
|
|
92
|
-
})
|
|
93
|
-
|
|
94
|
-
await createKnexTable(db, makeSchemaInfo('posts'), schema, {
|
|
95
|
-
timestamps: true
|
|
96
|
-
})
|
|
97
|
-
|
|
98
|
-
const info = await db('posts').columnInfo()
|
|
99
|
-
assert.ok(info.created_at)
|
|
100
|
-
assert.ok(info.updated_at)
|
|
101
|
-
})
|
|
102
|
-
|
|
103
|
-
it('handles foreign key references', async () => {
|
|
104
|
-
const userSchema = makeTableSchema({
|
|
105
|
-
username: { type: 'string', unique: true }
|
|
106
|
-
})
|
|
107
|
-
await createKnexTable(db, makeSchemaInfo('users'), userSchema)
|
|
108
|
-
|
|
109
|
-
const postSchema = makeTableSchema({
|
|
110
|
-
title: { type: 'string', required: true },
|
|
111
|
-
userId: {
|
|
112
|
-
type: 'id',
|
|
113
|
-
required: true,
|
|
114
|
-
references: { table: 'users', onDelete: 'CASCADE' }
|
|
115
|
-
}
|
|
116
|
-
})
|
|
117
|
-
await createKnexTable(db, makeSchemaInfo('posts'), postSchema)
|
|
118
|
-
|
|
119
|
-
await db('users').insert({ username: 'testuser' })
|
|
120
|
-
const user = await db('users').where('username', 'testuser').first()
|
|
121
|
-
await db('posts').insert({ title: 'Test Post', user_id: user.id })
|
|
122
|
-
|
|
123
|
-
const posts = await db('posts')
|
|
124
|
-
.join('users', 'posts.user_id', 'users.id')
|
|
125
|
-
.select('posts.title', 'users.username')
|
|
126
|
-
|
|
127
|
-
assert.equal(posts.length, 1)
|
|
128
|
-
assert.equal(posts[0].title, 'Test Post')
|
|
129
|
-
assert.equal(posts[0].username, 'testuser')
|
|
130
|
-
})
|
|
131
|
-
|
|
132
|
-
it('respects a primary key defined in the schema', async () => {
|
|
133
|
-
const schema = makeTableSchema({
|
|
134
|
-
isbn: { type: 'string', primary: true, maxLength: 13 },
|
|
135
|
-
title: { type: 'string', required: true }
|
|
136
|
-
})
|
|
137
|
-
|
|
138
|
-
await createKnexTable(db, makeSchemaInfo('books'), schema, {
|
|
139
|
-
autoIncrement: false
|
|
140
|
-
})
|
|
141
|
-
|
|
142
|
-
const info = await db('books').columnInfo()
|
|
143
|
-
assert.ok(!info.id)
|
|
144
|
-
assert.ok(info.isbn)
|
|
145
|
-
|
|
146
|
-
await db('books').insert({
|
|
147
|
-
isbn: '9781234567890',
|
|
148
|
-
title: 'Test Book'
|
|
149
|
-
})
|
|
150
|
-
|
|
151
|
-
const books = await db('books').select()
|
|
152
|
-
assert.equal(books[0].isbn, '9781234567890')
|
|
153
|
-
})
|
|
154
|
-
|
|
155
|
-
it('enforces unique constraints', async () => {
|
|
156
|
-
const schema = makeTableSchema({
|
|
157
|
-
email: { type: 'string', unique: true },
|
|
158
|
-
username: { type: 'string', unique: true }
|
|
159
|
-
})
|
|
160
|
-
|
|
161
|
-
await createKnexTable(db, makeSchemaInfo('accounts'), schema)
|
|
162
|
-
|
|
163
|
-
await db('accounts').insert({
|
|
164
|
-
email: 'test@example.com',
|
|
165
|
-
username: 'testuser'
|
|
166
|
-
})
|
|
167
|
-
|
|
168
|
-
await assert.rejects(async () => {
|
|
169
|
-
await db('accounts').insert({
|
|
170
|
-
email: 'test@example.com',
|
|
171
|
-
username: 'otheruser'
|
|
172
|
-
})
|
|
173
|
-
})
|
|
174
|
-
})
|
|
175
|
-
|
|
176
|
-
it('defaults storage columns to snake_case and keeps per-field overrides', async () => {
|
|
177
|
-
const schema = makeTableSchema({
|
|
178
|
-
displayName: { type: 'string', required: true },
|
|
179
|
-
lastSeenAt: { type: 'dateTime', temporalPrecision: 3, defaultTo: () => new Date().toISOString() },
|
|
180
|
-
observedAtMs: { type: 'epochMilliseconds' },
|
|
181
|
-
observedAtSeconds: { type: 'epochSeconds' },
|
|
182
|
-
externalRef: { type: 'string', storage: { column: 'legacy_ref' } }
|
|
183
|
-
})
|
|
184
|
-
|
|
185
|
-
await createKnexTable(db, makeSchemaInfo('mapped_profiles'), schema)
|
|
186
|
-
|
|
187
|
-
const info = await db('mapped_profiles').columnInfo()
|
|
188
|
-
assert.ok(info.id)
|
|
189
|
-
assert.ok(info.display_name)
|
|
190
|
-
assert.ok(info.last_seen_at)
|
|
191
|
-
assert.equal(info.last_seen_at.defaultValue, null)
|
|
192
|
-
assert.ok(info.observed_at_ms)
|
|
193
|
-
assert.ok(info.observed_at_seconds)
|
|
194
|
-
assert.ok(info.legacy_ref)
|
|
195
|
-
assert.equal(info.displayName, undefined)
|
|
196
|
-
assert.equal(info.external_ref, undefined)
|
|
197
|
-
})
|
|
198
|
-
|
|
199
|
-
it('supports logical id fields mapped to custom storage columns', async () => {
|
|
200
|
-
const schema = makeTableSchema({
|
|
201
|
-
id: { type: 'id', primary: true, storage: { column: 'book_id' } },
|
|
202
|
-
title: { type: 'string', required: true }
|
|
203
|
-
})
|
|
204
|
-
|
|
205
|
-
await createKnexTable(db, makeSchemaInfo('books', 'book_id'), schema)
|
|
206
|
-
|
|
207
|
-
const info = await db('books').columnInfo()
|
|
208
|
-
assert.ok(info.book_id)
|
|
209
|
-
assert.equal(info.id, undefined)
|
|
210
|
-
|
|
211
|
-
await db('books').insert({
|
|
212
|
-
book_id: 101,
|
|
213
|
-
title: 'Mapped ID Book'
|
|
214
|
-
})
|
|
215
|
-
|
|
216
|
-
const books = await db('books').select()
|
|
217
|
-
assert.equal(books.length, 1)
|
|
218
|
-
assert.equal(books[0].book_id, 101)
|
|
219
|
-
})
|
|
220
|
-
|
|
221
|
-
it('supports named composite indexes, foreign keys, checks, and enum columns', async () => {
|
|
222
|
-
await db.raw('PRAGMA foreign_keys = ON')
|
|
223
|
-
await db.raw(`
|
|
224
|
-
CREATE TABLE workspace_users (
|
|
225
|
-
workspace_id INTEGER NOT NULL,
|
|
226
|
-
user_id INTEGER NOT NULL,
|
|
227
|
-
PRIMARY KEY (workspace_id, user_id)
|
|
228
|
-
)
|
|
229
|
-
`)
|
|
230
|
-
|
|
231
|
-
const schema = makeTableSchema({
|
|
232
|
-
workspaceId: { type: 'id', required: true },
|
|
233
|
-
userId: { type: 'id', required: true },
|
|
234
|
-
role: { type: 'string', enum: ['owner', 'member'], required: true, defaultTo: 'member' },
|
|
235
|
-
noteCount: { type: 'number', defaultTo: 0 }
|
|
236
|
-
}, {
|
|
237
|
-
indexes: [
|
|
238
|
-
{
|
|
239
|
-
name: 'uq_memberships_workspace_user',
|
|
240
|
-
unique: true,
|
|
241
|
-
columns: ['workspaceId', 'userId']
|
|
242
|
-
}
|
|
243
|
-
],
|
|
244
|
-
foreignKeys: [
|
|
245
|
-
{
|
|
246
|
-
name: 'fk_memberships_workspace_user',
|
|
247
|
-
columns: ['workspaceId', 'userId'],
|
|
248
|
-
referencedTableName: 'workspace_users',
|
|
249
|
-
referencedColumns: ['workspace_id', 'user_id'],
|
|
250
|
-
deleteRule: 'CASCADE',
|
|
251
|
-
updateRule: 'RESTRICT'
|
|
252
|
-
}
|
|
253
|
-
],
|
|
254
|
-
checkConstraints: [
|
|
255
|
-
{
|
|
256
|
-
name: 'chk_memberships_note_count_non_negative',
|
|
257
|
-
clause: 'note_count >= 0'
|
|
258
|
-
}
|
|
259
|
-
]
|
|
260
|
-
})
|
|
261
|
-
|
|
262
|
-
await createKnexTable(db, makeSchemaInfo('memberships'), schema)
|
|
263
|
-
|
|
264
|
-
const snapshot = await introspectKnexTableSnapshot(db, {
|
|
265
|
-
tableName: 'memberships',
|
|
266
|
-
idColumn: 'id'
|
|
267
|
-
})
|
|
268
|
-
|
|
269
|
-
const membershipIndex = snapshot.indexes.find((index) => index.name === 'uq_memberships_workspace_user')
|
|
270
|
-
assert.ok(membershipIndex)
|
|
271
|
-
assert.equal(membershipIndex.unique, true)
|
|
272
|
-
assert.deepEqual(membershipIndex.columns, ['workspace_id', 'user_id'])
|
|
273
|
-
|
|
274
|
-
const membershipForeignKey = snapshot.foreignKeys.find((foreignKey) => foreignKey.name === 'fk_memberships_workspace_user')
|
|
275
|
-
assert.ok(membershipForeignKey)
|
|
276
|
-
assert.equal(membershipForeignKey.referencedTableName, 'workspace_users')
|
|
277
|
-
assert.equal(membershipForeignKey.deleteRule, 'CASCADE')
|
|
278
|
-
assert.equal(membershipForeignKey.updateRule, 'RESTRICT')
|
|
279
|
-
assert.deepEqual(
|
|
280
|
-
membershipForeignKey.columns.map((entry) => [entry.name, entry.referencedName]),
|
|
281
|
-
[['workspace_id', 'workspace_id'], ['user_id', 'user_id']]
|
|
282
|
-
)
|
|
283
|
-
|
|
284
|
-
const membershipCheck = snapshot.checkConstraints.find((constraint) => constraint.name === 'chk_memberships_note_count_non_negative')
|
|
285
|
-
assert.ok(membershipCheck)
|
|
286
|
-
assert.equal(membershipCheck.clause, 'note_count >= 0')
|
|
287
|
-
|
|
288
|
-
const roleColumn = snapshot.columns.find((column) => column.name === 'role')
|
|
289
|
-
assert.ok(roleColumn)
|
|
290
|
-
assert.deepEqual(roleColumn.enumValues, ['owner', 'member'])
|
|
291
|
-
})
|
|
292
|
-
})
|
|
293
|
-
|
|
294
|
-
describe('dbTablesOperations.generateKnexMigration', () => {
|
|
295
|
-
beforeEach(() => {
|
|
296
|
-
db = knexLib({
|
|
297
|
-
client: 'better-sqlite3',
|
|
298
|
-
connection: {
|
|
299
|
-
filename: ':memory:'
|
|
300
|
-
},
|
|
301
|
-
useNullAsDefault: true
|
|
302
|
-
})
|
|
303
|
-
})
|
|
304
|
-
|
|
305
|
-
afterEach(async () => {
|
|
306
|
-
await db.destroy()
|
|
307
|
-
})
|
|
308
|
-
|
|
309
|
-
it('generates executable migrations', async () => {
|
|
310
|
-
const schema = makeTableSchema({
|
|
311
|
-
name: { type: 'string', required: true },
|
|
312
|
-
age: { type: 'number', min: 0 },
|
|
313
|
-
email: { type: 'string', unique: true }
|
|
314
|
-
})
|
|
315
|
-
|
|
316
|
-
const migration = generateKnexMigration('users', schema)
|
|
317
|
-
const migrationModule = {}
|
|
318
|
-
const migrationCode = migration
|
|
319
|
-
.replace(/exports\.up/g, 'migrationModule.up')
|
|
320
|
-
.replace(/exports\.down/g, 'migrationModule.down')
|
|
321
|
-
|
|
322
|
-
new Function('migrationModule', migrationCode)(migrationModule)
|
|
323
|
-
|
|
324
|
-
await migrationModule.up(db)
|
|
325
|
-
|
|
326
|
-
const exists = await db.schema.hasTable('users')
|
|
327
|
-
assert.equal(exists, true)
|
|
328
|
-
|
|
329
|
-
await db('users').insert({
|
|
330
|
-
name: 'Test User',
|
|
331
|
-
age: 25,
|
|
332
|
-
email: 'test@example.com'
|
|
333
|
-
})
|
|
334
|
-
|
|
335
|
-
await migrationModule.down(db)
|
|
336
|
-
|
|
337
|
-
const existsAfter = await db.schema.hasTable('users')
|
|
338
|
-
assert.equal(existsAfter, false)
|
|
339
|
-
})
|
|
340
|
-
|
|
341
|
-
it('includes the expected schema features in generated migrations', () => {
|
|
342
|
-
const schema = makeTableSchema({
|
|
343
|
-
id: { type: 'id', primary: true },
|
|
344
|
-
title: { type: 'string', required: true, maxLength: 200 },
|
|
345
|
-
price: { type: 'number', precision: 10, scale: 2 },
|
|
346
|
-
inStock: { type: 'boolean', defaultTo: true },
|
|
347
|
-
categoryId: {
|
|
348
|
-
type: 'id',
|
|
349
|
-
nullable: true,
|
|
350
|
-
references: { table: 'categories', onDelete: 'SET NULL' }
|
|
351
|
-
},
|
|
352
|
-
tags: { type: 'array', defaultTo: [] }
|
|
353
|
-
})
|
|
354
|
-
|
|
355
|
-
const migration = generateKnexMigration('products', schema, {
|
|
356
|
-
timestamps: true
|
|
357
|
-
})
|
|
358
|
-
|
|
359
|
-
assert.ok(migration.includes("table.integer('id').unsigned().primary()"))
|
|
360
|
-
assert.ok(migration.includes("table.string('title', 200).notNullable()"))
|
|
361
|
-
assert.ok(migration.includes("table.decimal('price', 10, 2)"))
|
|
362
|
-
assert.ok(migration.includes(".defaultTo(true)"))
|
|
363
|
-
assert.ok(migration.includes("table.foreign(['category_id'], 'products_category_id_foreign').references(['id']).inTable('categories').onDelete('SET NULL')"))
|
|
364
|
-
assert.ok(migration.includes('table.timestamps(true, true)'))
|
|
365
|
-
})
|
|
366
|
-
|
|
367
|
-
it('uses default snake_case columns in generated migrations and keeps per-field overrides', () => {
|
|
368
|
-
const schema = makeTableSchema({
|
|
369
|
-
displayName: { type: 'string', required: true },
|
|
370
|
-
loginCount: { type: 'number', defaultTo: 0 },
|
|
371
|
-
createdAt: { type: 'dateTime', temporalPrecision: 3, defaultTo: () => new Date().toISOString() },
|
|
372
|
-
observedAtMs: { type: 'epochMilliseconds' },
|
|
373
|
-
observedAtSeconds: { type: 'epochSeconds' },
|
|
374
|
-
externalRef: { type: 'string', storage: { column: 'legacy_ref' } }
|
|
375
|
-
})
|
|
376
|
-
|
|
377
|
-
const migration = generateKnexMigration('mapped_profiles', schema)
|
|
378
|
-
|
|
379
|
-
assert.ok(migration.includes("table.string('display_name').notNullable()"))
|
|
380
|
-
assert.ok(migration.includes("table.float('login_count').defaultTo(0)"))
|
|
381
|
-
assert.ok(migration.includes("table.datetime('created_at', { precision: 3 })"))
|
|
382
|
-
assert.equal(migration.includes("table.datetime('created_at', { precision: 3 }).defaultTo"), false)
|
|
383
|
-
assert.ok(migration.includes("table.bigInteger('observed_at_ms')"))
|
|
384
|
-
assert.ok(migration.includes("table.bigInteger('observed_at_seconds')"))
|
|
385
|
-
assert.ok(migration.includes("table.string('legacy_ref')"))
|
|
386
|
-
assert.ok(!migration.includes("table.string('displayName')"))
|
|
387
|
-
})
|
|
388
|
-
|
|
389
|
-
it('supports mapped logical id fields in generated migrations', () => {
|
|
390
|
-
const schema = makeTableSchema({
|
|
391
|
-
id: { type: 'id', primary: true, storage: { column: 'book_id' } },
|
|
392
|
-
title: { type: 'string', required: true }
|
|
393
|
-
})
|
|
394
|
-
|
|
395
|
-
const migration = generateKnexMigration('books', schema)
|
|
396
|
-
|
|
397
|
-
assert.ok(migration.includes("table.integer('book_id').unsigned().primary()"))
|
|
398
|
-
assert.ok(migration.includes("table.string('title').notNullable()"))
|
|
399
|
-
assert.equal((migration.match(/book_id/g) || []).length, 1)
|
|
400
|
-
})
|
|
401
|
-
|
|
402
|
-
it('includes named composite indexes, foreign keys, checks, enum, and set columns in generated migrations', () => {
|
|
403
|
-
const schema = makeTableSchema({
|
|
404
|
-
workspaceId: { type: 'id', required: true },
|
|
405
|
-
userId: { type: 'id', required: true },
|
|
406
|
-
role: { type: 'string', enum: ['owner', 'member'], required: true, defaultTo: 'member' },
|
|
407
|
-
flags: { type: 'string', setValues: ['featured', 'archived'] },
|
|
408
|
-
noteCount: { type: 'number', defaultTo: 0 }
|
|
409
|
-
}, {
|
|
410
|
-
indexes: [
|
|
411
|
-
{
|
|
412
|
-
name: 'uq_memberships_workspace_user',
|
|
413
|
-
unique: true,
|
|
414
|
-
columns: ['workspaceId', 'userId']
|
|
415
|
-
}
|
|
416
|
-
],
|
|
417
|
-
foreignKeys: [
|
|
418
|
-
{
|
|
419
|
-
name: 'fk_memberships_workspace_user',
|
|
420
|
-
columns: ['workspaceId', 'userId'],
|
|
421
|
-
referencedTableName: 'workspace_users',
|
|
422
|
-
referencedColumns: ['workspace_id', 'user_id'],
|
|
423
|
-
deleteRule: 'CASCADE',
|
|
424
|
-
updateRule: 'RESTRICT'
|
|
425
|
-
}
|
|
426
|
-
],
|
|
427
|
-
checkConstraints: [
|
|
428
|
-
{
|
|
429
|
-
name: 'chk_memberships_note_count_non_negative',
|
|
430
|
-
clause: 'note_count >= 0'
|
|
431
|
-
}
|
|
432
|
-
]
|
|
433
|
-
})
|
|
434
|
-
|
|
435
|
-
const migration = generateKnexMigration('memberships', schema, {
|
|
436
|
-
dialect: 'mysql2'
|
|
437
|
-
})
|
|
438
|
-
|
|
439
|
-
assert.ok(migration.includes("table.enu('role', ['owner', 'member']).notNullable().defaultTo('member')"))
|
|
440
|
-
assert.ok(migration.includes("table.specificType('flags', 'set(\\'featured\\', \\'archived\\')')"))
|
|
441
|
-
assert.ok(migration.includes("table.unique(['workspace_id', 'user_id'], 'uq_memberships_workspace_user')"))
|
|
442
|
-
assert.ok(migration.includes("table.foreign(['workspace_id', 'user_id'], 'fk_memberships_workspace_user').references(['workspace_id', 'user_id']).inTable('workspace_users').onDelete('CASCADE').onUpdate('RESTRICT')"))
|
|
443
|
-
assert.ok(migration.includes("table.check('note_count >= 0', [], 'chk_memberships_note_count_non_negative')"))
|
|
444
|
-
})
|
|
445
|
-
|
|
446
|
-
it('includes indexType for non-unique indexes in generated migrations', () => {
|
|
447
|
-
const schema = makeTableSchema({
|
|
448
|
-
body: { type: 'string' }
|
|
449
|
-
}, {
|
|
450
|
-
indexes: [
|
|
451
|
-
{
|
|
452
|
-
name: 'idx_articles_body_fulltext',
|
|
453
|
-
columns: ['body'],
|
|
454
|
-
indexType: 'FULLTEXT'
|
|
455
|
-
}
|
|
456
|
-
]
|
|
457
|
-
})
|
|
458
|
-
|
|
459
|
-
const migration = generateKnexMigration('articles', schema)
|
|
460
|
-
|
|
461
|
-
assert.ok(migration.includes("table.index(['body'], 'idx_articles_body_fulltext', { \"indexType\": 'FULLTEXT' })"))
|
|
462
|
-
})
|
|
463
|
-
|
|
464
|
-
it('rejects indexType on unique index metadata', () => {
|
|
465
|
-
const schema = makeTableSchema({
|
|
466
|
-
email: { type: 'string' }
|
|
467
|
-
}, {
|
|
468
|
-
indexes: [
|
|
469
|
-
{
|
|
470
|
-
name: 'uq_accounts_email',
|
|
471
|
-
unique: true,
|
|
472
|
-
columns: ['email'],
|
|
473
|
-
indexType: 'BTREE'
|
|
474
|
-
}
|
|
475
|
-
]
|
|
476
|
-
})
|
|
477
|
-
|
|
478
|
-
assert.throws(
|
|
479
|
-
() => generateKnexMigration('accounts', schema),
|
|
480
|
-
/cannot define indexType/i
|
|
481
|
-
)
|
|
482
|
-
})
|
|
483
|
-
})
|
|
484
|
-
|
|
485
|
-
describe('dbTablesOperations.generateKnexMigrationDiff', () => {
|
|
486
|
-
beforeEach(() => {
|
|
487
|
-
db = knexLib({
|
|
488
|
-
client: 'better-sqlite3',
|
|
489
|
-
connection: {
|
|
490
|
-
filename: ':memory:'
|
|
491
|
-
},
|
|
492
|
-
useNullAsDefault: true
|
|
493
|
-
})
|
|
494
|
-
})
|
|
495
|
-
|
|
496
|
-
afterEach(async () => {
|
|
497
|
-
await db.destroy()
|
|
498
|
-
})
|
|
499
|
-
|
|
500
|
-
it('generates additive alter migrations from a live snapshot', async () => {
|
|
501
|
-
await db.raw('PRAGMA foreign_keys = ON')
|
|
502
|
-
await db.raw(`
|
|
503
|
-
CREATE TABLE workspace_users (
|
|
504
|
-
workspace_id INTEGER NOT NULL,
|
|
505
|
-
user_id INTEGER NOT NULL,
|
|
506
|
-
PRIMARY KEY (workspace_id, user_id)
|
|
507
|
-
)
|
|
508
|
-
`)
|
|
509
|
-
await db.raw(`
|
|
510
|
-
CREATE TABLE memberships (
|
|
511
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
512
|
-
workspace_id INTEGER NOT NULL,
|
|
513
|
-
user_id INTEGER NOT NULL
|
|
514
|
-
)
|
|
515
|
-
`)
|
|
516
|
-
|
|
517
|
-
const currentSnapshot = await introspectKnexTableSnapshot(db, {
|
|
518
|
-
tableName: 'memberships',
|
|
519
|
-
idColumn: 'id'
|
|
520
|
-
})
|
|
521
|
-
const desiredSchema = makeTableSchema({
|
|
522
|
-
workspaceId: { type: 'id', required: true },
|
|
523
|
-
userId: { type: 'id', required: true },
|
|
524
|
-
role: { type: 'string', enum: ['owner', 'member'], required: true, defaultTo: 'member' },
|
|
525
|
-
noteCount: { type: 'number', defaultTo: 0 }
|
|
526
|
-
}, {
|
|
527
|
-
indexes: [
|
|
528
|
-
{
|
|
529
|
-
name: 'uq_memberships_workspace_user',
|
|
530
|
-
unique: true,
|
|
531
|
-
columns: ['workspaceId', 'userId']
|
|
532
|
-
}
|
|
533
|
-
],
|
|
534
|
-
foreignKeys: [
|
|
535
|
-
{
|
|
536
|
-
name: 'fk_memberships_workspace_user',
|
|
537
|
-
columns: ['workspaceId', 'userId'],
|
|
538
|
-
referencedTableName: 'workspace_users',
|
|
539
|
-
referencedColumns: ['workspace_id', 'user_id'],
|
|
540
|
-
deleteRule: 'CASCADE',
|
|
541
|
-
updateRule: 'RESTRICT'
|
|
542
|
-
}
|
|
543
|
-
]
|
|
544
|
-
})
|
|
545
|
-
|
|
546
|
-
const diff = generateKnexMigrationDiff('memberships', currentSnapshot, desiredSchema, {
|
|
547
|
-
dialect: 'better-sqlite3'
|
|
548
|
-
})
|
|
549
|
-
|
|
550
|
-
assert.deepEqual(diff.warnings, [])
|
|
551
|
-
assert.equal(Object.hasOwn(diff.plan, 'dropCheckConstraints'), false)
|
|
552
|
-
assert.deepEqual(diff.plan.addColumns.map((column) => column.name), ['note_count', 'role'])
|
|
553
|
-
assert.deepEqual(diff.plan.addIndexes.map((index) => index.name), ['uq_memberships_workspace_user'])
|
|
554
|
-
assert.deepEqual(diff.plan.addForeignKeys.map((foreignKey) => foreignKey.name), ['fk_memberships_workspace_user'])
|
|
555
|
-
assert.ok(diff.migration.includes("table.float('note_count').defaultTo(0)"))
|
|
556
|
-
assert.ok(diff.migration.includes("table.enu('role', ['owner', 'member']).notNullable().defaultTo('member')"))
|
|
557
|
-
|
|
558
|
-
const migrationModule = {}
|
|
559
|
-
new Function('migrationModule', diff.migration
|
|
560
|
-
.replace(/exports\.up/g, 'migrationModule.up')
|
|
561
|
-
.replace(/exports\.down/g, 'migrationModule.down'))(migrationModule)
|
|
562
|
-
|
|
563
|
-
await migrationModule.up(db)
|
|
564
|
-
|
|
565
|
-
const afterSnapshot = await introspectKnexTableSnapshot(db, {
|
|
566
|
-
tableName: 'memberships',
|
|
567
|
-
idColumn: 'id'
|
|
568
|
-
})
|
|
569
|
-
|
|
570
|
-
const roleColumn = afterSnapshot.columns.find((column) => column.name === 'role')
|
|
571
|
-
assert.ok(roleColumn)
|
|
572
|
-
assert.deepEqual(roleColumn.enumValues, ['owner', 'member'])
|
|
573
|
-
assert.equal(roleColumn.defaultValue, 'member')
|
|
574
|
-
assert.ok(afterSnapshot.columns.some((column) => column.name === 'note_count'))
|
|
575
|
-
assert.ok(afterSnapshot.indexes.some((index) => index.name === 'uq_memberships_workspace_user'))
|
|
576
|
-
assert.ok(afterSnapshot.foreignKeys.some((foreignKey) => foreignKey.name === 'fk_memberships_workspace_user'))
|
|
577
|
-
|
|
578
|
-
const secondDiff = generateKnexMigrationDiff('memberships', afterSnapshot, desiredSchema, {
|
|
579
|
-
dialect: 'better-sqlite3'
|
|
580
|
-
})
|
|
581
|
-
|
|
582
|
-
assert.deepEqual(secondDiff.warnings, [])
|
|
583
|
-
assert.equal(secondDiff.plan.addColumns.length, 0)
|
|
584
|
-
assert.equal(secondDiff.plan.alterColumns.length, 0)
|
|
585
|
-
assert.equal(secondDiff.plan.dropColumns.length, 0)
|
|
586
|
-
assert.equal(secondDiff.plan.addIndexes.length, 0)
|
|
587
|
-
assert.equal(secondDiff.plan.dropIndexes.length, 0)
|
|
588
|
-
assert.equal(secondDiff.plan.addForeignKeys.length, 0)
|
|
589
|
-
assert.equal(secondDiff.plan.dropForeignKeys.length, 0)
|
|
590
|
-
})
|
|
591
|
-
|
|
592
|
-
it('recreates indexes when indexType changes', async () => {
|
|
593
|
-
await db.raw(`
|
|
594
|
-
CREATE TABLE articles (
|
|
595
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
596
|
-
body TEXT
|
|
597
|
-
)
|
|
598
|
-
`)
|
|
599
|
-
|
|
600
|
-
const currentSnapshot = await introspectKnexTableSnapshot(db, {
|
|
601
|
-
tableName: 'articles',
|
|
602
|
-
idColumn: 'id'
|
|
603
|
-
})
|
|
604
|
-
currentSnapshot.indexes.push({
|
|
605
|
-
name: 'idx_articles_body',
|
|
606
|
-
unique: false,
|
|
607
|
-
columns: ['body'],
|
|
608
|
-
indexType: ''
|
|
609
|
-
})
|
|
610
|
-
|
|
611
|
-
const desiredSchema = makeTableSchema({
|
|
612
|
-
body: { type: 'string' }
|
|
613
|
-
}, {
|
|
614
|
-
indexes: [
|
|
615
|
-
{
|
|
616
|
-
name: 'idx_articles_body',
|
|
617
|
-
columns: ['body'],
|
|
618
|
-
indexType: 'FULLTEXT'
|
|
619
|
-
}
|
|
620
|
-
]
|
|
621
|
-
})
|
|
622
|
-
|
|
623
|
-
const diff = generateKnexMigrationDiff('articles', currentSnapshot, desiredSchema, {
|
|
624
|
-
dialect: 'mysql2'
|
|
625
|
-
})
|
|
626
|
-
|
|
627
|
-
assert.deepEqual(diff.plan.addIndexes.map((index) => index.name), ['idx_articles_body'])
|
|
628
|
-
assert.deepEqual(diff.plan.dropIndexes.map((index) => index.name), ['idx_articles_body'])
|
|
629
|
-
assert.ok(diff.migration.includes("table.dropIndex(['body'], 'idx_articles_body');"))
|
|
630
|
-
assert.ok(diff.migration.includes("table.index(['body'], 'idx_articles_body', { \"indexType\": 'FULLTEXT' });"))
|
|
631
|
-
})
|
|
632
|
-
|
|
633
|
-
it('warns about destructive column changes and skipped drops by default', async () => {
|
|
634
|
-
await db.raw(`
|
|
635
|
-
CREATE TABLE documents (
|
|
636
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
637
|
-
title VARCHAR(255),
|
|
638
|
-
legacy_code TEXT
|
|
639
|
-
)
|
|
640
|
-
`)
|
|
641
|
-
|
|
642
|
-
const currentSnapshot = await introspectKnexTableSnapshot(db, {
|
|
643
|
-
tableName: 'documents',
|
|
644
|
-
idColumn: 'id'
|
|
645
|
-
})
|
|
646
|
-
const desiredSchema = makeTableSchema({
|
|
647
|
-
title: { type: 'string', required: true, maxLength: 50 }
|
|
648
|
-
}, {
|
|
649
|
-
checkConstraints: [
|
|
650
|
-
{
|
|
651
|
-
name: 'chk_documents_title_non_empty',
|
|
652
|
-
clause: 'length(title) > 0'
|
|
653
|
-
}
|
|
654
|
-
]
|
|
655
|
-
})
|
|
656
|
-
|
|
657
|
-
const diff = generateKnexMigrationDiff('documents', currentSnapshot, desiredSchema, {
|
|
658
|
-
dialect: 'sqlite'
|
|
659
|
-
})
|
|
660
|
-
|
|
661
|
-
assert.ok(diff.warnings.some((warning) => warning.includes("Column 'legacy_code' exists in the live table but not in the desired schema.")))
|
|
662
|
-
assert.ok(diff.warnings.some((warning) => warning.includes("Column 'title' changes from nullable to not-null")))
|
|
663
|
-
assert.ok(diff.warnings.some((warning) => warning.includes("Column 'title' reduces maxLength from 255 to 50")))
|
|
664
|
-
assert.ok(diff.warnings.some((warning) => warning.includes("Skipping check constraint 'chk_documents_title_non_empty'")))
|
|
665
|
-
assert.equal(diff.plan.dropColumns.length, 0)
|
|
666
|
-
assert.deepEqual(diff.plan.alterColumns.map((column) => column.name), ['title'])
|
|
667
|
-
})
|
|
668
|
-
|
|
669
|
-
it('warns when setValues are diffed on a non-MySQL dialect', async () => {
|
|
670
|
-
await db.raw(`
|
|
671
|
-
CREATE TABLE articles (
|
|
672
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT
|
|
673
|
-
)
|
|
674
|
-
`)
|
|
675
|
-
|
|
676
|
-
const currentSnapshot = await introspectKnexTableSnapshot(db, {
|
|
677
|
-
tableName: 'articles',
|
|
678
|
-
idColumn: 'id'
|
|
679
|
-
})
|
|
680
|
-
const desiredSchema = makeTableSchema({
|
|
681
|
-
flags: { type: 'string', setValues: ['featured', 'archived'] }
|
|
682
|
-
})
|
|
683
|
-
|
|
684
|
-
const diff = generateKnexMigrationDiff('articles', currentSnapshot, desiredSchema, {
|
|
685
|
-
dialect: 'sqlite'
|
|
686
|
-
})
|
|
687
|
-
|
|
688
|
-
assert.ok(diff.warnings.some((warning) => warning.includes("Skipping setValues column 'flags'")))
|
|
689
|
-
assert.equal(diff.plan.addColumns.length, 0)
|
|
690
|
-
})
|
|
691
|
-
})
|
|
692
|
-
|
|
693
|
-
describe('dbTablesOperations field-only helpers', () => {
|
|
694
|
-
beforeEach(() => {
|
|
695
|
-
db = knexLib({
|
|
696
|
-
client: 'better-sqlite3',
|
|
697
|
-
connection: {
|
|
698
|
-
filename: ':memory:'
|
|
699
|
-
},
|
|
700
|
-
useNullAsDefault: true
|
|
701
|
-
})
|
|
702
|
-
})
|
|
703
|
-
|
|
704
|
-
afterEach(async () => {
|
|
705
|
-
await db.destroy()
|
|
706
|
-
})
|
|
707
|
-
|
|
708
|
-
it('rejects top-level metadata in addKnexFields', async () => {
|
|
709
|
-
await assert.rejects(
|
|
710
|
-
() => addKnexFields(db, 'accounts', makeTableSchema({
|
|
711
|
-
email: { type: 'string' }
|
|
712
|
-
}, {
|
|
713
|
-
indexes: [{ name: 'idx_accounts_email', columns: ['email'] }]
|
|
714
|
-
})),
|
|
715
|
-
/does not accept top-level indexes/i
|
|
716
|
-
)
|
|
717
|
-
})
|
|
718
|
-
|
|
719
|
-
it('rejects top-level metadata in alterKnexFields', async () => {
|
|
720
|
-
await assert.rejects(
|
|
721
|
-
() => alterKnexFields(db, 'accounts', makeTableSchema({
|
|
722
|
-
email: { type: 'string' }
|
|
723
|
-
}, {
|
|
724
|
-
checkConstraints: [{ name: 'chk_accounts_email', clause: "email <> ''" }]
|
|
725
|
-
})),
|
|
726
|
-
/does not accept top-level checkConstraints/i
|
|
727
|
-
)
|
|
728
|
-
})
|
|
729
|
-
})
|
|
730
|
-
|
|
731
|
-
describe('RestApiKnexPlugin migration scope methods', () => {
|
|
732
|
-
let api
|
|
733
|
-
|
|
734
|
-
before(async () => {
|
|
735
|
-
db = knexLib({
|
|
736
|
-
client: 'better-sqlite3',
|
|
737
|
-
connection: {
|
|
738
|
-
filename: ':memory:'
|
|
739
|
-
},
|
|
740
|
-
useNullAsDefault: true
|
|
741
|
-
})
|
|
742
|
-
|
|
743
|
-
api = new Api({
|
|
744
|
-
name: 'migration-scope-test-api',
|
|
745
|
-
log: { level: 'warn' }
|
|
746
|
-
})
|
|
747
|
-
|
|
748
|
-
await api.use(RestApiPlugin, {
|
|
749
|
-
simplifiedApi: false,
|
|
750
|
-
simplifiedTransport: false
|
|
751
|
-
})
|
|
752
|
-
await api.use(RestApiKnexPlugin, { knex: db })
|
|
753
|
-
|
|
754
|
-
await api.addResource('memberships', {
|
|
755
|
-
schema: {
|
|
756
|
-
id: { type: 'id' },
|
|
757
|
-
workspaceId: { type: 'id', required: true },
|
|
758
|
-
userId: { type: 'id', required: true },
|
|
759
|
-
role: { type: 'string', enum: ['owner', 'member'], required: true, defaultTo: 'member' }
|
|
760
|
-
},
|
|
761
|
-
indexes: [
|
|
762
|
-
{
|
|
763
|
-
name: 'uq_scope_memberships_workspace_user',
|
|
764
|
-
unique: true,
|
|
765
|
-
columns: ['workspaceId', 'userId']
|
|
766
|
-
}
|
|
767
|
-
],
|
|
768
|
-
checkConstraints: [
|
|
769
|
-
{
|
|
770
|
-
name: 'chk_scope_memberships_workspace_positive',
|
|
771
|
-
clause: 'workspace_id > 0'
|
|
772
|
-
}
|
|
773
|
-
],
|
|
774
|
-
tableName: 'scope_memberships'
|
|
775
|
-
})
|
|
776
|
-
|
|
777
|
-
await api.resources.memberships.createKnexTable()
|
|
778
|
-
})
|
|
779
|
-
|
|
780
|
-
after(async () => {
|
|
781
|
-
await db.destroy()
|
|
782
|
-
})
|
|
783
|
-
|
|
784
|
-
it('exposes create and diff migration helpers through table-backed resource scopes', async () => {
|
|
785
|
-
const createMigration = await api.resources.memberships.generateKnexMigration()
|
|
786
|
-
|
|
787
|
-
assert.ok(createMigration.includes("table.unique(['workspace_id', 'user_id'], 'uq_scope_memberships_workspace_user')"))
|
|
788
|
-
assert.ok(createMigration.includes("table.check('workspace_id > 0', [], 'chk_scope_memberships_workspace_positive')"))
|
|
789
|
-
|
|
790
|
-
const diff = await api.resources.memberships.generateKnexMigrationDiff()
|
|
791
|
-
|
|
792
|
-
assert.deepEqual(diff.warnings, [])
|
|
793
|
-
assert.equal(diff.plan.addColumns.length, 0)
|
|
794
|
-
assert.equal(diff.plan.alterColumns.length, 0)
|
|
795
|
-
assert.equal(diff.plan.addIndexes.length, 0)
|
|
796
|
-
assert.equal(diff.plan.addCheckConstraints.length, 0)
|
|
797
|
-
})
|
|
798
|
-
})
|