@orchestr-sh/orchestr 1.11.1 → 1.11.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/CHANGELOG.md +2 -0
- package/dist/Cache/CacheManager.cjs +1 -1
- package/dist/Cache/CacheManager.mjs +1 -1
- package/dist/Cache/CacheManager.mjs.map +1 -1
- package/dist/Cache/Events/CacheFlushed.cjs +1 -1
- package/dist/Cache/Events/CacheFlushed.mjs +1 -1
- package/dist/Cache/Events/CacheFlushed.mjs.map +1 -1
- package/dist/Cache/Events/CacheHit.cjs +1 -1
- package/dist/Cache/Events/CacheHit.mjs +1 -1
- package/dist/Cache/Events/CacheHit.mjs.map +1 -1
- package/dist/Cache/Events/CacheMissed.cjs +1 -1
- package/dist/Cache/Events/CacheMissed.mjs +1 -1
- package/dist/Cache/Events/CacheMissed.mjs.map +1 -1
- package/dist/Cache/Events/KeyForgotten.cjs +1 -1
- package/dist/Cache/Events/KeyForgotten.mjs +1 -1
- package/dist/Cache/Events/KeyForgotten.mjs.map +1 -1
- package/dist/Cache/Events/KeyWritten.cjs +1 -1
- package/dist/Cache/Events/KeyWritten.mjs +1 -1
- package/dist/Cache/Events/KeyWritten.mjs.map +1 -1
- package/dist/Cache/Locks/CacheLock.cjs +1 -1
- package/dist/Cache/Locks/CacheLock.mjs +1 -1
- package/dist/Cache/Locks/CacheLock.mjs.map +1 -1
- package/dist/Cache/Locks/Lock.cjs +1 -1
- package/dist/Cache/Locks/Lock.mjs +1 -1
- package/dist/Cache/Locks/Lock.mjs.map +1 -1
- package/dist/Cache/Repository.cjs +1 -1
- package/dist/Cache/Repository.mjs +1 -1
- package/dist/Cache/Repository.mjs.map +1 -1
- package/dist/Cache/Stores/ArrayStore.cjs +1 -1
- package/dist/Cache/Stores/ArrayStore.mjs +1 -1
- package/dist/Cache/Stores/ArrayStore.mjs.map +1 -1
- package/dist/Cache/Stores/DatabaseStore.cjs +1 -1
- package/dist/Cache/Stores/DatabaseStore.mjs +1 -1
- package/dist/Cache/Stores/DatabaseStore.mjs.map +1 -1
- package/dist/Cache/Stores/FileStore.cjs +1 -1
- package/dist/Cache/Stores/FileStore.mjs +1 -1
- package/dist/Cache/Stores/FileStore.mjs.map +1 -1
- package/dist/Cache/Tags/TagSet.cjs +1 -1
- package/dist/Cache/Tags/TagSet.mjs +1 -1
- package/dist/Cache/Tags/TagSet.mjs.map +1 -1
- package/dist/Cache/Tags/TaggedCache.cjs +1 -1
- package/dist/Cache/Tags/TaggedCache.mjs +1 -1
- package/dist/Cache/Tags/TaggedCache.mjs.map +1 -1
- package/dist/Console/Commands/CacheClearCommand.cjs +1 -1
- package/dist/Console/Commands/CacheClearCommand.mjs +1 -1
- package/dist/Console/Commands/CacheClearCommand.mjs.map +1 -1
- package/dist/Console/Commands/CacheForgetCommand.cjs +1 -1
- package/dist/Console/Commands/CacheForgetCommand.mjs +1 -1
- package/dist/Console/Commands/CacheForgetCommand.mjs.map +1 -1
- package/dist/Console/Commands/CacheTableCommand.cjs +1 -1
- package/dist/Console/Commands/CacheTableCommand.mjs +1 -1
- package/dist/Console/Commands/CacheTableCommand.mjs.map +1 -1
- package/dist/Console/Commands/DeployCommand.mjs.map +1 -1
- package/dist/Console/Commands/DeployEnvCommand.mjs.map +1 -1
- package/dist/Console/Commands/DeployInitCommand.mjs.map +1 -1
- package/dist/Console/Commands/DeployProvisionCommand.mjs.map +1 -1
- package/dist/Console/Commands/DeployRollbackCommand.mjs.map +1 -1
- package/dist/Console/Commands/DeployServerCommand.mjs.map +1 -1
- package/dist/Console/Commands/DeployStatusCommand.mjs.map +1 -1
- package/dist/Console/Commands/EventCacheCommand.cjs +1 -1
- package/dist/Console/Commands/EventCacheCommand.mjs +1 -1
- package/dist/Console/Commands/EventCacheCommand.mjs.map +1 -1
- package/dist/Console/Commands/EventClearCommand.cjs +1 -1
- package/dist/Console/Commands/EventClearCommand.mjs +1 -1
- package/dist/Console/Commands/EventClearCommand.mjs.map +1 -1
- package/dist/Console/Commands/EventListCommand.cjs +1 -1
- package/dist/Console/Commands/EventListCommand.mjs +1 -1
- package/dist/Console/Commands/EventListCommand.mjs.map +1 -1
- package/dist/Console/Commands/MakeControllerCommand.cjs +1 -1
- package/dist/Console/Commands/MakeControllerCommand.mjs +1 -1
- package/dist/Console/Commands/MakeControllerCommand.mjs.map +1 -1
- package/dist/Console/Commands/MakeEventCommand.cjs +1 -1
- package/dist/Console/Commands/MakeEventCommand.mjs +1 -1
- package/dist/Console/Commands/MakeEventCommand.mjs.map +1 -1
- package/dist/Console/Commands/MakeJobCommand.cjs +1 -1
- package/dist/Console/Commands/MakeJobCommand.mjs +1 -1
- package/dist/Console/Commands/MakeJobCommand.mjs.map +1 -1
- package/dist/Console/Commands/MakeListenerCommand.cjs +1 -1
- package/dist/Console/Commands/MakeListenerCommand.mjs +1 -1
- package/dist/Console/Commands/MakeListenerCommand.mjs.map +1 -1
- package/dist/Console/Commands/MakeMigrationCommand.cjs +1 -1
- package/dist/Console/Commands/MakeMigrationCommand.mjs +1 -1
- package/dist/Console/Commands/MakeMigrationCommand.mjs.map +1 -1
- package/dist/Console/Commands/MakeSeederCommand.cjs +1 -1
- package/dist/Console/Commands/MakeSeederCommand.mjs +1 -1
- package/dist/Console/Commands/MakeSeederCommand.mjs.map +1 -1
- package/dist/Console/Commands/MakeViewCommand.cjs +1 -1
- package/dist/Console/Commands/MakeViewCommand.mjs +1 -1
- package/dist/Console/Commands/MakeViewCommand.mjs.map +1 -1
- package/dist/Console/Commands/MigrateCommand.cjs +1 -1
- package/dist/Console/Commands/MigrateCommand.mjs +1 -1
- package/dist/Console/Commands/MigrateCommand.mjs.map +1 -1
- package/dist/Console/Commands/MigrateFreshCommand.cjs +1 -1
- package/dist/Console/Commands/MigrateFreshCommand.mjs +1 -1
- package/dist/Console/Commands/MigrateFreshCommand.mjs.map +1 -1
- package/dist/Console/Commands/MigrateRefreshCommand.cjs +1 -1
- package/dist/Console/Commands/MigrateRefreshCommand.mjs +1 -1
- package/dist/Console/Commands/MigrateRefreshCommand.mjs.map +1 -1
- package/dist/Console/Commands/MigrateResetCommand.cjs +1 -1
- package/dist/Console/Commands/MigrateResetCommand.mjs +1 -1
- package/dist/Console/Commands/MigrateResetCommand.mjs.map +1 -1
- package/dist/Console/Commands/MigrateRollbackCommand.cjs +1 -1
- package/dist/Console/Commands/MigrateRollbackCommand.mjs +1 -1
- package/dist/Console/Commands/MigrateRollbackCommand.mjs.map +1 -1
- package/dist/Console/Commands/MigrateStatusCommand.cjs +1 -1
- package/dist/Console/Commands/MigrateStatusCommand.mjs +1 -1
- package/dist/Console/Commands/MigrateStatusCommand.mjs.map +1 -1
- package/dist/Console/Commands/QueueBatchesTableCommand.cjs +1 -1
- package/dist/Console/Commands/QueueBatchesTableCommand.mjs +1 -1
- package/dist/Console/Commands/QueueBatchesTableCommand.mjs.map +1 -1
- package/dist/Console/Commands/QueueClearCommand.cjs +1 -1
- package/dist/Console/Commands/QueueClearCommand.mjs +1 -1
- package/dist/Console/Commands/QueueClearCommand.mjs.map +1 -1
- package/dist/Console/Commands/QueueFailedCommand.cjs +1 -1
- package/dist/Console/Commands/QueueFailedCommand.mjs +1 -1
- package/dist/Console/Commands/QueueFailedCommand.mjs.map +1 -1
- package/dist/Console/Commands/QueueFailedTableCommand.cjs +1 -1
- package/dist/Console/Commands/QueueFailedTableCommand.mjs +1 -1
- package/dist/Console/Commands/QueueFailedTableCommand.mjs.map +1 -1
- package/dist/Console/Commands/QueueFlushCommand.cjs +1 -1
- package/dist/Console/Commands/QueueFlushCommand.mjs +1 -1
- package/dist/Console/Commands/QueueFlushCommand.mjs.map +1 -1
- package/dist/Console/Commands/QueueForgetCommand.cjs +1 -1
- package/dist/Console/Commands/QueueForgetCommand.mjs +1 -1
- package/dist/Console/Commands/QueueForgetCommand.mjs.map +1 -1
- package/dist/Console/Commands/QueueMonitorCommand.cjs +1 -1
- package/dist/Console/Commands/QueueMonitorCommand.mjs +1 -1
- package/dist/Console/Commands/QueueMonitorCommand.mjs.map +1 -1
- package/dist/Console/Commands/QueuePruneBatchesCommand.cjs +1 -1
- package/dist/Console/Commands/QueuePruneBatchesCommand.mjs +1 -1
- package/dist/Console/Commands/QueuePruneBatchesCommand.mjs.map +1 -1
- package/dist/Console/Commands/QueuePruneFailedCommand.cjs +1 -1
- package/dist/Console/Commands/QueuePruneFailedCommand.mjs +1 -1
- package/dist/Console/Commands/QueuePruneFailedCommand.mjs.map +1 -1
- package/dist/Console/Commands/QueueRestartCommand.cjs +1 -1
- package/dist/Console/Commands/QueueRestartCommand.mjs +1 -1
- package/dist/Console/Commands/QueueRestartCommand.mjs.map +1 -1
- package/dist/Console/Commands/QueueRetryCommand.cjs +1 -1
- package/dist/Console/Commands/QueueRetryCommand.mjs +1 -1
- package/dist/Console/Commands/QueueRetryCommand.mjs.map +1 -1
- package/dist/Console/Commands/QueueTableCommand.cjs +1 -1
- package/dist/Console/Commands/QueueTableCommand.mjs +1 -1
- package/dist/Console/Commands/QueueTableCommand.mjs.map +1 -1
- package/dist/Console/Commands/QueueWorkCommand.cjs +1 -1
- package/dist/Console/Commands/QueueWorkCommand.mjs +1 -1
- package/dist/Console/Commands/QueueWorkCommand.mjs.map +1 -1
- package/dist/Console/Commands/SeedCommand.cjs +1 -1
- package/dist/Console/Commands/SeedCommand.mjs +1 -1
- package/dist/Console/Commands/SeedCommand.mjs.map +1 -1
- package/dist/Console/ConsoleKernel.cjs +1 -1
- package/dist/Console/ConsoleKernel.mjs +1 -1
- package/dist/Console/ConsoleKernel.mjs.map +1 -1
- package/dist/Console/orchestr.mjs.map +1 -1
- package/dist/Container/Container.mjs.map +1 -1
- package/dist/Database/Adapters/DrizzleAdapter.cjs +1 -1
- package/dist/Database/Adapters/DrizzleAdapter.mjs +1 -1
- package/dist/Database/Adapters/DrizzleAdapter.mjs.map +1 -1
- package/dist/Database/Connection.cjs +1 -1
- package/dist/Database/Connection.mjs +1 -1
- package/dist/Database/Connection.mjs.map +1 -1
- package/dist/Database/DatabaseManager.cjs +1 -1
- package/dist/Database/DatabaseManager.mjs +1 -1
- package/dist/Database/DatabaseManager.mjs.map +1 -1
- package/dist/Database/Ensemble/Ensemble.mjs.map +1 -1
- package/dist/Database/Ensemble/EnsembleBuilder.mjs.map +1 -1
- package/dist/Database/Ensemble/EnsembleCollection.cjs +1 -1
- package/dist/Database/Ensemble/EnsembleCollection.mjs +1 -1
- package/dist/Database/Ensemble/EnsembleCollection.mjs.map +1 -1
- package/dist/Database/Ensemble/Relations/BelongsTo.mjs.map +1 -1
- package/dist/Database/Ensemble/Relations/BelongsToMany.cjs +1 -1
- package/dist/Database/Ensemble/Relations/BelongsToMany.mjs +1 -1
- package/dist/Database/Ensemble/Relations/BelongsToMany.mjs.map +1 -1
- package/dist/Database/Ensemble/Relations/HasMany.mjs.map +1 -1
- package/dist/Database/Ensemble/Relations/MorphTo.mjs.map +1 -1
- package/dist/Database/Ensemble/Relations/MorphToMany.mjs.map +1 -1
- package/dist/Database/Migrations/Blueprint.cjs +1 -1
- package/dist/Database/Migrations/Blueprint.mjs +1 -1
- package/dist/Database/Migrations/Blueprint.mjs.map +1 -1
- package/dist/Database/Migrations/MigrationCreator.cjs +1 -1
- package/dist/Database/Migrations/MigrationCreator.mjs +1 -1
- package/dist/Database/Migrations/MigrationCreator.mjs.map +1 -1
- package/dist/Database/Migrations/MigrationRepository.cjs +1 -1
- package/dist/Database/Migrations/MigrationRepository.mjs +1 -1
- package/dist/Database/Migrations/MigrationRepository.mjs.map +1 -1
- package/dist/Database/Migrations/Migrator.cjs +1 -1
- package/dist/Database/Migrations/Migrator.mjs +1 -1
- package/dist/Database/Migrations/Migrator.mjs.map +1 -1
- package/dist/Database/Migrations/SchemaBuilder.cjs +1 -1
- package/dist/Database/Migrations/SchemaBuilder.mjs +1 -1
- package/dist/Database/Migrations/SchemaBuilder.mjs.map +1 -1
- package/dist/Database/Query/Builder.cjs +1 -1
- package/dist/Database/Query/Builder.mjs +1 -1
- package/dist/Database/Query/Builder.mjs.map +1 -1
- package/dist/Database/Query/Expression.cjs +1 -1
- package/dist/Database/Query/Expression.mjs +1 -1
- package/dist/Database/Query/Expression.mjs.map +1 -1
- package/dist/Database/Seeders/SeederRunner.cjs +1 -1
- package/dist/Database/Seeders/SeederRunner.mjs +1 -1
- package/dist/Database/Seeders/SeederRunner.mjs.map +1 -1
- package/dist/Deploy/Deployer.cjs +1 -1
- package/dist/Deploy/Deployer.mjs +1 -1
- package/dist/Deploy/Deployer.mjs.map +1 -1
- package/dist/Deploy/ProjectConfig.mjs.map +1 -1
- package/dist/Deploy/Provisioner.cjs +1 -1
- package/dist/Deploy/Provisioner.mjs +1 -1
- package/dist/Deploy/Provisioner.mjs.map +1 -1
- package/dist/Deploy/SSHConnection.mjs.map +1 -1
- package/dist/Deploy/SymphonyClient.cjs +1 -1
- package/dist/Deploy/SymphonyClient.mjs +1 -1
- package/dist/Deploy/SymphonyClient.mjs.map +1 -1
- package/dist/Deploy/TarBuilder.mjs.map +1 -1
- package/dist/Deploy/prompt.mjs.map +1 -1
- package/dist/Events/Dispatcher.cjs +1 -1
- package/dist/Events/Dispatcher.mjs +1 -1
- package/dist/Events/Dispatcher.mjs.map +1 -1
- package/dist/Events/EventServiceProvider.cjs +1 -1
- package/dist/Events/EventServiceProvider.mjs.map +1 -1
- package/dist/Facades/Bus.mjs.map +1 -1
- package/dist/Facades/Cache.mjs.map +1 -1
- package/dist/Facades/Config.mjs.map +1 -1
- package/dist/Facades/DB.mjs.map +1 -1
- package/dist/Facades/Event.mjs.map +1 -1
- package/dist/Facades/Queue.mjs.map +1 -1
- package/dist/Facades/Route.mjs.map +1 -1
- package/dist/Facades/View.mjs.map +1 -1
- package/dist/Foundation/Application.mjs.map +1 -1
- package/dist/Foundation/Http/FormRequest.mjs.map +1 -1
- package/dist/Foundation/Http/Rules/AnyOfRule.mjs.map +1 -1
- package/dist/Foundation/Http/Rules/ImageFileRule.mjs.map +1 -1
- package/dist/Foundation/Http/Validator.mjs.map +1 -1
- package/dist/Queue/Batching/Batch.cjs +1 -1
- package/dist/Queue/Batching/Batch.mjs +1 -1
- package/dist/Queue/Batching/Batch.mjs.map +1 -1
- package/dist/Queue/Batching/PendingBatch.cjs +1 -1
- package/dist/Queue/Batching/PendingBatch.mjs +1 -1
- package/dist/Queue/Batching/PendingBatch.mjs.map +1 -1
- package/dist/Queue/Concerns/Dispatchable.mjs.map +1 -1
- package/dist/Queue/Drivers/DatabaseDriver.cjs +1 -1
- package/dist/Queue/Drivers/DatabaseDriver.mjs +1 -1
- package/dist/Queue/Drivers/DatabaseDriver.mjs.map +1 -1
- package/dist/Queue/Drivers/NullDriver.cjs +1 -1
- package/dist/Queue/Drivers/NullDriver.mjs +1 -1
- package/dist/Queue/Drivers/NullDriver.mjs.map +1 -1
- package/dist/Queue/Drivers/SyncDriver.cjs +1 -1
- package/dist/Queue/Drivers/SyncDriver.mjs +1 -1
- package/dist/Queue/Drivers/SyncDriver.mjs.map +1 -1
- package/dist/Queue/Events/JobExceptionOccurred.cjs +1 -1
- package/dist/Queue/Events/JobExceptionOccurred.mjs +1 -1
- package/dist/Queue/Events/JobExceptionOccurred.mjs.map +1 -1
- package/dist/Queue/Events/JobFailed.cjs +1 -1
- package/dist/Queue/Events/JobFailed.mjs +1 -1
- package/dist/Queue/Events/JobFailed.mjs.map +1 -1
- package/dist/Queue/Events/JobProcessed.cjs +1 -1
- package/dist/Queue/Events/JobProcessed.mjs +1 -1
- package/dist/Queue/Events/JobProcessed.mjs.map +1 -1
- package/dist/Queue/Events/JobProcessing.cjs +1 -1
- package/dist/Queue/Events/JobProcessing.mjs +1 -1
- package/dist/Queue/Events/JobProcessing.mjs.map +1 -1
- package/dist/Queue/Events/JobQueued.cjs +1 -1
- package/dist/Queue/Events/JobQueued.mjs +1 -1
- package/dist/Queue/Events/JobQueued.mjs.map +1 -1
- package/dist/Queue/Events/JobRetryRequested.cjs +1 -1
- package/dist/Queue/Events/JobRetryRequested.mjs +1 -1
- package/dist/Queue/Events/JobRetryRequested.mjs.map +1 -1
- package/dist/Queue/Events/WorkerStopping.cjs +1 -1
- package/dist/Queue/Events/WorkerStopping.mjs +1 -1
- package/dist/Queue/Events/WorkerStopping.mjs.map +1 -1
- package/dist/Queue/Failed/DatabaseFailedJobProvider.cjs +1 -1
- package/dist/Queue/Failed/DatabaseFailedJobProvider.mjs +1 -1
- package/dist/Queue/Failed/DatabaseFailedJobProvider.mjs.map +1 -1
- package/dist/Queue/Middleware/RateLimited.cjs +1 -1
- package/dist/Queue/Middleware/RateLimited.mjs +1 -1
- package/dist/Queue/Middleware/RateLimited.mjs.map +1 -1
- package/dist/Queue/Middleware/ThrottlesExceptions.cjs +1 -1
- package/dist/Queue/Middleware/ThrottlesExceptions.mjs +1 -1
- package/dist/Queue/Middleware/ThrottlesExceptions.mjs.map +1 -1
- package/dist/Queue/Middleware/WithoutOverlapping.cjs +1 -1
- package/dist/Queue/Middleware/WithoutOverlapping.mjs +1 -1
- package/dist/Queue/Middleware/WithoutOverlapping.mjs.map +1 -1
- package/dist/Queue/PendingChain.cjs +1 -1
- package/dist/Queue/PendingChain.mjs +1 -1
- package/dist/Queue/PendingChain.mjs.map +1 -1
- package/dist/Queue/PendingDispatch.cjs +1 -1
- package/dist/Queue/PendingDispatch.mjs +1 -1
- package/dist/Queue/PendingDispatch.mjs.map +1 -1
- package/dist/Queue/QueueManager.cjs +1 -1
- package/dist/Queue/QueueManager.mjs +1 -1
- package/dist/Queue/QueueManager.mjs.map +1 -1
- package/dist/Queue/QueueServiceProvider.mjs.map +1 -1
- package/dist/Queue/Workers/Worker.cjs +1 -1
- package/dist/Queue/Workers/Worker.mjs +1 -1
- package/dist/Queue/Workers/Worker.mjs.map +1 -1
- package/dist/Routing/Request.mjs.map +1 -1
- package/dist/Routing/Response.mjs.map +1 -1
- package/dist/Support/EventDiscovery.cjs +1 -1
- package/dist/Support/EventDiscovery.mjs +1 -1
- package/dist/Support/EventDiscovery.mjs.map +1 -1
- package/dist/Support/Testing/Fakes/EventFake.cjs +1 -1
- package/dist/Support/Testing/Fakes/EventFake.mjs +1 -1
- package/dist/Support/Testing/Fakes/EventFake.mjs.map +1 -1
- package/dist/Support/helpers.mjs.map +1 -1
- package/dist/View/Engines/TemplateEngine.mjs.map +1 -1
- package/package.json +17 -17
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BelongsToMany.mjs","names":[],"sources":["../../../../src/Database/Ensemble/Relations/BelongsToMany.ts"],"sourcesContent":["/**\n * BelongsToMany Relationship\n *\n * Represents a many-to-many relationship\n */\n\nimport { Ensemble } from '@/Database/Ensemble/Ensemble';\nimport { EnsembleBuilder } from '@/Database/Ensemble/EnsembleBuilder';\nimport { EnsembleCollection } from '@/Database/Ensemble/EnsembleCollection';\nimport { Relation } from './Relation';\n\nexport class BelongsToMany<TRelated extends Ensemble, TParent extends Ensemble> extends Relation<TRelated, TParent> {\n /**\n * The intermediate table for the relation\n */\n protected table: string;\n\n /**\n * The foreign key of the parent model\n */\n protected foreignPivotKey: string;\n\n /**\n * The associated key of the relation\n */\n protected relatedPivotKey: string;\n\n /**\n * The parent key of the relationship\n */\n protected parentKey: string;\n\n /**\n * The related key of the relationship\n */\n protected relatedKey: string;\n\n /**\n * The name of the relationship\n */\n protected relationName: string;\n\n /**\n * The pivot table columns to retrieve\n */\n protected pivotColumns: string[] = [];\n\n /**\n * Any pivot table restrictions\n */\n protected pivotWheres: Array<{ column: string; operator?: string; value?: any; boolean: string }> = [];\n\n /**\n * The pivot table values to attach\n */\n protected pivotValues: Record<string, any>[] = [];\n\n /**\n * Whether we are using timestamps on the pivot table\n */\n protected usingTimestamps: boolean = false;\n\n /**\n * The custom pivot table model\n */\n protected using?: any;\n\n /**\n * The name of the \"created at\" column\n */\n protected pivotCreatedAt?: string;\n\n /**\n * The name of the \"updated at\" column\n */\n protected pivotUpdatedAt?: string;\n\n /**\n * The name of the accessor to use for the pivot relationship\n */\n protected accessor: string = 'pivot';\n\n /**\n * Create a new belongs to many relationship instance\n */\n constructor(\n query: EnsembleBuilder<TRelated>,\n parent: TParent,\n table: string,\n foreignPivotKey: string,\n relatedPivotKey: string,\n parentKey: string,\n relatedKey: string,\n relationName?: string\n ) {\n super(query, parent);\n this.table = table;\n this.foreignPivotKey = foreignPivotKey;\n this.relatedPivotKey = relatedPivotKey;\n this.parentKey = parentKey;\n this.relatedKey = relatedKey;\n this.relationName = relationName || '';\n this.initializeRelation();\n }\n\n /**\n * Set the base constraints on the relation query\n */\n addConstraints(): void {\n this.performJoin();\n\n if (Relation['constraints']) {\n this.addWhereConstraints();\n }\n }\n\n /**\n * Set the join clause for the relation query\n */\n protected performJoin(query?: EnsembleBuilder<TRelated>): void {\n query = query || this.query;\n\n // Join the pivot table on the related key\n query.join(this.table, `${this.getQualifiedRelatedKeyName()}`, '=', `${this.getQualifiedRelatedPivotKeyName()}`);\n }\n\n /**\n * Set the where clause for the relation query\n */\n protected addWhereConstraints(): void {\n const parentKeyValue = this.parent.getAttribute(this.parentKey);\n\n // Only add constraint if parent key value exists\n if (parentKeyValue !== null && parentKeyValue !== undefined) {\n this.query.where(this.getQualifiedForeignPivotKeyName(), '=', parentKeyValue);\n }\n }\n\n /**\n * Set the constraints for an eager load of the relation\n */\n addEagerConstraints(models: TParent[]): void {\n const keys = this.getKeys(models, this.parentKey);\n this.query.whereIn(this.getQualifiedForeignPivotKeyName(), keys);\n }\n\n /**\n * Initialize the relation on a set of models\n */\n initRelation(models: TParent[], relation: string): TParent[] {\n for (const model of models) {\n model.setRelation(relation, new EnsembleCollection<TRelated>());\n }\n\n return models;\n }\n\n /**\n * Match the eagerly loaded results to their parents\n */\n match(models: TParent[], results: EnsembleCollection<TRelated>, relation: string): TParent[] {\n const dictionary = this.buildDictionary(results);\n\n for (const model of models) {\n const key = model.getAttribute(this.parentKey);\n\n if (key !== null && key !== undefined && dictionary[key]) {\n model.setRelation(relation, new EnsembleCollection<TRelated>(dictionary[key]));\n }\n }\n\n return models;\n }\n\n /**\n * Build model dictionary keyed by the relation's foreign key\n */\n protected buildDictionary(results: EnsembleCollection<TRelated>): Record<any, TRelated[]> {\n const dictionary: Record<any, TRelated[]> = {};\n\n for (const result of results) {\n const pivotAttributes = this.migratePivotAttributes(result);\n const key = pivotAttributes[this.foreignPivotKey];\n\n if (key !== null && key !== undefined) {\n if (!dictionary[key]) {\n dictionary[key] = [];\n }\n dictionary[key].push(result);\n }\n }\n\n return dictionary;\n }\n\n /**\n * Get the results of the relationship\n */\n async getResults(): Promise<TRelated[]> {\n const parentKey = this.parent.getAttribute(this.parentKey);\n\n if (!parentKey) {\n return [];\n }\n\n return this.get();\n }\n\n /**\n * Execute the query and get the models\n */\n async get(): Promise<TRelated[]> {\n this.ensureConstraints();\n\n const builder = this.query.addSelect(...this.shouldSelect());\n\n const models = await builder.get();\n\n this.hydratePivotRelation(models);\n\n return models;\n }\n\n /**\n * Get the select columns for the relation query\n */\n protected shouldSelect(columns: string[] = ['*']): string[] {\n if (columns.length === 1 && columns[0] === '*') {\n columns = [`${this.related.getTable()}.*`];\n }\n\n return [...columns, ...this.aliasedPivotColumns()];\n }\n\n /**\n * Get the pivot columns for the relation\n */\n protected aliasedPivotColumns(): string[] {\n const defaults = [this.foreignPivotKey, this.relatedPivotKey];\n const columns = [...defaults, ...this.pivotColumns];\n\n return columns.map((column) => {\n return `${this.table}.${column} as pivot_${column}`;\n });\n }\n\n /**\n * Hydrate the pivot relationship on the models\n */\n protected hydratePivotRelation(models: TRelated[]): void {\n for (const model of models) {\n const pivot = this.migratePivotAttributes(model);\n model.setRelation(this.accessor, pivot);\n }\n }\n\n /**\n * Migrate the pivot attributes from the model to a pivot model\n */\n protected migratePivotAttributes(model: TRelated): Record<string, any> {\n const values: Record<string, any> = {};\n\n // Extract all pivot_* attributes\n const attributes = (model as any).attributes || {};\n for (const [key, value] of Object.entries(attributes)) {\n if (key.startsWith('pivot_')) {\n const pivotKey = key.substring(6); // Remove 'pivot_' prefix\n values[pivotKey] = value;\n delete (model as any).attributes[key];\n }\n }\n\n return values;\n }\n\n /**\n * Get the fully qualified foreign key for the relation\n */\n protected getQualifiedForeignPivotKeyName(): string {\n return `${this.table}.${this.foreignPivotKey}`;\n }\n\n /**\n * Get the fully qualified \"related key\" for the relation\n */\n protected getQualifiedRelatedPivotKeyName(): string {\n return `${this.table}.${this.relatedPivotKey}`;\n }\n\n /**\n * Get the fully qualified parent key name\n */\n protected getQualifiedParentKeyName(): string {\n return `${this.parent.getTable()}.${this.parentKey}`;\n }\n\n /**\n * Get the fully qualified related key name\n */\n protected getQualifiedRelatedKeyName(): string {\n return `${this.related.getTable()}.${this.relatedKey}`;\n }\n\n /**\n * Specify the pivot table columns to retrieve\n */\n withPivot(...columns: string[]): this {\n this.pivotColumns = [...this.pivotColumns, ...columns];\n\n return this;\n }\n\n /**\n * Indicate that the pivot table has timestamps\n */\n withTimestamps(createdAt?: string, updatedAt?: string): this {\n this.usingTimestamps = true;\n\n this.pivotCreatedAt = createdAt || 'created_at';\n this.pivotUpdatedAt = updatedAt || 'updated_at';\n\n return this.withPivot(this.pivotCreatedAt, this.pivotUpdatedAt);\n }\n\n /**\n * Set a where clause for the pivot table\n */\n wherePivot(column: string, operator?: any, value?: any): this {\n if (arguments.length === 2) {\n value = operator;\n operator = '=';\n }\n\n this.pivotWheres.push({\n column: `${this.table}.${column}`,\n operator,\n value,\n boolean: 'and',\n });\n\n return this.query.where(`${this.table}.${column}`, operator, value) as any;\n }\n\n /**\n * Set a \"where in\" clause for the pivot table\n */\n wherePivotIn(column: string, values: any[]): this {\n return this.query.whereIn(`${this.table}.${column}`, values) as any;\n }\n\n /**\n * Set a \"where not in\" clause for the pivot table\n */\n wherePivotNotIn(column: string, values: any[]): this {\n return this.query.whereNotIn(`${this.table}.${column}`, values) as any;\n }\n\n /**\n * Set a \"where null\" clause for the pivot table\n */\n wherePivotNull(column: string): this {\n return this.query.whereNull(`${this.table}.${column}`) as any;\n }\n\n /**\n * Set a \"where not null\" clause for the pivot table\n */\n wherePivotNotNull(column: string): this {\n return this.query.whereNotNull(`${this.table}.${column}`) as any;\n }\n\n /**\n * Set an \"or where\" clause for the pivot table\n */\n orWherePivot(column: string, operator?: any, value?: any): this {\n if (arguments.length === 2) {\n value = operator;\n operator = '=';\n }\n\n return this.query.orWhere(`${this.table}.${column}`, operator, value) as any;\n }\n\n /**\n * Attach models to the parent\n */\n async attach(ids: any | any[], attributes: Record<string, any> = {}): Promise<void> {\n const records = this.formatAttachRecords(this.parseIds(ids), attributes);\n\n if (records.length === 0) {\n return;\n }\n\n const connection = this.parent.getConnection();\n await connection.table(this.table).insert(records);\n }\n\n /**\n * Detach models from the parent\n */\n async detach(ids?: any | any[]): Promise<number> {\n const connection = this.parent.getConnection();\n let query = connection.table(this.table).where(this.foreignPivotKey, '=', this.parent.getAttribute(this.parentKey));\n\n if (ids !== undefined) {\n const parsedIds = this.parseIds(ids);\n query = query.whereIn(this.relatedPivotKey, parsedIds);\n }\n\n return await query.delete();\n }\n\n /**\n * Sync the intermediate tables with a list of IDs\n */\n async sync(ids: any | any[] | Record<number | string, Record<string, any>>): Promise<{\n attached: any[];\n detached: any[];\n updated: any[];\n }> {\n const changes = {\n attached: [] as any[],\n detached: [] as any[],\n updated: [] as any[],\n };\n\n const current = await this.getCurrentlyAttachedPivots();\n const records = this.formatRecordsList(this.parseIds(ids));\n\n const detach = current.filter((id) => !records.some((record) => record.id === id));\n\n if (detach.length > 0) {\n await this.detach(detach);\n changes.detached = detach;\n }\n\n changes.attached = await this.attachNew(records, current);\n changes.updated = await this.updateExisting(records, current);\n\n return changes;\n }\n\n /**\n * Sync without detaching\n */\n async syncWithoutDetaching(ids: any | any[] | Record<number | string, Record<string, any>>): Promise<{\n attached: any[];\n updated: any[];\n }> {\n const changes = {\n attached: [] as any[],\n updated: [] as any[],\n };\n\n const current = await this.getCurrentlyAttachedPivots();\n const records = this.formatRecordsList(this.parseIds(ids));\n\n changes.attached = await this.attachNew(records, current);\n changes.updated = await this.updateExisting(records, current);\n\n return changes;\n }\n\n /**\n * Toggle models from the parent\n */\n async toggle(ids: any | any[]): Promise<{\n attached: any[];\n detached: any[];\n }> {\n const changes = {\n attached: [] as any[],\n detached: [] as any[],\n };\n\n const parsedIds = this.parseIds(ids);\n const current = await this.getCurrentlyAttachedPivots();\n\n const detach = parsedIds.filter((id) => current.includes(id));\n const attach = parsedIds.filter((id) => !current.includes(id));\n\n if (detach.length > 0) {\n await this.detach(detach);\n changes.detached = detach;\n }\n\n if (attach.length > 0) {\n await this.attach(attach);\n changes.attached = attach;\n }\n\n return changes;\n }\n\n /**\n * Update an existing pivot record on the table\n */\n async updateExistingPivot(id: any, attributes: Record<string, any>): Promise<number> {\n if (this.usingTimestamps && this.pivotUpdatedAt) {\n attributes[this.pivotUpdatedAt] = new Date();\n }\n\n const connection = this.parent.getConnection();\n return await connection\n .table(this.table)\n .where(this.foreignPivotKey, '=', this.parent.getAttribute(this.parentKey))\n .where(this.relatedPivotKey, '=', id)\n .update(attributes);\n }\n\n /**\n * Get the currently attached pivot IDs\n */\n protected async getCurrentlyAttachedPivots(): Promise<any[]> {\n const connection = this.parent.getConnection();\n const results = await connection\n .table(this.table)\n .where(this.foreignPivotKey, '=', this.parent.getAttribute(this.parentKey))\n .pluck(this.relatedPivotKey);\n\n return results;\n }\n\n /**\n * Attach new records\n */\n protected async attachNew(\n records: Array<{ id: any; attributes: Record<string, any> }>,\n current: any[]\n ): Promise<any[]> {\n const newRecords = records.filter((record) => !current.includes(record.id));\n\n if (newRecords.length === 0) {\n return [];\n }\n\n await this.attach(\n newRecords.map((r) => r.id),\n newRecords[0]?.attributes || {}\n );\n\n return newRecords.map((r) => r.id);\n }\n\n /**\n * Update existing records\n */\n protected async updateExisting(\n records: Array<{ id: any; attributes: Record<string, any> }>,\n current: any[]\n ): Promise<any[]> {\n const updated: any[] = [];\n\n for (const record of records) {\n if (current.includes(record.id) && Object.keys(record.attributes).length > 0) {\n await this.updateExistingPivot(record.id, record.attributes);\n updated.push(record.id);\n }\n }\n\n return updated;\n }\n\n /**\n * Format the records for attaching\n */\n protected formatAttachRecords(ids: any[], attributes: Record<string, any>): Record<string, any>[] {\n const records: Record<string, any>[] = [];\n const hasTimestamps = this.usingTimestamps;\n\n for (const id of ids) {\n const record: Record<string, any> = {\n [this.foreignPivotKey]: this.parent.getAttribute(this.parentKey),\n [this.relatedPivotKey]: id,\n ...attributes,\n };\n\n if (hasTimestamps) {\n const now = new Date();\n if (this.pivotCreatedAt) {\n record[this.pivotCreatedAt] = now;\n }\n if (this.pivotUpdatedAt) {\n record[this.pivotUpdatedAt] = now;\n }\n }\n\n records.push(record);\n }\n\n return records;\n }\n\n /**\n * Format the sync records\n */\n protected formatRecordsList(ids: any[]): Array<{ id: any; attributes: Record<string, any> }> {\n return ids.map((id) => {\n if (typeof id === 'object' && !Array.isArray(id)) {\n const { id: recordId, ...attributes } = id;\n return { id: recordId, attributes };\n }\n return { id, attributes: {} };\n });\n }\n\n /**\n * Parse the IDs from the given value\n */\n protected parseIds(value: any): any[] {\n if (value instanceof EnsembleCollection) {\n return value.modelKeys();\n }\n\n if (Array.isArray(value)) {\n return value;\n }\n\n if (typeof value === 'object' && value !== null) {\n // Handle {id: attributes} format\n return Object.keys(value).map((key) => {\n const id = isNaN(Number(key)) ? key : Number(key);\n return { id, ...value[key] };\n });\n }\n\n return [value];\n }\n\n /**\n * Get the name of the pivot accessor\n */\n getPivotAccessor(): string {\n return this.accessor;\n }\n\n /**\n * Set the name of the pivot accessor\n */\n as(accessor: string): this {\n this.accessor = accessor;\n return this;\n }\n\n /**\n * Get the pivot table name\n */\n getTable(): string {\n return this.table;\n }\n\n /**\n * Get the foreign pivot key name\n */\n getForeignPivotKeyName(): string {\n return this.foreignPivotKey;\n }\n\n /**\n * Get the related pivot key name\n */\n getRelatedPivotKeyName(): string {\n return this.relatedPivotKey;\n }\n\n /**\n * Get the parent key name\n */\n getParentKeyName(): string {\n return this.parentKey;\n }\n\n /**\n * Get the related key name\n */\n getRelatedKeyName(): string {\n return this.relatedKey;\n }\n\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AAK,MAMd,wBAAiC,CAC/B,OAAO,KAAK,gBAMd,wBAAiC,CAC/B,OAAO,KAAK,gBAMd,kBAA2B,CACzB,OAAO,KAAK,UAMd,mBAA4B,CAC1B,OAAO,KAAK,WAMd,iBAA0B,CACxB,OAAO,KAAK"}
|
|
1
|
+
{"version":3,"file":"BelongsToMany.mjs","names":[],"sources":["../../../../src/Database/Ensemble/Relations/BelongsToMany.ts"],"sourcesContent":["/**\n * BelongsToMany Relationship\n *\n * Represents a many-to-many relationship\n */\n\nimport { Ensemble } from '@/Database/Ensemble/Ensemble';\nimport { EnsembleBuilder } from '@/Database/Ensemble/EnsembleBuilder';\nimport { EnsembleCollection } from '@/Database/Ensemble/EnsembleCollection';\nimport { Relation } from './Relation';\n\nexport class BelongsToMany<TRelated extends Ensemble, TParent extends Ensemble> extends Relation<TRelated, TParent> {\n /**\n * The intermediate table for the relation\n */\n protected table: string;\n\n /**\n * The foreign key of the parent model\n */\n protected foreignPivotKey: string;\n\n /**\n * The associated key of the relation\n */\n protected relatedPivotKey: string;\n\n /**\n * The parent key of the relationship\n */\n protected parentKey: string;\n\n /**\n * The related key of the relationship\n */\n protected relatedKey: string;\n\n /**\n * The name of the relationship\n */\n protected relationName: string;\n\n /**\n * The pivot table columns to retrieve\n */\n protected pivotColumns: string[] = [];\n\n /**\n * Any pivot table restrictions\n */\n protected pivotWheres: Array<{ column: string; operator?: string; value?: any; boolean: string }> = [];\n\n /**\n * The pivot table values to attach\n */\n protected pivotValues: Record<string, any>[] = [];\n\n /**\n * Whether we are using timestamps on the pivot table\n */\n protected usingTimestamps: boolean = false;\n\n /**\n * The custom pivot table model\n */\n protected using?: any;\n\n /**\n * The name of the \"created at\" column\n */\n protected pivotCreatedAt?: string;\n\n /**\n * The name of the \"updated at\" column\n */\n protected pivotUpdatedAt?: string;\n\n /**\n * The name of the accessor to use for the pivot relationship\n */\n protected accessor: string = 'pivot';\n\n /**\n * Create a new belongs to many relationship instance\n */\n constructor(\n query: EnsembleBuilder<TRelated>,\n parent: TParent,\n table: string,\n foreignPivotKey: string,\n relatedPivotKey: string,\n parentKey: string,\n relatedKey: string,\n relationName?: string\n ) {\n super(query, parent);\n this.table = table;\n this.foreignPivotKey = foreignPivotKey;\n this.relatedPivotKey = relatedPivotKey;\n this.parentKey = parentKey;\n this.relatedKey = relatedKey;\n this.relationName = relationName || '';\n this.initializeRelation();\n }\n\n /**\n * Set the base constraints on the relation query\n */\n addConstraints(): void {\n this.performJoin();\n\n if (Relation['constraints']) {\n this.addWhereConstraints();\n }\n }\n\n /**\n * Set the join clause for the relation query\n */\n protected performJoin(query?: EnsembleBuilder<TRelated>): void {\n query = query || this.query;\n\n // Join the pivot table on the related key\n query.join(this.table, `${this.getQualifiedRelatedKeyName()}`, '=', `${this.getQualifiedRelatedPivotKeyName()}`);\n }\n\n /**\n * Set the where clause for the relation query\n */\n protected addWhereConstraints(): void {\n const parentKeyValue = this.parent.getAttribute(this.parentKey);\n\n // Only add constraint if parent key value exists\n if (parentKeyValue !== null && parentKeyValue !== undefined) {\n this.query.where(this.getQualifiedForeignPivotKeyName(), '=', parentKeyValue);\n }\n }\n\n /**\n * Set the constraints for an eager load of the relation\n */\n addEagerConstraints(models: TParent[]): void {\n const keys = this.getKeys(models, this.parentKey);\n this.query.whereIn(this.getQualifiedForeignPivotKeyName(), keys);\n }\n\n /**\n * Initialize the relation on a set of models\n */\n initRelation(models: TParent[], relation: string): TParent[] {\n for (const model of models) {\n model.setRelation(relation, new EnsembleCollection<TRelated>());\n }\n\n return models;\n }\n\n /**\n * Match the eagerly loaded results to their parents\n */\n match(models: TParent[], results: EnsembleCollection<TRelated>, relation: string): TParent[] {\n const dictionary = this.buildDictionary(results);\n\n for (const model of models) {\n const key = model.getAttribute(this.parentKey);\n\n if (key !== null && key !== undefined && dictionary[key]) {\n model.setRelation(relation, new EnsembleCollection<TRelated>(dictionary[key]));\n }\n }\n\n return models;\n }\n\n /**\n * Build model dictionary keyed by the relation's foreign key\n */\n protected buildDictionary(results: EnsembleCollection<TRelated>): Record<any, TRelated[]> {\n const dictionary: Record<any, TRelated[]> = {};\n\n for (const result of results) {\n const pivotAttributes = this.migratePivotAttributes(result);\n const key = pivotAttributes[this.foreignPivotKey];\n\n if (key !== null && key !== undefined) {\n if (!dictionary[key]) {\n dictionary[key] = [];\n }\n dictionary[key].push(result);\n }\n }\n\n return dictionary;\n }\n\n /**\n * Get the results of the relationship\n */\n async getResults(): Promise<TRelated[]> {\n const parentKey = this.parent.getAttribute(this.parentKey);\n\n if (!parentKey) {\n return [];\n }\n\n return this.get();\n }\n\n /**\n * Execute the query and get the models\n */\n async get(): Promise<TRelated[]> {\n this.ensureConstraints();\n\n const builder = this.query.addSelect(...this.shouldSelect());\n\n const models = await builder.get();\n\n this.hydratePivotRelation(models);\n\n return models;\n }\n\n /**\n * Get the select columns for the relation query\n */\n protected shouldSelect(columns: string[] = ['*']): string[] {\n if (columns.length === 1 && columns[0] === '*') {\n columns = [`${this.related.getTable()}.*`];\n }\n\n return [...columns, ...this.aliasedPivotColumns()];\n }\n\n /**\n * Get the pivot columns for the relation\n */\n protected aliasedPivotColumns(): string[] {\n const defaults = [this.foreignPivotKey, this.relatedPivotKey];\n const columns = [...defaults, ...this.pivotColumns];\n\n return columns.map((column) => {\n return `${this.table}.${column} as pivot_${column}`;\n });\n }\n\n /**\n * Hydrate the pivot relationship on the models\n */\n protected hydratePivotRelation(models: TRelated[]): void {\n for (const model of models) {\n const pivot = this.migratePivotAttributes(model);\n model.setRelation(this.accessor, pivot);\n }\n }\n\n /**\n * Migrate the pivot attributes from the model to a pivot model\n */\n protected migratePivotAttributes(model: TRelated): Record<string, any> {\n const values: Record<string, any> = {};\n\n // Extract all pivot_* attributes\n const attributes = (model as any).attributes || {};\n for (const [key, value] of Object.entries(attributes)) {\n if (key.startsWith('pivot_')) {\n const pivotKey = key.substring(6); // Remove 'pivot_' prefix\n values[pivotKey] = value;\n delete (model as any).attributes[key];\n }\n }\n\n return values;\n }\n\n /**\n * Get the fully qualified foreign key for the relation\n */\n protected getQualifiedForeignPivotKeyName(): string {\n return `${this.table}.${this.foreignPivotKey}`;\n }\n\n /**\n * Get the fully qualified \"related key\" for the relation\n */\n protected getQualifiedRelatedPivotKeyName(): string {\n return `${this.table}.${this.relatedPivotKey}`;\n }\n\n /**\n * Get the fully qualified parent key name\n */\n protected getQualifiedParentKeyName(): string {\n return `${this.parent.getTable()}.${this.parentKey}`;\n }\n\n /**\n * Get the fully qualified related key name\n */\n protected getQualifiedRelatedKeyName(): string {\n return `${this.related.getTable()}.${this.relatedKey}`;\n }\n\n /**\n * Specify the pivot table columns to retrieve\n */\n withPivot(...columns: string[]): this {\n this.pivotColumns = [...this.pivotColumns, ...columns];\n\n return this;\n }\n\n /**\n * Indicate that the pivot table has timestamps\n */\n withTimestamps(createdAt?: string, updatedAt?: string): this {\n this.usingTimestamps = true;\n\n this.pivotCreatedAt = createdAt || 'created_at';\n this.pivotUpdatedAt = updatedAt || 'updated_at';\n\n return this.withPivot(this.pivotCreatedAt, this.pivotUpdatedAt);\n }\n\n /**\n * Set a where clause for the pivot table\n */\n wherePivot(column: string, operator?: any, value?: any): this {\n if (arguments.length === 2) {\n value = operator;\n operator = '=';\n }\n\n this.pivotWheres.push({\n column: `${this.table}.${column}`,\n operator,\n value,\n boolean: 'and',\n });\n\n return this.query.where(`${this.table}.${column}`, operator, value) as any;\n }\n\n /**\n * Set a \"where in\" clause for the pivot table\n */\n wherePivotIn(column: string, values: any[]): this {\n return this.query.whereIn(`${this.table}.${column}`, values) as any;\n }\n\n /**\n * Set a \"where not in\" clause for the pivot table\n */\n wherePivotNotIn(column: string, values: any[]): this {\n return this.query.whereNotIn(`${this.table}.${column}`, values) as any;\n }\n\n /**\n * Set a \"where null\" clause for the pivot table\n */\n wherePivotNull(column: string): this {\n return this.query.whereNull(`${this.table}.${column}`) as any;\n }\n\n /**\n * Set a \"where not null\" clause for the pivot table\n */\n wherePivotNotNull(column: string): this {\n return this.query.whereNotNull(`${this.table}.${column}`) as any;\n }\n\n /**\n * Set an \"or where\" clause for the pivot table\n */\n orWherePivot(column: string, operator?: any, value?: any): this {\n if (arguments.length === 2) {\n value = operator;\n operator = '=';\n }\n\n return this.query.orWhere(`${this.table}.${column}`, operator, value) as any;\n }\n\n /**\n * Attach models to the parent\n */\n async attach(ids: any | any[], attributes: Record<string, any> = {}): Promise<void> {\n const records = this.formatAttachRecords(this.parseIds(ids), attributes);\n\n if (records.length === 0) {\n return;\n }\n\n const connection = this.parent.getConnection();\n await connection.table(this.table).insert(records);\n }\n\n /**\n * Detach models from the parent\n */\n async detach(ids?: any | any[]): Promise<number> {\n const connection = this.parent.getConnection();\n let query = connection.table(this.table).where(this.foreignPivotKey, '=', this.parent.getAttribute(this.parentKey));\n\n if (ids !== undefined) {\n const parsedIds = this.parseIds(ids);\n query = query.whereIn(this.relatedPivotKey, parsedIds);\n }\n\n return await query.delete();\n }\n\n /**\n * Sync the intermediate tables with a list of IDs\n */\n async sync(ids: any | any[] | Record<number | string, Record<string, any>>): Promise<{\n attached: any[];\n detached: any[];\n updated: any[];\n }> {\n const changes = {\n attached: [] as any[],\n detached: [] as any[],\n updated: [] as any[],\n };\n\n const current = await this.getCurrentlyAttachedPivots();\n const records = this.formatRecordsList(this.parseIds(ids));\n\n const detach = current.filter((id) => !records.some((record) => record.id === id));\n\n if (detach.length > 0) {\n await this.detach(detach);\n changes.detached = detach;\n }\n\n changes.attached = await this.attachNew(records, current);\n changes.updated = await this.updateExisting(records, current);\n\n return changes;\n }\n\n /**\n * Sync without detaching\n */\n async syncWithoutDetaching(ids: any | any[] | Record<number | string, Record<string, any>>): Promise<{\n attached: any[];\n updated: any[];\n }> {\n const changes = {\n attached: [] as any[],\n updated: [] as any[],\n };\n\n const current = await this.getCurrentlyAttachedPivots();\n const records = this.formatRecordsList(this.parseIds(ids));\n\n changes.attached = await this.attachNew(records, current);\n changes.updated = await this.updateExisting(records, current);\n\n return changes;\n }\n\n /**\n * Toggle models from the parent\n */\n async toggle(ids: any | any[]): Promise<{\n attached: any[];\n detached: any[];\n }> {\n const changes = {\n attached: [] as any[],\n detached: [] as any[],\n };\n\n const parsedIds = this.parseIds(ids);\n const current = await this.getCurrentlyAttachedPivots();\n\n const detach = parsedIds.filter((id) => current.includes(id));\n const attach = parsedIds.filter((id) => !current.includes(id));\n\n if (detach.length > 0) {\n await this.detach(detach);\n changes.detached = detach;\n }\n\n if (attach.length > 0) {\n await this.attach(attach);\n changes.attached = attach;\n }\n\n return changes;\n }\n\n /**\n * Update an existing pivot record on the table\n */\n async updateExistingPivot(id: any, attributes: Record<string, any>): Promise<number> {\n if (this.usingTimestamps && this.pivotUpdatedAt) {\n attributes[this.pivotUpdatedAt] = new Date();\n }\n\n const connection = this.parent.getConnection();\n return await connection\n .table(this.table)\n .where(this.foreignPivotKey, '=', this.parent.getAttribute(this.parentKey))\n .where(this.relatedPivotKey, '=', id)\n .update(attributes);\n }\n\n /**\n * Get the currently attached pivot IDs\n */\n protected async getCurrentlyAttachedPivots(): Promise<any[]> {\n const connection = this.parent.getConnection();\n const results = await connection\n .table(this.table)\n .where(this.foreignPivotKey, '=', this.parent.getAttribute(this.parentKey))\n .pluck(this.relatedPivotKey);\n\n return results;\n }\n\n /**\n * Attach new records\n */\n protected async attachNew(\n records: Array<{ id: any; attributes: Record<string, any> }>,\n current: any[]\n ): Promise<any[]> {\n const newRecords = records.filter((record) => !current.includes(record.id));\n\n if (newRecords.length === 0) {\n return [];\n }\n\n await this.attach(\n newRecords.map((r) => r.id),\n newRecords[0]?.attributes || {}\n );\n\n return newRecords.map((r) => r.id);\n }\n\n /**\n * Update existing records\n */\n protected async updateExisting(\n records: Array<{ id: any; attributes: Record<string, any> }>,\n current: any[]\n ): Promise<any[]> {\n const updated: any[] = [];\n\n for (const record of records) {\n if (current.includes(record.id) && Object.keys(record.attributes).length > 0) {\n await this.updateExistingPivot(record.id, record.attributes);\n updated.push(record.id);\n }\n }\n\n return updated;\n }\n\n /**\n * Format the records for attaching\n */\n protected formatAttachRecords(ids: any[], attributes: Record<string, any>): Record<string, any>[] {\n const records: Record<string, any>[] = [];\n const hasTimestamps = this.usingTimestamps;\n\n for (const id of ids) {\n const record: Record<string, any> = {\n [this.foreignPivotKey]: this.parent.getAttribute(this.parentKey),\n [this.relatedPivotKey]: id,\n ...attributes,\n };\n\n if (hasTimestamps) {\n const now = new Date();\n if (this.pivotCreatedAt) {\n record[this.pivotCreatedAt] = now;\n }\n if (this.pivotUpdatedAt) {\n record[this.pivotUpdatedAt] = now;\n }\n }\n\n records.push(record);\n }\n\n return records;\n }\n\n /**\n * Format the sync records\n */\n protected formatRecordsList(ids: any[]): Array<{ id: any; attributes: Record<string, any> }> {\n return ids.map((id) => {\n if (typeof id === 'object' && !Array.isArray(id)) {\n const { id: recordId, ...attributes } = id;\n return { id: recordId, attributes };\n }\n return { id, attributes: {} };\n });\n }\n\n /**\n * Parse the IDs from the given value\n */\n protected parseIds(value: any): any[] {\n if (value instanceof EnsembleCollection) {\n return value.modelKeys();\n }\n\n if (Array.isArray(value)) {\n return value;\n }\n\n if (typeof value === 'object' && value !== null) {\n // Handle {id: attributes} format\n return Object.keys(value).map((key) => {\n const id = isNaN(Number(key)) ? key : Number(key);\n return { id, ...value[key] };\n });\n }\n\n return [value];\n }\n\n /**\n * Get the name of the pivot accessor\n */\n getPivotAccessor(): string {\n return this.accessor;\n }\n\n /**\n * Set the name of the pivot accessor\n */\n as(accessor: string): this {\n this.accessor = accessor;\n return this;\n }\n\n /**\n * Get the pivot table name\n */\n getTable(): string {\n return this.table;\n }\n\n /**\n * Get the foreign pivot key name\n */\n getForeignPivotKeyName(): string {\n return this.foreignPivotKey;\n }\n\n /**\n * Get the related pivot key name\n */\n getRelatedPivotKeyName(): string {\n return this.relatedPivotKey;\n }\n\n /**\n * Get the parent key name\n */\n getParentKeyName(): string {\n return this.parentKey;\n }\n\n /**\n * Get the related key name\n */\n getRelatedKeyName(): string {\n return this.relatedKey;\n }\n\n /**\n * Get the relationship name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AAiC,CAC/B,OAAO,KAAK,gBAMd,kBAA2B,CACzB,OAAO,KAAK,UAMd,mBAA4B,CAC1B,OAAO,KAAK,WAMd,iBAA0B,CACxB,OAAO,KAAK"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HasMany.mjs","names":[],"sources":["../../../../src/Database/Ensemble/Relations/HasMany.ts"],"sourcesContent":["/**\n * HasMany Relationship\n *\n * Represents a one-to-many relationship\n */\n\nimport { Ensemble } from '@/Database/Ensemble/Ensemble';\nimport { EnsembleBuilder } from '@/Database/Ensemble/EnsembleBuilder';\nimport { EnsembleCollection } from '@/Database/Ensemble/EnsembleCollection';\nimport { Relation } from './Relation';\n\nexport class HasMany<TRelated extends Ensemble, TParent extends Ensemble> extends Relation<TRelated, TParent> {\n /**\n * The foreign key of the parent model\n */\n protected foreignKey: string;\n\n /**\n * The local key of the parent model\n */\n protected localKey: string;\n\n /**\n * Create a new has many relationship instance\n */\n constructor(query: EnsembleBuilder<TRelated>, parent: TParent, foreignKey: string, localKey: string) {\n super(query, parent);\n this.foreignKey = foreignKey;\n this.localKey = localKey;\n this.initializeRelation();\n }\n\n /**\n * Set the base constraints on the relation query\n */\n addConstraints(): void {\n if (Relation['constraints']) {\n const parentKey = this.getParentKey();\n\n // Only add constraint if parent key exists\n if (parentKey !== null && parentKey !== undefined) {\n this.query.where(this.foreignKey, '=', parentKey);\n }\n }\n }\n\n /**\n * Set the constraints for an eager load of the relation\n */\n addEagerConstraints(models: TParent[]): void {\n const keys = this.getKeys(models, this.localKey);\n this.query.whereIn(this.foreignKey, keys);\n }\n\n /**\n * Initialize the relation on a set of models\n */\n initRelation(models: TParent[], relation: string): TParent[] {\n for (const model of models) {\n model.setRelation(relation, new EnsembleCollection<TRelated>());\n }\n\n return models;\n }\n\n /**\n * Match the eagerly loaded results to their parents\n */\n match(models: TParent[], results: EnsembleCollection<TRelated>, relation: string): TParent[] {\n const dictionary = this.buildDictionary(results);\n\n for (const model of models) {\n const key = model.getAttribute(this.localKey);\n\n if (key !== null && key !== undefined && dictionary[key]) {\n model.setRelation(relation, new EnsembleCollection<TRelated>(dictionary[key]));\n }\n }\n\n return models;\n }\n\n /**\n * Build model dictionary keyed by the relation's foreign key\n */\n protected buildDictionary(results: EnsembleCollection<TRelated>): Record<any, TRelated[]> {\n const dictionary: Record<any, TRelated[]> = {};\n\n for (const result of results) {\n const key = result.getAttribute(this.foreignKey);\n\n if (key !== null && key !== undefined) {\n if (!dictionary[key]) {\n dictionary[key] = [];\n }\n dictionary[key].push(result);\n }\n }\n\n return dictionary;\n }\n\n /**\n * Get the results of the relationship\n */\n async getResults(): Promise<TRelated[]> {\n if (!this.getParentKey()) {\n return [];\n }\n\n this.ensureConstraints();\n return this.query.get();\n }\n\n /**\n * Get the key value of the parent's local key\n */\n protected getParentKey(): any {\n return this.parent.getAttribute(this.localKey);\n }\n\n /**\n * Get the foreign key for the relationship\n */\n getForeignKeyName(): string {\n return this.foreignKey;\n }\n\n /**\n * Get the local key for the relationship\n */\n getLocalKeyName(): string {\n return this.localKey;\n }\n\n /**\n * Make a new related instance\n */\n make(attributes: Record<string, any> = {}): TRelated {\n return this.related.newInstance(attributes);\n }\n\n /**\n * Create a new instance of the related model\n */\n async create(attributes: Record<string, any> = {}): Promise<TRelated> {\n const instance = this.make(attributes);\n\n instance.setAttribute(this.foreignKey, this.getParentKey());\n\n await instance.save();\n\n return instance;\n }\n\n /**\n * Create an array of new instances of the related model\n */\n async createMany(records: Record<string, any>[]): Promise<TRelated[]> {\n const instances: TRelated[] = [];\n\n for (const record of records) {\n instances.push(await this.create(record));\n }\n\n return instances;\n }\n\n /**\n * Create a new instance and set the foreign key\n */\n async save(model: TRelated): Promise<TRelated> {\n model.setAttribute(this.foreignKey, this.getParentKey());\n\n await model.save();\n\n return model;\n }\n\n /**\n * Save multiple models with the foreign key set\n */\n async saveMany(models: TRelated[]): Promise<TRelated[]> {\n for (const model of models) {\n await this.save(model);\n }\n\n return models;\n }\n\n /**\n * Find a related model by its primary key\n */\n async find(id: any): Promise<TRelated | null> {\n return this.query.where(this.related.getKeyName(), '=', id).first();\n }\n\n /**\n * Find multiple related models by their primary keys\n */\n async findMany(ids: any[]): Promise<TRelated[]> {\n return this.query.whereIn(this.related.getKeyName(), ids).get();\n }\n\n /**\n * Find a related model by its primary key or throw an exception\n */\n async findOrFail(id: any): Promise<TRelated> {\n const result = await this.find(id);\n\n if (!result) {\n throw new Error(`Model not found with id: ${id}`);\n }\n\n return result;\n }\n\n /**\n * Get the first related model matching the attributes or create it\n */\n async firstOrCreate(attributes: Record<string, any>, values: Record<string, any> = {}): Promise<TRelated> {\n let query = this.query.clone();\n\n // Apply each attribute as a where clause\n for (const [key, value] of Object.entries(attributes)) {\n query = query.where(key, '=', value);\n }\n\n const instance = await query.first();\n\n if (instance) {\n return instance;\n }\n\n return this.create({ ...attributes, ...values });\n }\n\n /**\n * Update the parent model on the relationship\n */\n async update(attributes: Record<string, any>): Promise<number> {\n const updatedAtColumn = this.related.getUpdatedAtColumn();\n if (updatedAtColumn) {\n attributes[updatedAtColumn] = new Date();\n }\n\n return this.query.update(attributes);\n }\n}\n"],"mappings":"4JAQ4E,IACtC,CAEtC,IAAa,EAAb,cAAkF,CAA4B,CAI5G,WAKA,SAKA,YAAY,EAAkC,EAAiB,EAAoB,EAAkB,CACnG,MAAM,EAAO,EAAO,CACpB,KAAK,WAAa,EAClB,KAAK,SAAW,EAChB,KAAK,oBAAoB,CAM3B,gBAAuB,CACrB,GAAI,EAAS,YAAgB,CAC3B,IAAM,EAAY,KAAK,cAAc,CAGjC,GAAc,MAChB,KAAK,MAAM,MAAM,KAAK,WAAY,IAAK,EAAU,EAQvD,oBAAoB,EAAyB,CAC3C,IAAM,EAAO,KAAK,QAAQ,EAAQ,KAAK,SAAS,CAChD,KAAK,MAAM,QAAQ,KAAK,WAAY,EAAK,CAM3C,aAAa,EAAmB,EAA6B,CAC3D,IAAK,IAAM,KAAS,EAClB,EAAM,YAAY,EAAU,IAAI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AS,EAClB,MAAM,KAAK,KAAK,EAAM,CAGxB,OAAO,EAMT,MAAM,KAAK,EAAmC,CAC5C,OAAO,KAAK,MAAM,MAAM,KAAK,QAAQ,YAAY,CAAE,IAAK,EAAG,CAAC,OAAO,CAMrE,MAAM,SAAS,EAAiC,CAC9C,OAAO,KAAK,MAAM,QAAQ,KAAK,QAAQ,YAAY,CAAE,EAAI,CAAC,KAAK,CAMjE,MAAM,WAAW,EAA4B,CAC3C,IAAM,EAAS,MAAM,KAAK,KAAK,EAAG,CAElC,GAAI,CAAC,EACH,MAAU,MAAM,4BAA4B,IAAK,CAGnD,OAAO,EAMT,MAAM,cAAc,EAAiC,EAA8B,EAAE,CAAqB,CACxG,IAAI,EAAQ,KAAK,MAAM,OAAO,CAG9B,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,EAAW,CACnD,EAAQ,EAAM,MAAM,EAAK,IAAK,EAAM,CAStC,
|
|
1
|
+
{"version":3,"file":"HasMany.mjs","names":[],"sources":["../../../../src/Database/Ensemble/Relations/HasMany.ts"],"sourcesContent":["/**\n * HasMany Relationship\n *\n * Represents a one-to-many relationship\n */\n\nimport { Ensemble } from '@/Database/Ensemble/Ensemble';\nimport { EnsembleBuilder } from '@/Database/Ensemble/EnsembleBuilder';\nimport { EnsembleCollection } from '@/Database/Ensemble/EnsembleCollection';\nimport { Relation } from './Relation';\n\nexport class HasMany<TRelated extends Ensemble, TParent extends Ensemble> extends Relation<TRelated, TParent> {\n /**\n * The foreign key of the parent model\n */\n protected foreignKey: string;\n\n /**\n * The local key of the parent model\n */\n protected localKey: string;\n\n /**\n * Create a new has many relationship instance\n */\n constructor(query: EnsembleBuilder<TRelated>, parent: TParent, foreignKey: string, localKey: string) {\n super(query, parent);\n this.foreignKey = foreignKey;\n this.localKey = localKey;\n this.initializeRelation();\n }\n\n /**\n * Set the base constraints on the relation query\n */\n addConstraints(): void {\n if (Relation['constraints']) {\n const parentKey = this.getParentKey();\n\n // Only add constraint if parent key exists\n if (parentKey !== null && parentKey !== undefined) {\n this.query.where(this.foreignKey, '=', parentKey);\n }\n }\n }\n\n /**\n * Set the constraints for an eager load of the relation\n */\n addEagerConstraints(models: TParent[]): void {\n const keys = this.getKeys(models, this.localKey);\n this.query.whereIn(this.foreignKey, keys);\n }\n\n /**\n * Initialize the relation on a set of models\n */\n initRelation(models: TParent[], relation: string): TParent[] {\n for (const model of models) {\n model.setRelation(relation, new EnsembleCollection<TRelated>());\n }\n\n return models;\n }\n\n /**\n * Match the eagerly loaded results to their parents\n */\n match(models: TParent[], results: EnsembleCollection<TRelated>, relation: string): TParent[] {\n const dictionary = this.buildDictionary(results);\n\n for (const model of models) {\n const key = model.getAttribute(this.localKey);\n\n if (key !== null && key !== undefined && dictionary[key]) {\n model.setRelation(relation, new EnsembleCollection<TRelated>(dictionary[key]));\n }\n }\n\n return models;\n }\n\n /**\n * Build model dictionary keyed by the relation's foreign key\n */\n protected buildDictionary(results: EnsembleCollection<TRelated>): Record<any, TRelated[]> {\n const dictionary: Record<any, TRelated[]> = {};\n\n for (const result of results) {\n const key = result.getAttribute(this.foreignKey);\n\n if (key !== null && key !== undefined) {\n if (!dictionary[key]) {\n dictionary[key] = [];\n }\n dictionary[key].push(result);\n }\n }\n\n return dictionary;\n }\n\n /**\n * Get the results of the relationship\n */\n async getResults(): Promise<TRelated[]> {\n if (!this.getParentKey()) {\n return [];\n }\n\n this.ensureConstraints();\n return this.query.get();\n }\n\n /**\n * Get the key value of the parent's local key\n */\n protected getParentKey(): any {\n return this.parent.getAttribute(this.localKey);\n }\n\n /**\n * Get the foreign key for the relationship\n */\n getForeignKeyName(): string {\n return this.foreignKey;\n }\n\n /**\n * Get the local key for the relationship\n */\n getLocalKeyName(): string {\n return this.localKey;\n }\n\n /**\n * Make a new related instance\n */\n make(attributes: Record<string, any> = {}): TRelated {\n return this.related.newInstance(attributes);\n }\n\n /**\n * Create a new instance of the related model\n */\n async create(attributes: Record<string, any> = {}): Promise<TRelated> {\n const instance = this.make(attributes);\n\n instance.setAttribute(this.foreignKey, this.getParentKey());\n\n await instance.save();\n\n return instance;\n }\n\n /**\n * Create an array of new instances of the related model\n */\n async createMany(records: Record<string, any>[]): Promise<TRelated[]> {\n const instances: TRelated[] = [];\n\n for (const record of records) {\n instances.push(await this.create(record));\n }\n\n return instances;\n }\n\n /**\n * Create a new instance and set the foreign key\n */\n async save(model: TRelated): Promise<TRelated> {\n model.setAttribute(this.foreignKey, this.getParentKey());\n\n await model.save();\n\n return model;\n }\n\n /**\n * Save multiple models with the foreign key set\n */\n async saveMany(models: TRelated[]): Promise<TRelated[]> {\n for (const model of models) {\n await this.save(model);\n }\n\n return models;\n }\n\n /**\n * Find a related model by its primary key\n */\n async find(id: any): Promise<TRelated | null> {\n return this.query.where(this.related.getKeyName(), '=', id).first();\n }\n\n /**\n * Find multiple related models by their primary keys\n */\n async findMany(ids: any[]): Promise<TRelated[]> {\n return this.query.whereIn(this.related.getKeyName(), ids).get();\n }\n\n /**\n * Find a related model by its primary key or throw an exception\n */\n async findOrFail(id: any): Promise<TRelated> {\n const result = await this.find(id);\n\n if (!result) {\n throw new Error(`Model not found with id: ${id}`);\n }\n\n return result;\n }\n\n /**\n * Get the first related model matching the attributes or create it\n */\n async firstOrCreate(attributes: Record<string, any>, values: Record<string, any> = {}): Promise<TRelated> {\n let query = this.query.clone();\n\n // Apply each attribute as a where clause\n for (const [key, value] of Object.entries(attributes)) {\n query = query.where(key, '=', value);\n }\n\n const instance = await query.first();\n\n if (instance) {\n return instance;\n }\n\n return this.create({ ...attributes, ...values });\n }\n\n /**\n * Update the parent model on the relationship\n */\n async update(attributes: Record<string, any>): Promise<number> {\n const updatedAtColumn = this.related.getUpdatedAtColumn();\n if (updatedAtColumn) {\n attributes[updatedAtColumn] = new Date();\n }\n\n return this.query.update(attributes);\n }\n}\n"],"mappings":"4JAQ4E,IACtC,CAEtC,IAAa,EAAb,cAAkF,CAA4B,CAI5G,WAKA,SAKA,YAAY,EAAkC,EAAiB,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@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MorphTo.mjs","names":[],"sources":["../../../../src/Database/Ensemble/Relations/MorphTo.ts"],"sourcesContent":["/**\n * MorphTo Relationship\n *\n * Represents a polymorphic inverse relationship\n * Example: Comment belongs to Post or Video (commentable)\n */\n\nimport { Ensemble } from '@/Database/Ensemble/Ensemble';\nimport { EnsembleBuilder } from '@/Database/Ensemble/EnsembleBuilder';\nimport { EnsembleCollection } from '@/Database/Ensemble/EnsembleCollection';\nimport { MorphMap } from './MorphMap';\nimport { Relation } from './Relation';\n\nexport class MorphTo<TParent extends Ensemble> extends Relation<Ensemble, TParent> {\n /**\n * The foreign key of the parent model (e.g., 'commentable_id')\n */\n protected foreignKey: string;\n\n /**\n * The morph type column (e.g., 'commentable_type')\n */\n protected morphType: string;\n\n /**\n * The owner key on the related model\n */\n protected ownerKey: string;\n\n /**\n * The name of the relationship\n */\n protected relationName: string;\n\n /**\n * Dictionary of models grouped by type\n */\n protected dictionary: Map<string, Map<any, Ensemble>> = new Map();\n\n /**\n * Models loaded by type\n */\n protected models: Map<string, Ensemble[]> = new Map();\n\n /**\n * Create a new morph to relationship instance\n */\n constructor(\n query: EnsembleBuilder<Ensemble>,\n parent: TParent,\n foreignKey: string,\n morphType: string,\n ownerKey: string,\n relationName: string\n ) {\n super(query, parent);\n this.foreignKey = foreignKey;\n this.morphType = morphType;\n this.ownerKey = ownerKey;\n this.relationName = relationName;\n // Don't call initializeRelation() - MorphTo doesn't add constraints in constructor\n }\n\n /**\n * Set the base constraints on the relation query\n * MorphTo doesn't use base constraints - queries are built per type\n */\n addConstraints(): void {\n // MorphTo doesn't add constraints here\n // Constraints are added dynamically based on type\n }\n\n /**\n * Set the constraints for an eager load of the relation\n */\n addEagerConstraints(models: TParent[]): void {\n // Build dictionary grouped by type\n this.buildDictionary(models);\n }\n\n /**\n * Build dictionary of models grouped by morph type\n */\n protected buildDictionary(models: TParent[]): void {\n this.dictionary.clear();\n\n for (const model of models) {\n const type = model.getAttribute(this.morphType);\n const id = model.getAttribute(this.foreignKey);\n\n if (!type || id === null || id === undefined) {\n continue;\n }\n\n if (!this.dictionary.has(type)) {\n this.dictionary.set(type, new Map());\n }\n\n const typeDict = this.dictionary.get(type)!;\n typeDict.set(id, null as any); // Placeholder, will be replaced in match\n }\n }\n\n /**\n * Initialize the relation on a set of models\n */\n initRelation(models: TParent[], relation: string): TParent[] {\n for (const model of models) {\n model.setRelation(relation, null);\n }\n\n return models;\n }\n\n /**\n * Match the eagerly loaded results to their parents\n */\n match(models: TParent[], results: EnsembleCollection<Ensemble>, relation: string): TParent[] {\n // Match each model with its related parent\n for (const model of models) {\n const type = model.getAttribute(this.morphType);\n const id = model.getAttribute(this.foreignKey);\n\n if (!type || id === null || id === undefined) {\n model.setRelation(relation, null);\n continue;\n }\n\n const typeDict = this.dictionary.get(type);\n if (typeDict && typeDict.has(id)) {\n const related = typeDict.get(id);\n model.setRelation(relation, related || null);\n } else {\n model.setRelation(relation, null);\n }\n }\n\n return models;\n }\n\n /**\n * Get the eager loading results\n */\n async getEager(): Promise<Ensemble[]> {\n const allResults: Ensemble[] = [];\n\n for (const [type, ids] of this.dictionary.entries()) {\n const modelClass = MorphMap.getClass(type);\n\n if (!modelClass) {\n console.warn(`MorphTo: Unknown morph type \"${type}\". Did you forget to register it in MorphMap?`);\n continue;\n }\n\n const instance = new modelClass();\n const models = await instance.newQuery().whereIn(this.ownerKey, Array.from(ids.keys())).get();\n\n // Store in dictionary for matching\n for (const model of models) {\n const key = model.getAttribute(this.ownerKey);\n const typeDict = this.dictionary.get(type);\n if (typeDict && typeDict.has(key)) {\n typeDict.set(key, model);\n }\n }\n\n allResults.push(...models);\n }\n\n return allResults;\n }\n\n /**\n * Get the results of the relationship\n */\n async getResults(): Promise<Ensemble | null> {\n const type = this.parent.getAttribute(this.morphType);\n const id = this.parent.getAttribute(this.foreignKey);\n\n if (!type || id === null || id === undefined) {\n return null;\n }\n\n const modelClass = MorphMap.getClass(type);\n\n if (!modelClass) {\n console.warn(`MorphTo: Unknown morph type \"${type}\". Did you forget to register it in MorphMap?`);\n return null;\n }\n\n const instance = new modelClass();\n return instance.newQuery().where(this.ownerKey, '=', id).first();\n }\n\n /**\n * Associate the model instance to the parent model\n */\n associate(model: Ensemble | null): this {\n if (model === null) {\n return this.dissociate();\n }\n\n this.parent.setAttribute(this.foreignKey, model.getAttribute(this.ownerKey));\n this.parent.setAttribute(this.morphType, MorphMap.getMorphedModel(model));\n this.parent.setRelation(this.relationName, model);\n\n return this;\n }\n\n /**\n * Dissociate the model from the parent\n */\n dissociate(): this {\n this.parent.setAttribute(this.foreignKey, null);\n this.parent.setAttribute(this.morphType, null);\n this.parent.setRelation(this.relationName, null);\n\n return this;\n }\n\n /**\n * Get the foreign key value\n */\n protected getForeignKeyValue(): any {\n return this.parent.getAttribute(this.foreignKey);\n }\n\n /**\n * Get the morph type value\n */\n protected getMorphTypeValue(): string | null {\n return this.parent.getAttribute(this.morphType);\n }\n\n /**\n * Get the foreign key for the relationship\n */\n getForeignKeyName(): string {\n return this.foreignKey;\n }\n\n /**\n * Get the morph type for the relationship\n */\n getMorphType(): string {\n return this.morphType;\n }\n\n /**\n * Get the owner key for the relationship\n */\n getOwnerKeyName(): string {\n return this.ownerKey;\n }\n}\n"],"mappings":"sPAUsC,IACA,CAEzB,EAAb,cAAuD,CAA4B,CAIjF,WAKA,UAKA,SAKA,aAKA,WAAwD,IAAI,IAK5D,OAA4C,IAAI,IAKhD,YACE,EACA,EACA,EACA,EACA,EACA,EACA,CACA,MAAM,EAAO,EAAO,CACpB,KAAK,WAAa,EAClB,KAAK,UAAY,EACjB,KAAK,SAAW,EAChB,KAAK,aAAe,EAQtB,gBAAuB,EAQvB,oBAAoB,EAAyB,CAE3C,KAAK,gBAAgB,EAAO,CAM9B,gBAA0B,EAAyB,CACjD,KAAK,WAAW,OAAO,CAEvB,IAAK,IAAM,KAAS,EAAQ,CAC1B,IAAM,EAAO,EAAM,aAAa,KAAK,UAAU,CACzC,EAAK,EAAM,aAAa,KAAK,WAAW,CAE1C,CAAC,GAAQ,GAAO,OAIf,KAAK,WAAW,IAAI,EAAK,EAC5B,KAAK,WAAW,IAAI,EAAM,IAAI,IAAM,
|
|
1
|
+
{"version":3,"file":"MorphTo.mjs","names":[],"sources":["../../../../src/Database/Ensemble/Relations/MorphTo.ts"],"sourcesContent":["/**\n * MorphTo Relationship\n *\n * Represents a polymorphic inverse relationship\n * Example: Comment belongs to Post or Video (commentable)\n */\n\nimport { Ensemble } from '@/Database/Ensemble/Ensemble';\nimport { EnsembleBuilder } from '@/Database/Ensemble/EnsembleBuilder';\nimport { EnsembleCollection } from '@/Database/Ensemble/EnsembleCollection';\nimport { MorphMap } from './MorphMap';\nimport { Relation } from './Relation';\n\nexport class MorphTo<TParent extends Ensemble> extends Relation<Ensemble, TParent> {\n /**\n * The foreign key of the parent model (e.g., 'commentable_id')\n */\n protected foreignKey: string;\n\n /**\n * The morph type column (e.g., 'commentable_type')\n */\n protected morphType: string;\n\n /**\n * The owner key on the related model\n */\n protected ownerKey: string;\n\n /**\n * The name of the relationship\n */\n protected relationName: string;\n\n /**\n * Dictionary of models grouped by type\n */\n protected dictionary: Map<string, Map<any, Ensemble>> = new Map();\n\n /**\n * Models loaded by type\n */\n protected models: Map<string, Ensemble[]> = new Map();\n\n /**\n * Create a new morph to relationship instance\n */\n constructor(\n query: EnsembleBuilder<Ensemble>,\n parent: TParent,\n foreignKey: string,\n morphType: string,\n ownerKey: string,\n relationName: string\n ) {\n super(query, parent);\n this.foreignKey = foreignKey;\n this.morphType = morphType;\n this.ownerKey = ownerKey;\n this.relationName = relationName;\n // Don't call initializeRelation() - MorphTo doesn't add constraints in constructor\n }\n\n /**\n * Set the base constraints on the relation query\n * MorphTo doesn't use base constraints - queries are built per type\n */\n addConstraints(): void {\n // MorphTo doesn't add constraints here\n // Constraints are added dynamically based on type\n }\n\n /**\n * Set the constraints for an eager load of the relation\n */\n addEagerConstraints(models: TParent[]): void {\n // Build dictionary grouped by type\n this.buildDictionary(models);\n }\n\n /**\n * Build dictionary of models grouped by morph type\n */\n protected buildDictionary(models: TParent[]): void {\n this.dictionary.clear();\n\n for (const model of models) {\n const type = model.getAttribute(this.morphType);\n const id = model.getAttribute(this.foreignKey);\n\n if (!type || id === null || id === undefined) {\n continue;\n }\n\n if (!this.dictionary.has(type)) {\n this.dictionary.set(type, new Map());\n }\n\n const typeDict = this.dictionary.get(type)!;\n typeDict.set(id, null as any); // Placeholder, will be replaced in match\n }\n }\n\n /**\n * Initialize the relation on a set of models\n */\n initRelation(models: TParent[], relation: string): TParent[] {\n for (const model of models) {\n model.setRelation(relation, null);\n }\n\n return models;\n }\n\n /**\n * Match the eagerly loaded results to their parents\n */\n match(models: TParent[], results: EnsembleCollection<Ensemble>, relation: string): TParent[] {\n // Match each model with its related parent\n for (const model of models) {\n const type = model.getAttribute(this.morphType);\n const id = model.getAttribute(this.foreignKey);\n\n if (!type || id === null || id === undefined) {\n model.setRelation(relation, null);\n continue;\n }\n\n const typeDict = this.dictionary.get(type);\n if (typeDict && typeDict.has(id)) {\n const related = typeDict.get(id);\n model.setRelation(relation, related || null);\n } else {\n model.setRelation(relation, null);\n }\n }\n\n return models;\n }\n\n /**\n * Get the eager loading results\n */\n async getEager(): Promise<Ensemble[]> {\n const allResults: Ensemble[] = [];\n\n for (const [type, ids] of this.dictionary.entries()) {\n const modelClass = MorphMap.getClass(type);\n\n if (!modelClass) {\n console.warn(`MorphTo: Unknown morph type \"${type}\". Did you forget to register it in MorphMap?`);\n continue;\n }\n\n const instance = new modelClass();\n const models = await instance.newQuery().whereIn(this.ownerKey, Array.from(ids.keys())).get();\n\n // Store in dictionary for matching\n for (const model of models) {\n const key = model.getAttribute(this.ownerKey);\n const typeDict = this.dictionary.get(type);\n if (typeDict && typeDict.has(key)) {\n typeDict.set(key, model);\n }\n }\n\n allResults.push(...models);\n }\n\n return allResults;\n }\n\n /**\n * Get the results of the relationship\n */\n async getResults(): Promise<Ensemble | null> {\n const type = this.parent.getAttribute(this.morphType);\n const id = this.parent.getAttribute(this.foreignKey);\n\n if (!type || id === null || id === undefined) {\n return null;\n }\n\n const modelClass = MorphMap.getClass(type);\n\n if (!modelClass) {\n console.warn(`MorphTo: Unknown morph type \"${type}\". Did you forget to register it in MorphMap?`);\n return null;\n }\n\n const instance = new modelClass();\n return instance.newQuery().where(this.ownerKey, '=', id).first();\n }\n\n /**\n * Associate the model instance to the parent model\n */\n associate(model: Ensemble | null): this {\n if (model === null) {\n return this.dissociate();\n }\n\n this.parent.setAttribute(this.foreignKey, model.getAttribute(this.ownerKey));\n this.parent.setAttribute(this.morphType, MorphMap.getMorphedModel(model));\n this.parent.setRelation(this.relationName, model);\n\n return this;\n }\n\n /**\n * Dissociate the model from the parent\n */\n dissociate(): this {\n this.parent.setAttribute(this.foreignKey, null);\n this.parent.setAttribute(this.morphType, null);\n this.parent.setRelation(this.relationName, null);\n\n return this;\n }\n\n /**\n * Get the foreign key value\n */\n protected getForeignKeyValue(): any {\n return this.parent.getAttribute(this.foreignKey);\n }\n\n /**\n * Get the morph type value\n */\n protected getMorphTypeValue(): string | null {\n return this.parent.getAttribute(this.morphType);\n }\n\n /**\n * Get the foreign key for the relationship\n */\n getForeignKeyName(): string {\n return this.foreignKey;\n }\n\n /**\n * Get the morph type for the relationship\n */\n getMorphType(): string {\n return this.morphType;\n }\n\n /**\n * Get the owner key for the relationship\n */\n getOwnerKeyName(): string {\n return this.ownerKey;\n }\n}\n"],"mappings":"sPAUsC,IACA,CAEzB,EAAb,cAAuD,CAA4B,CAIjF,WAKA,UAKA,SAKA,aAKA,WAAwD,IAAI,IAK5D,OAA4C,IAAI,IAKhD,YACE,EACA,EACA,EACA,EACA,EACA,EACA,CACA,MAAM,EAAO,EAAO,CACpB,KAAK,WAAa,EAClB,KAAK,UAAY,EACjB,KAAK,SAAW,EAChB,KAAK,aAAe,EAQtB,gBAAuB,EAQvB,oBAAoB,EAAyB,CAE3C,KAAK,gBAAgB,EA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\n *\n * Represents a polymorphic many-to-many relationship from the parent side\n * Example: Post has many Tags (where Tag can belong to many types via taggables table)\n */\n\nimport { Ensemble } from '@/Database/Ensemble/Ensemble';\nimport { EnsembleBuilder } from '@/Database/Ensemble/EnsembleBuilder';\nimport { BelongsToMany } from './BelongsToMany';\nimport { MorphMap } from './MorphMap';\n\nexport class MorphToMany<TRelated extends Ensemble, TParent extends Ensemble> extends BelongsToMany<TRelated, TParent> {\n /**\n * The morph type column (e.g., 'taggable_type')\n */\n protected morphType: string;\n\n /**\n * The morph class name or alias\n */\n protected morphClass: string;\n\n /**\n * Whether this is the inverse of the relation\n */\n protected inverse: boolean;\n\n /**\n * Create a new morph to many relationship instance\n */\n constructor(\n query: EnsembleBuilder<TRelated>,\n parent: TParent,\n name: string,\n table: string,\n foreignPivotKey: string,\n relatedPivotKey: string,\n morphType: string,\n parentKey: string,\n relatedKey: string,\n relationName?: string,\n inverse: boolean = false\n ) {\n super(query, parent, table, foreignPivotKey, relatedPivotKey, parentKey, relatedKey, relationName);\n\n this.morphType = morphType;\n this.morphClass = this.getMorphClass();\n this.inverse = inverse;\n }\n\n /**\n * Set the join clause for the relation query\n * Adds the morph type constraint\n */\n protected performJoin(query?: EnsembleBuilder<TRelated>): void {\n query = query || this.query;\n\n // Join the pivot table with morph type constraint\n query\n .join(this.table, `${this.getQualifiedRelatedKeyName()}`, '=', `${this.getQualifiedRelatedPivotKeyName()}`)\n .where(`${this.table}.${this.morphType}`, '=', this.morphClass);\n }\n\n /**\n * Set the where clause for eager loading\n */\n protected addWhereConstraints(): void {\n const parentKeyValue = this.parent.getAttribute(this.parentKey);\n\n // Only add constraint if parent key value exists\n if (parentKeyValue !== null && parentKeyValue !== undefined) {\n this.query.where(this.getQualifiedForeignPivotKeyName(), '=', parentKeyValue);\n }\n }\n\n /**\n * Get the morph class for the parent during initialization\n */\n protected getMorphClass(): string {\n if (this.inverse) {\n // For inverse relations, we don't set the morph class on parent\n // It will be set per attach/sync operation\n return '';\n }\n\n return MorphMap.getMorphedModel(this.parent);\n }\n\n /**\n * Get the morph type name\n */\n getMorphType(): string {\n return this.morphType;\n }\n\n /**\n * Get the morph class value\n */\n getMorphClassValue(): string {\n return this.morphClass;\n }\n\n /**\n * Set the morph class (used for inverse relations)\n */\n setMorphClass(morphClass: string): this {\n this.morphClass = morphClass;\n return this;\n }\n\n /**\n * Attach models to the parent with morph type\n */\n async attach(ids: any | any[], attributes: Record<string, any> = {}, touch: boolean = true): Promise<void> {\n const idsArray = Array.isArray(ids) ? ids : [ids];\n const parentKey = this.parent.getAttribute(this.parentKey);\n\n if (!parentKey) {\n throw new Error('Parent key must be set before attaching');\n }\n\n const records = idsArray.map((id) => ({\n [this.foreignPivotKey]: parentKey,\n [this.relatedPivotKey]: id,\n [this.morphType]: this.morphClass,\n ...attributes,\n }));\n\n const connection = this.parent.getConnection();\n await connection.table(this.table).insert(records);\n }\n\n /**\n * Detach models from the parent with morph type constraint\n */\n async detach(ids?: any | any[]): Promise<number> {\n const query = this.newPivotQuery();\n const parentKey = this.parent.getAttribute(this.parentKey);\n\n if (!parentKey) {\n return 0;\n }\n\n query.where(this.foreignPivotKey, '=', parentKey).where(this.morphType, '=', this.morphClass);\n\n if (ids) {\n const idsArray = Array.isArray(ids) ? ids : [ids];\n query.whereIn(this.relatedPivotKey, idsArray);\n }\n\n return query.delete();\n }\n\n /**\n * Sync the intermediate tables with morph type\n */\n async sync(ids: any[], detaching: boolean = true): Promise<{ attached: any[]; detached: any[]; updated: any[] }> {\n const changes = {\n attached: [] as any[],\n detached: [] as any[],\n updated: [] as any[],\n };\n\n const parentKey = this.parent.getAttribute(this.parentKey);\n if (!parentKey) {\n return changes;\n }\n\n // Get current IDs\n const current = await this.newPivotQuery()\n .where(this.foreignPivotKey, '=', parentKey)\n .where(this.morphType, '=', this.morphClass)\n .select(this.relatedPivotKey)\n .get();\n\n const currentIds = current.map((record: any) => record[this.relatedPivotKey]);\n const idsToAttach = ids.filter((id) => !currentIds.includes(id));\n const idsToDetach = detaching ? currentIds.filter((id: any) => !ids.includes(id)) : [];\n\n // Detach old records\n if (idsToDetach.length > 0) {\n await this.detach(idsToDetach);\n changes.detached = idsToDetach;\n }\n\n // Attach new records\n if (idsToAttach.length > 0) {\n await this.attach(idsToAttach);\n changes.attached = idsToAttach;\n }\n\n return changes;\n }\n\n /**\n * Create a new pivot query\n */\n protected newPivotQuery(): EnsembleBuilder<any> {\n const connection = this.parent.getConnection();\n return connection.table(this.table) as any;\n }\n}\n"],"mappings":"yQASgD,IACV,CAEzB,EAAb,cAAsF,CAAiC,CAIrH,UAKA,WAKA,QAKA,YACE,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EAAmB,GACnB,CACA,MAAM,EAAO,EAAQ,EAAO,EAAiB,EAAiB,EAAW,EAAY,EAAa,CAElG,KAAK,UAAY,EACjB,KAAK,WAAa,KAAK,eAAe,CACtC,KAAK,QAAU,EAOjB,YAAsB,EAAyC,CAC7D,IAAiB,KAAK,MAGtB,EACG,KAAK,KAAK,MAAO,GAAG,KAAK,4BAA4B,GAAI,IAAK,GAAG,KAAK,iCAAiC,GAAG,CAC1G,MAAM,GAAG,KAAK,MAAM,GAAG,KAAK,YAAa,IAAK,KAAK,WAAW,CAMnE,qBAAsC,CACpC,IAAM,EAAiB,KAAK,OAAO,aAAa,KAAK,UAAU,CAG3D,GAAmB,MACrB,KAAK,MAAM,MAAM,KAAK,iCAAiC,CAAE,IAAK,EAAe,CAOjF,eAAkC,CAOhC,OANI,KAAK,QAGA,GAGF,EAAS,gBAAgB,KAAK,OAAO,CAM9C,cAAuB,CACrB,OAAO,KAAK,UAMd,oBAA6B,CAC3B,OAAO,KAAK,WAMd,cAAc,EAA0B,CAEtC,MADA,MAAK,WAAa,EACX,KAMT,MAAM,OAAO,EAAkB,EAAkC,EAAE,CAAE,EAAiB,GAAqB,CACzG,IAAM,EAAW,MAAM,QAAQ,EAAI,CAAG,EAAM,CAAC,EAAI,CAC3C,EAAY,KAAK,OAAO,aAAa,KAAK,UAAU,CAE1D,GAAI,CAAC,EACH,MAAU,MAAM,0CAA0C,CAG5D,IAAM,EAAU,EAAS,IAAK,IAAQ,EACnC,KAAK,iBAAkB,GACvB,KAAK,iBAAkB,GACvB,KAAK,WAAY,KAAK,WACvB,GAAG,EACJ,EAAE,CAGH,MADmB,KAAK,OAAO,
|
|
1
|
+
{"version":3,"file":"MorphToMany.mjs","names":[],"sources":["../../../../src/Database/Ensemble/Relations/MorphToMany.ts"],"sourcesContent":["/**\n * MorphToMany Relationship\n *\n * Represents a polymorphic many-to-many relationship from the parent side\n * Example: Post has many Tags (where Tag can belong to many types via taggables table)\n */\n\nimport { Ensemble } from '@/Database/Ensemble/Ensemble';\nimport { EnsembleBuilder } from '@/Database/Ensemble/EnsembleBuilder';\nimport { BelongsToMany } from './BelongsToMany';\nimport { MorphMap } from './MorphMap';\n\nexport class MorphToMany<TRelated extends Ensemble, TParent extends Ensemble> extends BelongsToMany<TRelated, TParent> {\n /**\n * The morph type column (e.g., 'taggable_type')\n */\n protected morphType: string;\n\n /**\n * The morph class name or alias\n */\n protected morphClass: string;\n\n /**\n * Whether this is the inverse of the relation\n */\n protected inverse: boolean;\n\n /**\n * Create a new morph to many relationship instance\n */\n constructor(\n query: EnsembleBuilder<TRelated>,\n parent: TParent,\n name: string,\n table: string,\n foreignPivotKey: string,\n relatedPivotKey: string,\n morphType: string,\n parentKey: string,\n relatedKey: string,\n relationName?: string,\n inverse: boolean = false\n ) {\n super(query, parent, table, foreignPivotKey, relatedPivotKey, parentKey, relatedKey, relationName);\n\n this.morphType = morphType;\n this.morphClass = this.getMorphClass();\n this.inverse = inverse;\n }\n\n /**\n * Set the join clause for the relation query\n * Adds the morph type constraint\n */\n protected performJoin(query?: EnsembleBuilder<TRelated>): void {\n query = query || this.query;\n\n // Join the pivot table with morph type constraint\n query\n .join(this.table, `${this.getQualifiedRelatedKeyName()}`, '=', `${this.getQualifiedRelatedPivotKeyName()}`)\n .where(`${this.table}.${this.morphType}`, '=', this.morphClass);\n }\n\n /**\n * Set the where clause for eager loading\n */\n protected addWhereConstraints(): void {\n const parentKeyValue = this.parent.getAttribute(this.parentKey);\n\n // Only add constraint if parent key value exists\n if (parentKeyValue !== null && parentKeyValue !== undefined) {\n this.query.where(this.getQualifiedForeignPivotKeyName(), '=', parentKeyValue);\n }\n }\n\n /**\n * Get the morph class for the parent during initialization\n */\n protected getMorphClass(): string {\n if (this.inverse) {\n // For inverse relations, we don't set the morph class on parent\n // It will be set per attach/sync operation\n return '';\n }\n\n return MorphMap.getMorphedModel(this.parent);\n }\n\n /**\n * Get the morph type name\n */\n getMorphType(): string {\n return this.morphType;\n }\n\n /**\n * Get the morph class value\n */\n getMorphClassValue(): string {\n return this.morphClass;\n }\n\n /**\n * Set the morph class (used for inverse relations)\n */\n setMorphClass(morphClass: string): this {\n this.morphClass = morphClass;\n return this;\n }\n\n /**\n * Attach models to the parent with morph type\n */\n async attach(ids: any | any[], attributes: Record<string, any> = {}, touch: boolean = true): Promise<void> {\n const idsArray = Array.isArray(ids) ? ids : [ids];\n const parentKey = this.parent.getAttribute(this.parentKey);\n\n if (!parentKey) {\n throw new Error('Parent key must be set before attaching');\n }\n\n const records = idsArray.map((id) => ({\n [this.foreignPivotKey]: parentKey,\n [this.relatedPivotKey]: id,\n [this.morphType]: this.morphClass,\n ...attributes,\n }));\n\n const connection = this.parent.getConnection();\n await connection.table(this.table).insert(records);\n }\n\n /**\n * Detach models from the parent with morph type constraint\n */\n async detach(ids?: any | any[]): Promise<number> {\n const query = this.newPivotQuery();\n const parentKey = this.parent.getAttribute(this.parentKey);\n\n if (!parentKey) {\n return 0;\n }\n\n query.where(this.foreignPivotKey, '=', parentKey).where(this.morphType, '=', this.morphClass);\n\n if (ids) {\n const idsArray = Array.isArray(ids) ? ids : [ids];\n query.whereIn(this.relatedPivotKey, idsArray);\n }\n\n return query.delete();\n }\n\n /**\n * Sync the intermediate tables with morph type\n */\n async sync(ids: any[], detaching: boolean = true): Promise<{ attached: any[]; detached: any[]; updated: any[] }> {\n const changes = {\n attached: [] as any[],\n detached: [] as any[],\n updated: [] as any[],\n };\n\n const parentKey = this.parent.getAttribute(this.parentKey);\n if (!parentKey) {\n return changes;\n }\n\n // Get current IDs\n const current = await this.newPivotQuery()\n .where(this.foreignPivotKey, '=', parentKey)\n .where(this.morphType, '=', this.morphClass)\n .select(this.relatedPivotKey)\n .get();\n\n const currentIds = current.map((record: any) => record[this.relatedPivotKey]);\n const idsToAttach = ids.filter((id) => !currentIds.includes(id));\n const idsToDetach = detaching ? currentIds.filter((id: any) => !ids.includes(id)) : [];\n\n // Detach old records\n if (idsToDetach.length > 0) {\n await this.detach(idsToDetach);\n changes.detached = idsToDetach;\n }\n\n // Attach new records\n if (idsToAttach.length > 0) {\n await this.attach(idsToAttach);\n changes.attached = idsToAttach;\n }\n\n return changes;\n }\n\n /**\n * Create a new pivot query\n */\n protected newPivotQuery(): EnsembleBuilder<any> {\n const connection = this.parent.getConnection();\n return connection.table(this.table) as any;\n }\n}\n"],"mappings":"yQASgD,IACV,CAEzB,EAAb,cAAsF,CAAiC,CAIrH,UAKA,WAKA,QAKA,YACE,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EAAmB,GACnB,CACA,MAAM,EAAO,EAAQ,EAAO,EAAiB,EAAiB,EAAW,EAAY,EAAa,CAElG,KAAK,UAAY,EACjB,KAAK,WAAa,KAAK,eAAe,CACtC,KAAK,QAAU,EAOjB,YAAsB,EAAyC,CAC7D,IAAiB,KAAK,MAGtB,EACG,KAAK,KAAK,MAAO,GAAG,KAAK,4BAA4B,GAAI,IAAK,GAAG,KAAK,iCAAiC,GAAG,CAC1G,MAAM,GAAG,KAAK,MAAM,GAAG,KAAK,YAAa,IAAK,KAAK,WAAW,CAMnE,qBAAsC,CACpC,IAAM,EAAiB,KAAK,OAAO,aAAa,KAAK,UAAU,CAG3D,GAAmB,MACrB,KAAK,MAAM,MAAM,KAAK,iCAAiC,C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EAAU,CAC3C,MAAM,KAAK,UAAW,IAAK,KAAK,WAAW,CAC3C,OAAO,KAAK,gBAAgB,CAC5B,KAAK,EAEmB,IAAK,GAAgB,EAAO,KAAK,iBAAiB,CACvE,EAAc,EAAI,OAAQ,GAAO,CAAC,EAAW,SAAS,EAAG,CAAC,CAC1D,EAAc,EAAY,EAAW,OAAQ,GAAY,CAAC,EAAI,SAAS,EAAG,CAAC,CAAG,EAAE,CActF,OAXI,EAAY,OAAS,IACvB,MAAM,KAAK,OAAO,EAAY,CAC9B,EAAQ,SAAW,GAIjB,EAAY,OAAS,IACvB,MAAM,KAAK,OAAO,EAAY,CAC9B,EAAQ,SAAW,GAGd,EAMT,eAAgD,CAE9C,OADmB,KAAK,OAAO,eACd,CAAC,MAAM,KAAK,MAAM"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
require(`../../_virtual/_rolldown/runtime.cjs`);const e=require(`./ColumnDefinition.cjs`),t=require(`./ForeignKeyDefinition.cjs`);var n=class{columns=[];indexes=[];foreignKeys=[];commands=[];isCreate=!1;constructor(e){this.table=e}id(t=`id`){let n=new e.ColumnDefinition(t,`bigIncrements`);return n.isAutoIncrement=!0,n.isPrimary=!0,n.isUnsigned=!0,this.columns.push(n),n}bigIncrements(t){let n=new e.ColumnDefinition(t,`bigIncrements`);return n.isAutoIncrement=!0,n.isUnsigned=!0,this.columns.push(n),n}increments(t){let n=new e.ColumnDefinition(t,`increments`);return n.isAutoIncrement=!0,n.isUnsigned=!0,this.columns.push(n),n}uuid(t){let n=new e.ColumnDefinition(t,`uuid`);return n.length=36,this.columns.push(n),n}string(t,n=255){let r=new e.ColumnDefinition(t,`string`);return r.length=n,this.columns.push(r),r}text(t){let n=new e.ColumnDefinition(t,`text`);return this.columns.push(n),n}mediumText(t){let n=new e.ColumnDefinition(t,`mediumText`);return this.columns.push(n),n}longText(t){let n=new e.ColumnDefinition(t,`longText`);return this.columns.push(n),n}integer(t){let n=new e.ColumnDefinition(t,`integer`);return this.columns.push(n),n}bigInteger(t){let n=new e.ColumnDefinition(t,`bigInteger`);return this.columns.push(n),n}smallInteger(t){let n=new e.ColumnDefinition(t,`smallInteger`);return this.columns.push(n),n}tinyInteger(t){let n=new e.ColumnDefinition(t,`tinyInteger`);return this.columns.push(n),n}decimal(t,n=8,r=2){let i=new e.ColumnDefinition(t,`decimal`);return i.precision=n,i.scale=r,this.columns.push(i),i}float(t,n,r){let i=new e.ColumnDefinition(t,`float`);return i.precision=n,i.scale=r,this.columns.push(i),i}double(t,n,r){let i=new e.ColumnDefinition(t,`double`);return i.precision=n,i.scale=r,this.columns.push(i),i}boolean(t){let n=new e.ColumnDefinition(t,`boolean`);return this.columns.push(n),n}date(t){let n=new e.ColumnDefinition(t,`date`);return this.columns.push(n),n}datetime(t,n){let r=new e.ColumnDefinition(t,`datetime`);return r.precision=n,this.columns.push(r),r}timestamp(t,n){let r=new e.ColumnDefinition(t,`timestamp`);return r.precision=n,this.columns.push(r),r}timestamps(e){this.timestamp(`created_at`,e).nullable(),this.timestamp(`updated_at`,e).nullable()}json(t){let n=new e.ColumnDefinition(t,`json`);return this.columns.push(n),n}jsonb(t){let n=new e.ColumnDefinition(t,`jsonb`);return this.columns.push(n),n}binary(t){let n=new e.ColumnDefinition(t,`binary`);return this.columns.push(n),n}enum(t,n){let r=new e.ColumnDefinition(t,`enum`);return r.enumValues=n,this.columns.push(r),r}rememberToken(){return this.string(`remember_token`,100).nullable()}softDeletes(e=`deleted_at`){return this.timestamp(e).nullable()}index(e,t){this.indexes.push({columns:Array.isArray(e)?e:[e],name:t,type:`index`})}unique(e,t){this.indexes.push({columns:Array.isArray(e)?e:[e],name:t,type:`unique`})}primary(e){this.indexes.push({columns:Array.isArray(e)?e:[e],type:`primary`})}foreign(e,n){let r=new t.ForeignKeyDefinition(e,n);return this.foreignKeys.push(r),r}dropColumn(e){this.commands.push({type:`dropColumn`,columns:Array.isArray(e)?e:[e]})}dropIndex(e){this.commands.push({type:`dropIndex`,name:e})}dropForeign(e){this.commands.push({type:`dropForeign`,name:e})}renameColumn(e,t){this.commands.push({type:`renameColumn`,from:e,to:t})}};exports.Blueprint=n;
|
|
1
|
+
require(`../../_virtual/_rolldown/runtime.cjs`);const e=require(`./ColumnDefinition.cjs`),t=require(`./ForeignKeyDefinition.cjs`);var n=class{table;columns=[];indexes=[];foreignKeys=[];commands=[];isCreate=!1;constructor(e){this.table=e}id(t=`id`){let n=new e.ColumnDefinition(t,`bigIncrements`);return n.isAutoIncrement=!0,n.isPrimary=!0,n.isUnsigned=!0,this.columns.push(n),n}bigIncrements(t){let n=new e.ColumnDefinition(t,`bigIncrements`);return n.isAutoIncrement=!0,n.isUnsigned=!0,this.columns.push(n),n}increments(t){let n=new e.ColumnDefinition(t,`increments`);return n.isAutoIncrement=!0,n.isUnsigned=!0,this.columns.push(n),n}uuid(t){let n=new e.ColumnDefinition(t,`uuid`);return n.length=36,this.columns.push(n),n}string(t,n=255){let r=new e.ColumnDefinition(t,`string`);return r.length=n,this.columns.push(r),r}text(t){let n=new e.ColumnDefinition(t,`text`);return this.columns.push(n),n}mediumText(t){let n=new e.ColumnDefinition(t,`mediumText`);return this.columns.push(n),n}longText(t){let n=new e.ColumnDefinition(t,`longText`);return this.columns.push(n),n}integer(t){let n=new e.ColumnDefinition(t,`integer`);return this.columns.push(n),n}bigInteger(t){let n=new e.ColumnDefinition(t,`bigInteger`);return this.columns.push(n),n}smallInteger(t){let n=new e.ColumnDefinition(t,`smallInteger`);return this.columns.push(n),n}tinyInteger(t){let n=new e.ColumnDefinition(t,`tinyInteger`);return this.columns.push(n),n}decimal(t,n=8,r=2){let i=new e.ColumnDefinition(t,`decimal`);return i.precision=n,i.scale=r,this.columns.push(i),i}float(t,n,r){let i=new e.ColumnDefinition(t,`float`);return i.precision=n,i.scale=r,this.columns.push(i),i}double(t,n,r){let i=new e.ColumnDefinition(t,`double`);return i.precision=n,i.scale=r,this.columns.push(i),i}boolean(t){let n=new e.ColumnDefinition(t,`boolean`);return this.columns.push(n),n}date(t){let n=new e.ColumnDefinition(t,`date`);return this.columns.push(n),n}datetime(t,n){let r=new e.ColumnDefinition(t,`datetime`);return r.precision=n,this.columns.push(r),r}timestamp(t,n){let r=new e.ColumnDefinition(t,`timestamp`);return r.precision=n,this.columns.push(r),r}timestamps(e){this.timestamp(`created_at`,e).nullable(),this.timestamp(`updated_at`,e).nullable()}json(t){let n=new e.ColumnDefinition(t,`json`);return this.columns.push(n),n}jsonb(t){let n=new e.ColumnDefinition(t,`jsonb`);return this.columns.push(n),n}binary(t){let n=new e.ColumnDefinition(t,`binary`);return this.columns.push(n),n}enum(t,n){let r=new e.ColumnDefinition(t,`enum`);return r.enumValues=n,this.columns.push(r),r}rememberToken(){return this.string(`remember_token`,100).nullable()}softDeletes(e=`deleted_at`){return this.timestamp(e).nullable()}index(e,t){this.indexes.push({columns:Array.isArray(e)?e:[e],name:t,type:`index`})}unique(e,t){this.indexes.push({columns:Array.isArray(e)?e:[e],name:t,type:`unique`})}primary(e){this.indexes.push({columns:Array.isArray(e)?e:[e],type:`primary`})}foreign(e,n){let r=new t.ForeignKeyDefinition(e,n);return this.foreignKeys.push(r),r}dropColumn(e){this.commands.push({type:`dropColumn`,columns:Array.isArray(e)?e:[e]})}dropIndex(e){this.commands.push({type:`dropIndex`,name:e})}dropForeign(e){this.commands.push({type:`dropForeign`,name:e})}renameColumn(e,t){this.commands.push({type:`renameColumn`,from:e,to:t})}};exports.Blueprint=n;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ColumnDefinition as e}from"./ColumnDefinition.mjs";import{ForeignKeyDefinition as t}from"./ForeignKeyDefinition.mjs";var n=class{columns=[];indexes=[];foreignKeys=[];commands=[];isCreate=!1;constructor(e){this.table=e}id(t=`id`){let n=new e(t,`bigIncrements`);return n.isAutoIncrement=!0,n.isPrimary=!0,n.isUnsigned=!0,this.columns.push(n),n}bigIncrements(t){let n=new e(t,`bigIncrements`);return n.isAutoIncrement=!0,n.isUnsigned=!0,this.columns.push(n),n}increments(t){let n=new e(t,`increments`);return n.isAutoIncrement=!0,n.isUnsigned=!0,this.columns.push(n),n}uuid(t){let n=new e(t,`uuid`);return n.length=36,this.columns.push(n),n}string(t,n=255){let r=new e(t,`string`);return r.length=n,this.columns.push(r),r}text(t){let n=new e(t,`text`);return this.columns.push(n),n}mediumText(t){let n=new e(t,`mediumText`);return this.columns.push(n),n}longText(t){let n=new e(t,`longText`);return this.columns.push(n),n}integer(t){let n=new e(t,`integer`);return this.columns.push(n),n}bigInteger(t){let n=new e(t,`bigInteger`);return this.columns.push(n),n}smallInteger(t){let n=new e(t,`smallInteger`);return this.columns.push(n),n}tinyInteger(t){let n=new e(t,`tinyInteger`);return this.columns.push(n),n}decimal(t,n=8,r=2){let i=new e(t,`decimal`);return i.precision=n,i.scale=r,this.columns.push(i),i}float(t,n,r){let i=new e(t,`float`);return i.precision=n,i.scale=r,this.columns.push(i),i}double(t,n,r){let i=new e(t,`double`);return i.precision=n,i.scale=r,this.columns.push(i),i}boolean(t){let n=new e(t,`boolean`);return this.columns.push(n),n}date(t){let n=new e(t,`date`);return this.columns.push(n),n}datetime(t,n){let r=new e(t,`datetime`);return r.precision=n,this.columns.push(r),r}timestamp(t,n){let r=new e(t,`timestamp`);return r.precision=n,this.columns.push(r),r}timestamps(e){this.timestamp(`created_at`,e).nullable(),this.timestamp(`updated_at`,e).nullable()}json(t){let n=new e(t,`json`);return this.columns.push(n),n}jsonb(t){let n=new e(t,`jsonb`);return this.columns.push(n),n}binary(t){let n=new e(t,`binary`);return this.columns.push(n),n}enum(t,n){let r=new e(t,`enum`);return r.enumValues=n,this.columns.push(r),r}rememberToken(){return this.string(`remember_token`,100).nullable()}softDeletes(e=`deleted_at`){return this.timestamp(e).nullable()}index(e,t){this.indexes.push({columns:Array.isArray(e)?e:[e],name:t,type:`index`})}unique(e,t){this.indexes.push({columns:Array.isArray(e)?e:[e],name:t,type:`unique`})}primary(e){this.indexes.push({columns:Array.isArray(e)?e:[e],type:`primary`})}foreign(e,n){let r=new t(e,n);return this.foreignKeys.push(r),r}dropColumn(e){this.commands.push({type:`dropColumn`,columns:Array.isArray(e)?e:[e]})}dropIndex(e){this.commands.push({type:`dropIndex`,name:e})}dropForeign(e){this.commands.push({type:`dropForeign`,name:e})}renameColumn(e,t){this.commands.push({type:`renameColumn`,from:e,to:t})}};export{n as Blueprint};
|
|
1
|
+
import{ColumnDefinition as e}from"./ColumnDefinition.mjs";import{ForeignKeyDefinition as t}from"./ForeignKeyDefinition.mjs";var n=class{table;columns=[];indexes=[];foreignKeys=[];commands=[];isCreate=!1;constructor(e){this.table=e}id(t=`id`){let n=new e(t,`bigIncrements`);return n.isAutoIncrement=!0,n.isPrimary=!0,n.isUnsigned=!0,this.columns.push(n),n}bigIncrements(t){let n=new e(t,`bigIncrements`);return n.isAutoIncrement=!0,n.isUnsigned=!0,this.columns.push(n),n}increments(t){let n=new e(t,`increments`);return n.isAutoIncrement=!0,n.isUnsigned=!0,this.columns.push(n),n}uuid(t){let n=new e(t,`uuid`);return n.length=36,this.columns.push(n),n}string(t,n=255){let r=new e(t,`string`);return r.length=n,this.columns.push(r),r}text(t){let n=new e(t,`text`);return this.columns.push(n),n}mediumText(t){let n=new e(t,`mediumText`);return this.columns.push(n),n}longText(t){let n=new e(t,`longText`);return this.columns.push(n),n}integer(t){let n=new e(t,`integer`);return this.columns.push(n),n}bigInteger(t){let n=new e(t,`bigInteger`);return this.columns.push(n),n}smallInteger(t){let n=new e(t,`smallInteger`);return this.columns.push(n),n}tinyInteger(t){let n=new e(t,`tinyInteger`);return this.columns.push(n),n}decimal(t,n=8,r=2){let i=new e(t,`decimal`);return i.precision=n,i.scale=r,this.columns.push(i),i}float(t,n,r){let i=new e(t,`float`);return i.precision=n,i.scale=r,this.columns.push(i),i}double(t,n,r){let i=new e(t,`double`);return i.precision=n,i.scale=r,this.columns.push(i),i}boolean(t){let n=new e(t,`boolean`);return this.columns.push(n),n}date(t){let n=new e(t,`date`);return this.columns.push(n),n}datetime(t,n){let r=new e(t,`datetime`);return r.precision=n,this.columns.push(r),r}timestamp(t,n){let r=new e(t,`timestamp`);return r.precision=n,this.columns.push(r),r}timestamps(e){this.timestamp(`created_at`,e).nullable(),this.timestamp(`updated_at`,e).nullable()}json(t){let n=new e(t,`json`);return this.columns.push(n),n}jsonb(t){let n=new e(t,`jsonb`);return this.columns.push(n),n}binary(t){let n=new e(t,`binary`);return this.columns.push(n),n}enum(t,n){let r=new e(t,`enum`);return r.enumValues=n,this.columns.push(r),r}rememberToken(){return this.string(`remember_token`,100).nullable()}softDeletes(e=`deleted_at`){return this.timestamp(e).nullable()}index(e,t){this.indexes.push({columns:Array.isArray(e)?e:[e],name:t,type:`index`})}unique(e,t){this.indexes.push({columns:Array.isArray(e)?e:[e],name:t,type:`unique`})}primary(e){this.indexes.push({columns:Array.isArray(e)?e:[e],type:`primary`})}foreign(e,n){let r=new t(e,n);return this.foreignKeys.push(r),r}dropColumn(e){this.commands.push({type:`dropColumn`,columns:Array.isArray(e)?e:[e]})}dropIndex(e){this.commands.push({type:`dropIndex`,name:e})}dropForeign(e){this.commands.push({type:`dropForeign`,name:e})}renameColumn(e,t){this.commands.push({type:`renameColumn`,from:e,to:t})}};export{n as Blueprint};
|
|
2
2
|
//# sourceMappingURL=Blueprint.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Blueprint.mjs","names":[],"sources":["../../../src/Database/Migrations/Blueprint.ts"],"sourcesContent":["/**\n * Blueprint\n *\n * Defines a table schema in a migration\n */\n\nimport { Blueprint as IBlueprint } from '@/Database/Contracts/Schema';\nimport { ColumnDefinition } from './ColumnDefinition';\nimport { ForeignKeyDefinition } from './ForeignKeyDefinition';\n\nexport interface IndexDefinition {\n columns: string[];\n name?: string;\n type: 'index' | 'unique' | 'primary';\n}\n\nexport interface DropCommand {\n type: 'dropColumn' | 'dropIndex' | 'dropForeign' | 'renameColumn';\n name?: string;\n columns?: string[];\n from?: string;\n to?: string;\n}\n\nexport class Blueprint implements IBlueprint {\n public columns: ColumnDefinition[] = [];\n public indexes: IndexDefinition[] = [];\n public foreignKeys: ForeignKeyDefinition[] = [];\n public commands: DropCommand[] = [];\n public isCreate: boolean = false;\n\n constructor(public table: string) {}\n\n /**\n * Add an auto-incrementing ID column\n */\n id(column: string = 'id'): ColumnDefinition {\n const col = new ColumnDefinition(column, 'bigIncrements');\n col.isAutoIncrement = true;\n col.isPrimary = true;\n col.isUnsigned = true;\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a big auto-incrementing ID column\n */\n bigIncrements(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'bigIncrements');\n col.isAutoIncrement = true;\n col.isUnsigned = true;\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add an auto-incrementing column\n */\n increments(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'increments');\n col.isAutoIncrement = true;\n col.isUnsigned = true;\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a UUID column\n */\n uuid(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'uuid');\n col.length = 36;\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a string column\n */\n string(column: string, length: number = 255): ColumnDefinition {\n const col = new ColumnDefinition(column, 'string');\n col.length = length;\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a text column\n */\n text(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'text');\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a medium text column\n */\n mediumText(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'mediumText');\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a long text column\n */\n longText(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'longText');\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add an integer column\n */\n integer(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'integer');\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a big integer column\n */\n bigInteger(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'bigInteger');\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a small integer column\n */\n smallInteger(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'smallInteger');\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a tiny integer column\n */\n tinyInteger(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'tinyInteger');\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a decimal column\n */\n decimal(column: string, precision: number = 8, scale: number = 2): ColumnDefinition {\n const col = new ColumnDefinition(column, 'decimal');\n col.precision = precision;\n col.scale = scale;\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a float column\n */\n float(column: string, precision?: number, scale?: number): ColumnDefinition {\n const col = new ColumnDefinition(column, 'float');\n col.precision = precision;\n col.scale = scale;\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a double column\n */\n double(column: string, precision?: number, scale?: number): ColumnDefinition {\n const col = new ColumnDefinition(column, 'double');\n col.precision = precision;\n col.scale = scale;\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a boolean column\n */\n boolean(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'boolean');\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a date column\n */\n date(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'date');\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a datetime column\n */\n datetime(column: string, precision?: number): ColumnDefinition {\n const col = new ColumnDefinition(column, 'datetime');\n col.precision = precision;\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a timestamp column\n */\n timestamp(column: string, precision?: number): ColumnDefinition {\n const col = new ColumnDefinition(column, 'timestamp');\n col.precision = precision;\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add created_at and updated_at timestamp columns\n */\n timestamps(precision?: number): void {\n this.timestamp('created_at', precision).nullable();\n this.timestamp('updated_at', precision).nullable();\n }\n\n /**\n * Add a JSON column\n */\n json(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'json');\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a JSONB column\n */\n jsonb(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'jsonb');\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a binary column\n */\n binary(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'binary');\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add an enum column\n */\n enum(column: string, values: string[]): ColumnDefinition {\n const col = new ColumnDefinition(column, 'enum');\n col.enumValues = values;\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a remember token column\n */\n rememberToken(): ColumnDefinition {\n return this.string('remember_token', 100).nullable();\n }\n\n /**\n * Add soft delete columns\n */\n softDeletes(column: string = 'deleted_at'): ColumnDefinition {\n return this.timestamp(column).nullable();\n }\n\n /**\n * Add an index\n */\n index(columns: string | string[], indexName?: string): void {\n this.indexes.push({\n columns: Array.isArray(columns) ? columns : [columns],\n name: indexName,\n type: 'index',\n });\n }\n\n /**\n * Add a unique index\n */\n unique(columns: string | string[], indexName?: string): void {\n this.indexes.push({\n columns: Array.isArray(columns) ? columns : [columns],\n name: indexName,\n type: 'unique',\n });\n }\n\n /**\n * Add a primary key\n */\n primary(columns: string | string[]): void {\n this.indexes.push({\n columns: Array.isArray(columns) ? columns : [columns],\n type: 'primary',\n });\n }\n\n /**\n * Add a foreign key\n */\n foreign(columns: string | string[], indexName?: string): ForeignKeyDefinition {\n const fk = new ForeignKeyDefinition(columns, indexName);\n this.foreignKeys.push(fk);\n return fk;\n }\n\n /**\n * Drop a column\n */\n dropColumn(column: string | string[]): void {\n this.commands.push({\n type: 'dropColumn',\n columns: Array.isArray(column) ? column : [column],\n });\n }\n\n /**\n * Drop an index\n */\n dropIndex(indexName: string): void {\n this.commands.push({\n type: 'dropIndex',\n name: indexName,\n });\n }\n\n /**\n * Drop a foreign key\n */\n dropForeign(indexName: string): void {\n this.commands.push({\n type: 'dropForeign',\n name: indexName,\n });\n }\n\n /**\n * Rename a column\n */\n renameColumn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,QAAQ,KAAK,CAChB,QAAS,MAAM,QAAQ,EAAQ,CAAG,EAAU,CAAC,EAAQ,CACrD,KAAM,UACP,CAAC,CAMJ,QAAQ,EAA4B,EAA0C,CAC5E,IAAM,EAAK,IAAI,EAAqB,EAAS,EAAU,CAEvD,OADA,KAAK,YAAY,KAAK,EAAG,CAClB,EAMT,WAAW,EAAiC,CAC1C,KAAK,SAAS,KAAK,CACjB,KAAM,aACN,QAAS,MAAM,QAAQ,EAAO,CAAG,EAAS,CAAC,EAAO,CACnD,CAAC,CAMJ,UAAU,EAAyB,CACjC,KAAK,SAAS,KAAK,CACjB,KAAM,YACN,KAAM,EACP,CAAC,CAMJ,YAAY,EAAyB,CACnC,KAAK,SAAS,KAAK,CACjB,KAAM,cACN,KAAM,EACP,CAAC,CAMJ,aAAa,EAAc,EAAkB,CAC3C,KAAK,SAAS,KAAK,CACjB,KAAM,eACN,OACA,KACD,CAAC"}
|
|
1
|
+
{"version":3,"file":"Blueprint.mjs","names":[],"sources":["../../../src/Database/Migrations/Blueprint.ts"],"sourcesContent":["/**\n * Blueprint\n *\n * Defines a table schema in a migration\n */\n\nimport { Blueprint as IBlueprint } from '@/Database/Contracts/Schema';\nimport { ColumnDefinition } from './ColumnDefinition';\nimport { ForeignKeyDefinition } from './ForeignKeyDefinition';\n\nexport interface IndexDefinition {\n columns: string[];\n name?: string;\n type: 'index' | 'unique' | 'primary';\n}\n\nexport interface DropCommand {\n type: 'dropColumn' | 'dropIndex' | 'dropForeign' | 'renameColumn';\n name?: string;\n columns?: string[];\n from?: string;\n to?: string;\n}\n\nexport class Blueprint implements IBlueprint {\n public columns: ColumnDefinition[] = [];\n public indexes: IndexDefinition[] = [];\n public foreignKeys: ForeignKeyDefinition[] = [];\n public commands: DropCommand[] = [];\n public isCreate: boolean = false;\n\n constructor(public table: string) {}\n\n /**\n * Add an auto-incrementing ID column\n */\n id(column: string = 'id'): ColumnDefinition {\n const col = new ColumnDefinition(column, 'bigIncrements');\n col.isAutoIncrement = true;\n col.isPrimary = true;\n col.isUnsigned = true;\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a big auto-incrementing ID column\n */\n bigIncrements(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'bigIncrements');\n col.isAutoIncrement = true;\n col.isUnsigned = true;\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add an auto-incrementing column\n */\n increments(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'increments');\n col.isAutoIncrement = true;\n col.isUnsigned = true;\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a UUID column\n */\n uuid(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'uuid');\n col.length = 36;\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a string column\n */\n string(column: string, length: number = 255): ColumnDefinition {\n const col = new ColumnDefinition(column, 'string');\n col.length = length;\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a text column\n */\n text(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'text');\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a medium text column\n */\n mediumText(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'mediumText');\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a long text column\n */\n longText(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'longText');\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add an integer column\n */\n integer(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'integer');\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a big integer column\n */\n bigInteger(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'bigInteger');\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a small integer column\n */\n smallInteger(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'smallInteger');\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a tiny integer column\n */\n tinyInteger(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'tinyInteger');\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a decimal column\n */\n decimal(column: string, precision: number = 8, scale: number = 2): ColumnDefinition {\n const col = new ColumnDefinition(column, 'decimal');\n col.precision = precision;\n col.scale = scale;\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a float column\n */\n float(column: string, precision?: number, scale?: number): ColumnDefinition {\n const col = new ColumnDefinition(column, 'float');\n col.precision = precision;\n col.scale = scale;\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a double column\n */\n double(column: string, precision?: number, scale?: number): ColumnDefinition {\n const col = new ColumnDefinition(column, 'double');\n col.precision = precision;\n col.scale = scale;\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a boolean column\n */\n boolean(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'boolean');\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a date column\n */\n date(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'date');\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a datetime column\n */\n datetime(column: string, precision?: number): ColumnDefinition {\n const col = new ColumnDefinition(column, 'datetime');\n col.precision = precision;\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a timestamp column\n */\n timestamp(column: string, precision?: number): ColumnDefinition {\n const col = new ColumnDefinition(column, 'timestamp');\n col.precision = precision;\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add created_at and updated_at timestamp columns\n */\n timestamps(precision?: number): void {\n this.timestamp('created_at', precision).nullable();\n this.timestamp('updated_at', precision).nullable();\n }\n\n /**\n * Add a JSON column\n */\n json(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'json');\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a JSONB column\n */\n jsonb(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'jsonb');\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a binary column\n */\n binary(column: string): ColumnDefinition {\n const col = new ColumnDefinition(column, 'binary');\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add an enum column\n */\n enum(column: string, values: string[]): ColumnDefinition {\n const col = new ColumnDefinition(column, 'enum');\n col.enumValues = values;\n this.columns.push(col);\n return col;\n }\n\n /**\n * Add a remember token column\n */\n rememberToken(): ColumnDefinition {\n return this.string('remember_token', 100).nullable();\n }\n\n /**\n * Add soft delete columns\n */\n softDeletes(column: string = 'deleted_at'): ColumnDefinition {\n return this.timestamp(column).nullable();\n }\n\n /**\n * Add an index\n */\n index(columns: string | string[], indexName?: string): void {\n this.indexes.push({\n columns: Array.isArray(columns) ? columns : [columns],\n name: indexName,\n type: 'index',\n });\n }\n\n /**\n * Add a unique index\n */\n unique(columns: string | string[], indexName?: string): void {\n this.indexes.push({\n columns: Array.isArray(columns) ? columns : [columns],\n name: indexName,\n type: 'unique',\n });\n }\n\n /**\n * Add a primary key\n */\n primary(columns: string | string[]): void {\n this.indexes.push({\n columns: Array.isArray(columns) ? columns : [columns],\n type: 'primary',\n });\n }\n\n /**\n * Add a foreign key\n */\n foreign(columns: string | string[], indexName?: string): ForeignKeyDefinition {\n const fk = new ForeignKeyDefinition(columns, indexName);\n this.foreignKeys.push(fk);\n return fk;\n }\n\n /**\n * Drop a column\n */\n dropColumn(column: string | string[]): void {\n this.commands.push({\n type: 'dropColumn',\n columns: Array.isArray(column) ? column : [column],\n });\n }\n\n /**\n * Drop an index\n */\n dropIndex(indexName: string): void {\n this.commands.push({\n type: 'dropIndex',\n name: indexName,\n });\n }\n\n /**\n * Drop a foreign key\n */\n dropForeign(indexName: string): void {\n this.commands.push({\n type: 'dropForeign',\n name: indexName,\n });\n }\n\n /**\n * Rename a column\n */\n renameColumn(from: string, to: string): void {\n this.commands.push({\n type: 'renameColumn',\n from,\n to,\n });\n }\n}\n"],"mappings":"4HAwBA,IAAa,EAAb,KAA6C,CAOxB,MANnB,QAAqC,EAAE,CACvC,QAAoC,EAAE,CACtC,YAA6C,EAAE,CAC/C,SAAiC,EAAE,CACnC,SAA2B,GAE3B,YAAY,EAAsB,CAAf,KAAA,MAAA,EAKnB,G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AAK,SAAS,KAAK,CACjB,KAAM,aACN,QAAS,MAAM,QAAQ,EAAO,CAAG,EAAS,CAAC,EAAO,CACnD,CAAC,CAMJ,UAAU,EAAyB,CACjC,KAAK,SAAS,KAAK,CACjB,KAAM,YACN,KAAM,EACP,CAAC,CAMJ,YAAY,EAAyB,CACnC,KAAK,SAAS,KAAK,CACjB,KAAM,cACN,KAAM,EACP,CAAC,CAMJ,aAAa,EAAc,EAAkB,CAC3C,KAAK,SAAS,KAAK,CACjB,KAAM,eACN,OACA,KACD,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const e=require(`../../_virtual/_rolldown/runtime.cjs`);let t=require(`path`);t=e.__toESM(t);let n=require(`fs`);n=e.__toESM(n);var r=class{constructor(e){this.customStubPath=e}async create(e,r,i,a=!1){this.ensureMigrationDirectoryExists(r);let o=this.getDatePrefix()+`_`+e+`.ts`,s=t.join(r,o),c=this.getStub(i,a),l=this.populateStub(c,i);return n.writeFileSync(s,l),s}getStub(e,t=!1){return e&&t?this.getCreateStub():e?this.getUpdateStub():this.getBlankStub()}getBlankStub(){return`import { Migration } from '@orchestr-sh/orchestr';
|
|
1
|
+
const e=require(`../../_virtual/_rolldown/runtime.cjs`);let t=require(`path`);t=e.__toESM(t,1);let n=require(`fs`);n=e.__toESM(n,1);var r=class{customStubPath;constructor(e){this.customStubPath=e}async create(e,r,i,a=!1){this.ensureMigrationDirectoryExists(r);let o=this.getDatePrefix()+`_`+e+`.ts`,s=t.join(r,o),c=this.getStub(i,a),l=this.populateStub(c,i);return n.writeFileSync(s,l),s}getStub(e,t=!1){return e&&t?this.getCreateStub():e?this.getUpdateStub():this.getBlankStub()}getBlankStub(){return`import { Migration } from '@orchestr-sh/orchestr';
|
|
2
2
|
import { Schema } from '@orchestr-sh/orchestr';
|
|
3
3
|
|
|
4
4
|
export default class extends Migration {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import*as e from"path";import*as t from"fs";var n=class{constructor(e){this.customStubPath=e}async create(n,r,i,a=!1){this.ensureMigrationDirectoryExists(r);let o=this.getDatePrefix()+`_`+n+`.ts`,s=e.join(r,o),c=this.getStub(i,a),l=this.populateStub(c,i);return t.writeFileSync(s,l),s}getStub(e,t=!1){return e&&t?this.getCreateStub():e?this.getUpdateStub():this.getBlankStub()}getBlankStub(){return`import { Migration } from '@orchestr-sh/orchestr';
|
|
1
|
+
import*as e from"path";import*as t from"fs";var n=class{customStubPath;constructor(e){this.customStubPath=e}async create(n,r,i,a=!1){this.ensureMigrationDirectoryExists(r);let o=this.getDatePrefix()+`_`+n+`.ts`,s=e.join(r,o),c=this.getStub(i,a),l=this.populateStub(c,i);return t.writeFileSync(s,l),s}getStub(e,t=!1){return e&&t?this.getCreateStub():e?this.getUpdateStub():this.getBlankStub()}getBlankStub(){return`import { Migration } from '@orchestr-sh/orchestr';
|
|
2
2
|
import { Schema } from '@orchestr-sh/orchestr';
|
|
3
3
|
|
|
4
4
|
export default class extends Migration {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MigrationCreator.mjs","names":[],"sources":["../../../src/Database/Migrations/MigrationCreator.ts"],"sourcesContent":["/**\n * MigrationCreator\n *\n * Creates new migration files from stubs\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nexport class MigrationCreator {\n constructor(protected customStubPath?: string) {}\n\n /**\n * Create a new migration file\n */\n async create(name: string, migrationPath: string, table?: string, create: boolean = false): Promise<string> {\n this.ensureMigrationDirectoryExists(migrationPath);\n\n const fileName = this.getDatePrefix() + '_' + name + '.ts';\n const filePath = path.join(migrationPath, fileName);\n\n const stub = this.getStub(table, create);\n const populated = this.populateStub(stub, table);\n\n fs.writeFileSync(filePath, populated);\n\n return filePath;\n }\n\n /**\n * Get the migration stub\n */\n protected getStub(table?: string, create: boolean = false): string {\n if (table && create) {\n return this.getCreateStub();\n }\n\n if (table) {\n return this.getUpdateStub();\n }\n\n return this.getBlankStub();\n }\n\n /**\n * Get the blank migration stub\n */\n protected getBlankStub(): string {\n return `import { Migration } from '@orchestr-sh/orchestr';\nimport { Schema } from '@orchestr-sh/orchestr';\n\nexport default class extends Migration {\n /**\n * Run the migrations\n */\n async up(schema: Schema): Promise<void> {\n //\n }\n\n /**\n * Reverse the migrations\n */\n async down(schema: Schema): Promise<void> {\n //\n }\n}\n`;\n }\n\n /**\n * Get the create table stub\n */\n protected getCreateStub(): string {\n return `import { Migration } from '@orchestr-sh/orchestr';\nimport { Schema } from '@orchestr-sh/orchestr';\n\nexport default class extends Migration {\n /**\n * Run the migrations\n */\n async up(schema: Schema): Promise<void> {\n await schema.create('{{table}}', (table) => {\n table.id();\n table.timestamps();\n });\n }\n\n /**\n * Reverse the migrations\n */\n async down(schema: Schema): Promise<void> {\n await schema.dropIfExists('{{table}}');\n }\n}\n`;\n }\n\n /**\n * Get the update table stub\n */\n protected getUpdateStub(): string {\n return `import { Migration } from '@orchestr-sh/orchestr';\nimport { Schema } from '@orchestr-sh/orchestr';\n\nexport default class extends Migration {\n /**\n * Run the migrations\n */\n async up(schema: Schema): Promise<void> {\n await schema.table('{{table}}', (table) => {\n //\n });\n }\n\n /**\n * Reverse the migrations\n */\n async down(schema: Schema): Promise<void> {\n await schema.table('{{table}}', (table) => {\n //\n });\n }\n}\n`;\n }\n\n /**\n * Populate the stub with table name\n */\n protected populateStub(stub: string, table?: string): string {\n if (table) {\n return stub.replace(/\\{\\{table\\}\\}/g, table);\n }\n\n return stub;\n }\n\n /**\n * Get the date prefix for the migration\n */\n protected getDatePrefix(): string {\n const now = new Date();\n\n const year = now.getFullYear();\n const month = String(now.getMonth() + 1).padStart(2, '0');\n const day = String(now.getDate()).padStart(2, '0');\n const hour = String(now.getHours()).padStart(2, '0');\n const minute = String(now.getMinutes()).padStart(2, '0');\n const second = String(now.getSeconds()).padStart(2, '0');\n\n return `${year}_${month}_${day}_${hour}${minute}${second}`;\n }\n\n /**\n * Ensure the migration directory exists\n */\n protected ensureMigrationDirectoryExists(path: string): void {\n if (!fs.existsSync(path)) {\n fs.mkdirSync(path, { recursive: true });\n }\n }\n}\n"],"mappings":"4CASA,IAAa,EAAb,KAA8B,
|
|
1
|
+
{"version":3,"file":"MigrationCreator.mjs","names":[],"sources":["../../../src/Database/Migrations/MigrationCreator.ts"],"sourcesContent":["/**\n * MigrationCreator\n *\n * Creates new migration files from stubs\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nexport class MigrationCreator {\n constructor(protected customStubPath?: string) {}\n\n /**\n * Create a new migration file\n */\n async create(name: string, migrationPath: string, table?: string, create: boolean = false): Promise<string> {\n this.ensureMigrationDirectoryExists(migrationPath);\n\n const fileName = this.getDatePrefix() + '_' + name + '.ts';\n const filePath = path.join(migrationPath, fileName);\n\n const stub = this.getStub(table, create);\n const populated = this.populateStub(stub, table);\n\n fs.writeFileSync(filePath, populated);\n\n return filePath;\n }\n\n /**\n * Get the migration stub\n */\n protected getStub(table?: string, create: boolean = false): string {\n if (table && create) {\n return this.getCreateStub();\n }\n\n if (table) {\n return this.getUpdateStub();\n }\n\n return this.getBlankStub();\n }\n\n /**\n * Get the blank migration stub\n */\n protected getBlankStub(): string {\n return `import { Migration } from '@orchestr-sh/orchestr';\nimport { Schema } from '@orchestr-sh/orchestr';\n\nexport default class extends Migration {\n /**\n * Run the migrations\n */\n async up(schema: Schema): Promise<void> {\n //\n }\n\n /**\n * Reverse the migrations\n */\n async down(schema: Schema): Promise<void> {\n //\n }\n}\n`;\n }\n\n /**\n * Get the create table stub\n */\n protected getCreateStub(): string {\n return `import { Migration } from '@orchestr-sh/orchestr';\nimport { Schema } from '@orchestr-sh/orchestr';\n\nexport default class extends Migration {\n /**\n * Run the migrations\n */\n async up(schema: Schema): Promise<void> {\n await schema.create('{{table}}', (table) => {\n table.id();\n table.timestamps();\n });\n }\n\n /**\n * Reverse the migrations\n */\n async down(schema: Schema): Promise<void> {\n await schema.dropIfExists('{{table}}');\n }\n}\n`;\n }\n\n /**\n * Get the update table stub\n */\n protected getUpdateStub(): string {\n return `import { Migration } from '@orchestr-sh/orchestr';\nimport { Schema } from '@orchestr-sh/orchestr';\n\nexport default class extends Migration {\n /**\n * Run the migrations\n */\n async up(schema: Schema): Promise<void> {\n await schema.table('{{table}}', (table) => {\n //\n });\n }\n\n /**\n * Reverse the migrations\n */\n async down(schema: Schema): Promise<void> {\n await schema.table('{{table}}', (table) => {\n //\n });\n }\n}\n`;\n }\n\n /**\n * Populate the stub with table name\n */\n protected populateStub(stub: string, table?: string): string {\n if (table) {\n return stub.replace(/\\{\\{table\\}\\}/g, table);\n }\n\n return stub;\n }\n\n /**\n * Get the date prefix for the migration\n */\n protected getDatePrefix(): string {\n const now = new Date();\n\n const year = now.getFullYear();\n const month = String(now.getMonth() + 1).padStart(2, '0');\n const day = String(now.getDate()).padStart(2, '0');\n const hour = String(now.getHours()).padStart(2, '0');\n const minute = String(now.getMinutes()).padStart(2, '0');\n const second = String(now.getSeconds()).padStart(2, '0');\n\n return `${year}_${month}_${day}_${hour}${minute}${second}`;\n }\n\n /**\n * Ensure the migration directory exists\n */\n protected ensureMigrationDirectoryExists(path: string): void {\n if (!fs.existsSync(path)) {\n fs.mkdirSync(path, { recursive: true });\n }\n }\n}\n"],"mappings":"4CASA,IAAa,EAAb,KAA8B,CACN,eAAtB,YAAY,EAAmC,CAAzB,KAAA,eAAA,EAKtB,MAAM,OAAO,EAAc,EAAuB,EAAgB,EAAkB,GAAwB,CAC1G,KAAK,+BAA+B,EAAc,CAElD,IAAM,EAAW,KAAK,eAAe,CAAG,IAAM,EAAO,MAC/C,EAAW,EAAK,KAAK,EAAe,EAAS,CAE7C,EAAO,KAAK,QAAQ,EAAO,EAAO,CAClC,EAAY,KAAK,aAAa,EAAM,EAAM,CAIhD,OAFA,EAAG,cAAc,EAAU,EAAU,CAE9B,EAMT,QAAkB,EAAgB,EAAkB,GAAe,CASjE,OARI,GAAS,EACJ,KAAK,eAAe,CAGzB,EACK,KAAK,eAAe,CAGtB,KAAK,cAAc,CAM5B,cAAiC,CAC/B,MAAO;;;;;;;;;;;;;;;;;;EAwBT,eAAkC,CAChC,MAAO;;;;;;;;;;;;;;;;;;;;;EA2BT,eAAkC,CAChC,MAAO;;;;;;;;;;;;;;;;;;;;;;EA4BT,aAAuB,EAAc,EAAwB,CAK3D,OAJI,EACK,EAAK,QAAQ,iBAAkB,EAAM,CAGvC,EAMT,eAAkC,CAChC,IAAM,EAAM,IAAI,KAShB,MAAO,GAPM,EAAI,aAOH,CAAC,GAND,OAAO,EAAI,UAAU,CAAG,EAAE,CAAC,SAAS,EAAG,IAM9B,CAAC,GALZ,OAAO,EAAI,SAAS,CAAC,CAAC,SAAS,EAAG,IAKhB,CAAC,GAJlB,OAAO,EAAI,UAAU,CAAC,CAAC,SAAS,EAAG,IAIV,GAHvB,OAAO,EAAI,YAAY,CAAC,CAAC,SAAS,EAAG,IAGL,GAFhC,OAAO,EAAI,YAAY,CAAC,CAAC,SAAS,EAAG,IAEI,GAM1D,+BAAyC,EAAoB,CACtD,EAAG,WAAW,EAAK,EACtB,EAAG,UAAU,EAAM,CAAE,UAAW,GAAM,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
require(`../../_virtual/_rolldown/runtime.cjs`);var e=class{table=`migrations`;constructor(e){this.connection=e}async getRan(){return(await this.connection.table(this.table).orderBy(`batch`,`asc`).orderBy(`migration`,`asc`).get()).map(e=>e.migration)}async getMigrations(e){let t=this.connection.table(this.table).orderBy(`batch`,`desc`).orderBy(`migration`,`desc`);return e!==void 0&&e>0&&t.limit(e),await t.get()}async getLast(){let e=await this.getLastBatchNumber();return e===0?[]:await this.connection.table(this.table).where(`batch`,e).orderBy(`migration`,`desc`).get()}async getMigrationBatches(){let e=await this.connection.table(this.table).orderBy(`batch`,`asc`).orderBy(`migration`,`asc`).get(),t={};return e.forEach(e=>{t[e.migration]=e.batch}),t}async log(e,t){await this.connection.table(this.table).insert({migration:e,batch:t})}async delete(e){await this.connection.table(this.table).where(`migration`,e.migration).delete()}async getNextBatchNumber(){return await this.getLastBatchNumber()+1}async getLastBatchNumber(){let e=await this.connection.table(this.table).max(`batch`);return e===null?0:Number(e)}async createRepository(){this.connection.getAdapter(),await this.connection.query(`
|
|
1
|
+
require(`../../_virtual/_rolldown/runtime.cjs`);var e=class{connection;table=`migrations`;constructor(e){this.connection=e}async getRan(){return(await this.connection.table(this.table).orderBy(`batch`,`asc`).orderBy(`migration`,`asc`).get()).map(e=>e.migration)}async getMigrations(e){let t=this.connection.table(this.table).orderBy(`batch`,`desc`).orderBy(`migration`,`desc`);return e!==void 0&&e>0&&t.limit(e),await t.get()}async getLast(){let e=await this.getLastBatchNumber();return e===0?[]:await this.connection.table(this.table).where(`batch`,e).orderBy(`migration`,`desc`).get()}async getMigrationBatches(){let e=await this.connection.table(this.table).orderBy(`batch`,`asc`).orderBy(`migration`,`asc`).get(),t={};return e.forEach(e=>{t[e.migration]=e.batch}),t}async log(e,t){await this.connection.table(this.table).insert({migration:e,batch:t})}async delete(e){await this.connection.table(this.table).where(`migration`,e.migration).delete()}async getNextBatchNumber(){return await this.getLastBatchNumber()+1}async getLastBatchNumber(){let e=await this.connection.table(this.table).max(`batch`);return e===null?0:Number(e)}async createRepository(){this.connection.getAdapter(),await this.connection.query(`
|
|
2
2
|
CREATE TABLE IF NOT EXISTS ${this.table} (
|
|
3
3
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
4
4
|
migration VARCHAR(255) NOT NULL,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var e=class{table=`migrations`;constructor(e){this.connection=e}async getRan(){return(await this.connection.table(this.table).orderBy(`batch`,`asc`).orderBy(`migration`,`asc`).get()).map(e=>e.migration)}async getMigrations(e){let t=this.connection.table(this.table).orderBy(`batch`,`desc`).orderBy(`migration`,`desc`);return e!==void 0&&e>0&&t.limit(e),await t.get()}async getLast(){let e=await this.getLastBatchNumber();return e===0?[]:await this.connection.table(this.table).where(`batch`,e).orderBy(`migration`,`desc`).get()}async getMigrationBatches(){let e=await this.connection.table(this.table).orderBy(`batch`,`asc`).orderBy(`migration`,`asc`).get(),t={};return e.forEach(e=>{t[e.migration]=e.batch}),t}async log(e,t){await this.connection.table(this.table).insert({migration:e,batch:t})}async delete(e){await this.connection.table(this.table).where(`migration`,e.migration).delete()}async getNextBatchNumber(){return await this.getLastBatchNumber()+1}async getLastBatchNumber(){let e=await this.connection.table(this.table).max(`batch`);return e===null?0:Number(e)}async createRepository(){this.connection.getAdapter(),await this.connection.query(`
|
|
1
|
+
var e=class{connection;table=`migrations`;constructor(e){this.connection=e}async getRan(){return(await this.connection.table(this.table).orderBy(`batch`,`asc`).orderBy(`migration`,`asc`).get()).map(e=>e.migration)}async getMigrations(e){let t=this.connection.table(this.table).orderBy(`batch`,`desc`).orderBy(`migration`,`desc`);return e!==void 0&&e>0&&t.limit(e),await t.get()}async getLast(){let e=await this.getLastBatchNumber();return e===0?[]:await this.connection.table(this.table).where(`batch`,e).orderBy(`migration`,`desc`).get()}async getMigrationBatches(){let e=await this.connection.table(this.table).orderBy(`batch`,`asc`).orderBy(`migration`,`asc`).get(),t={};return e.forEach(e=>{t[e.migration]=e.batch}),t}async log(e,t){await this.connection.table(this.table).insert({migration:e,batch:t})}async delete(e){await this.connection.table(this.table).where(`migration`,e.migration).delete()}async getNextBatchNumber(){return await this.getLastBatchNumber()+1}async getLastBatchNumber(){let e=await this.connection.table(this.table).max(`batch`);return e===null?0:Number(e)}async createRepository(){this.connection.getAdapter(),await this.connection.query(`
|
|
2
2
|
CREATE TABLE IF NOT EXISTS ${this.table} (
|
|
3
3
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
4
4
|
migration VARCHAR(255) NOT NULL,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MigrationRepository.mjs","names":[],"sources":["../../../src/Database/Migrations/MigrationRepository.ts"],"sourcesContent":["/**\n * MigrationRepository\n *\n * Manages the migrations table that tracks which migrations have been run\n */\n\nimport { Connection } from '@/Database/Connection';\n\nexport interface MigrationData {\n id?: number;\n migration: string;\n batch: number;\n}\n\nexport class MigrationRepository {\n protected table: string = 'migrations';\n\n constructor(protected connection: Connection) {}\n\n /**\n * Get the migrations that have been run\n */\n async getRan(): Promise<string[]> {\n const results = await this.connection.table(this.table).orderBy('batch', 'asc').orderBy('migration', 'asc').get();\n\n return results.map((row: any) => row.migration);\n }\n\n /**\n * Get the list of migrations\n */\n async getMigrations(steps?: number): Promise<MigrationData[]> {\n const query = this.connection.table(this.table).orderBy('batch', 'desc').orderBy('migration', 'desc');\n\n if (steps !== undefined && steps > 0) {\n query.limit(steps);\n }\n\n return await query.get();\n }\n\n /**\n * Get the last migration batch\n */\n async getLast(): Promise<MigrationData[]> {\n const batch = await this.getLastBatchNumber();\n\n if (batch === 0) {\n return [];\n }\n\n return await this.connection.table(this.table).where('batch', batch).orderBy('migration', 'desc').get();\n }\n\n /**\n * Get the migrations for a batch\n */\n async getMigrationBatches(): Promise<Record<string, number>> {\n const results = await this.connection.table(this.table).orderBy('batch', 'asc').orderBy('migration', 'asc').get();\n\n const batches: Record<string, number> = {};\n results.forEach((row: any) => {\n batches[row.migration] = row.batch;\n });\n\n return batches;\n }\n\n /**\n * Log that a migration was run\n */\n async log(file: string, batch: number): Promise<void> {\n await this.connection.table(this.table).insert({\n migration: file,\n batch,\n });\n }\n\n /**\n * Remove a migration from the log\n */\n async delete(migration: MigrationData): Promise<void> {\n await this.connection.table(this.table).where('migration', migration.migration).delete();\n }\n\n /**\n * Get the next migration batch number\n */\n async getNextBatchNumber(): Promise<number> {\n return (await this.getLastBatchNumber()) + 1;\n }\n\n /**\n * Get the last migration batch number\n */\n async getLastBatchNumber(): Promise<number> {\n const result = await this.connection.table(this.table).max('batch');\n\n return result !== null ? Number(result) : 0;\n }\n\n /**\n * Create the migration repository table\n */\n async createRepository(): Promise<void> {\n const schema = this.connection.getAdapter();\n\n await this.connection.query(`\n CREATE TABLE IF NOT EXISTS ${this.table} (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n migration VARCHAR(255) NOT NULL,\n batch INTEGER NOT NULL\n )\n `);\n }\n\n /**\n * Determine if the migration repository exists\n */\n async repositoryExists(): Promise<boolean> {\n try {\n await this.connection.table(this.table).limit(1).get();\n return true;\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Delete the migration repository\n */\n async deleteRepository(): Promise<void> {\n await this.connection.query(`DROP TABLE IF EXISTS ${this.table}`);\n }\n\n /**\n * Set the information source to gather data\n */\n setSource(name: string): void {\n // Reserved for future use with different connections\n }\n}\n"],"mappings":"AAcA,IAAa,EAAb,KAAiC,
|
|
1
|
+
{"version":3,"file":"MigrationRepository.mjs","names":[],"sources":["../../../src/Database/Migrations/MigrationRepository.ts"],"sourcesContent":["/**\n * MigrationRepository\n *\n * Manages the migrations table that tracks which migrations have been run\n */\n\nimport { Connection } from '@/Database/Connection';\n\nexport interface MigrationData {\n id?: number;\n migration: string;\n batch: number;\n}\n\nexport class MigrationRepository {\n protected table: string = 'migrations';\n\n constructor(protected connection: Connection) {}\n\n /**\n * Get the migrations that have been run\n */\n async getRan(): Promise<string[]> {\n const results = await this.connection.table(this.table).orderBy('batch', 'asc').orderBy('migration', 'asc').get();\n\n return results.map((row: any) => row.migration);\n }\n\n /**\n * Get the list of migrations\n */\n async getMigrations(steps?: number): Promise<MigrationData[]> {\n const query = this.connection.table(this.table).orderBy('batch', 'desc').orderBy('migration', 'desc');\n\n if (steps !== undefined && steps > 0) {\n query.limit(steps);\n }\n\n return await query.get();\n }\n\n /**\n * Get the last migration batch\n */\n async getLast(): Promise<MigrationData[]> {\n const batch = await this.getLastBatchNumber();\n\n if (batch === 0) {\n return [];\n }\n\n return await this.connection.table(this.table).where('batch', batch).orderBy('migration', 'desc').get();\n }\n\n /**\n * Get the migrations for a batch\n */\n async getMigrationBatches(): Promise<Record<string, number>> {\n const results = await this.connection.table(this.table).orderBy('batch', 'asc').orderBy('migration', 'asc').get();\n\n const batches: Record<string, number> = {};\n results.forEach((row: any) => {\n batches[row.migration] = row.batch;\n });\n\n return batches;\n }\n\n /**\n * Log that a migration was run\n */\n async log(file: string, batch: number): Promise<void> {\n await this.connection.table(this.table).insert({\n migration: file,\n batch,\n });\n }\n\n /**\n * Remove a migration from the log\n */\n async delete(migration: MigrationData): Promise<void> {\n await this.connection.table(this.table).where('migration', migration.migration).delete();\n }\n\n /**\n * Get the next migration batch number\n */\n async getNextBatchNumber(): Promise<number> {\n return (await this.getLastBatchNumber()) + 1;\n }\n\n /**\n * Get the last migration batch number\n */\n async getLastBatchNumber(): Promise<number> {\n const result = await this.connection.table(this.table).max('batch');\n\n return result !== null ? Number(result) : 0;\n }\n\n /**\n * Create the migration repository table\n */\n async createRepository(): Promise<void> {\n const schema = this.connection.getAdapter();\n\n await this.connection.query(`\n CREATE TABLE IF NOT EXISTS ${this.table} (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n migration VARCHAR(255) NOT NULL,\n batch INTEGER NOT NULL\n )\n `);\n }\n\n /**\n * Determine if the migration repository exists\n */\n async repositoryExists(): Promise<boolean> {\n try {\n await this.connection.table(this.table).limit(1).get();\n return true;\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Delete the migration repository\n */\n async deleteRepository(): Promise<void> {\n await this.connection.query(`DROP TABLE IF EXISTS ${this.table}`);\n }\n\n /**\n * Set the information source to gather data\n */\n setSource(name: string): void {\n // Reserved for future use with different connections\n }\n}\n"],"mappings":"AAcA,IAAa,EAAb,KAAiC,CAGT,WAFtB,MAA0B,aAE1B,YAAY,EAAkC,CAAxB,KAAA,WAAA,EAKtB,MAAM,QAA4B,CAGhC,OAAO,MAFe,KAAK,WAAW,MAAM,KAAK,MAAM,CAAC,QAAQ,QAAS,MAAM,CAAC,QAAQ,YAAa,MAAM,CAAC,KAAK,EAElG,IAAK,GAAa,EAAI,UAAU,CAMjD,MAAM,cAAc,EAA0C,CAC5D,IAAM,EAAQ,KAAK,WAAW,MAAM,KAAK,MAAM,CAAC,QAAQ,QAAS,OAAO,CAAC,QAAQ,YAAa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AAK,WAAW,MAAM,wBAAwB,KAAK,QAAQ,CAMnE,UAAU,EAAoB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const e=require(`../../_virtual/_rolldown/runtime.cjs`),t=require(`./MigrationRepository.cjs`),n=require(`./SchemaBuilder.cjs`);let r=require(`path`);r=e.__toESM(r);let i=require(`fs`);i=e.__toESM(i);var a=class{repository;schema;constructor(e,r){this.connection=e,this.paths=r,this.repository=new t.MigrationRepository(e),this.schema=new n.SchemaBuilder(e)}async run(e={}){let t=[];await this.repository.createRepository();let n=await this.getMigrationFiles(),r=await this.repository.getRan(),i=n.filter(e=>!r.includes(e));if(i.length===0)return[];let a=await this.repository.getNextBatchNumber();for(let n of i)await this.runUp(n,a,e.pretend||!1),t.push(n);return t}async runUp(e,t,n){let r=await this.resolveMigration(e);if(n){console.log(`Would run: ${e}`);return}await r.up(this.schema),await this.repository.log(e,t)}async rollback(e={}){let t=[],n=await this.getMigrationsForRollback(e);if(n.length===0)return[];for(let r of n)await this.runDown(r.migration,e.pretend||!1),t.push(r.migration);return t}async runDown(e,t){let n=await this.resolveMigration(e);if(t){console.log(`Would rollback: ${e}`);return}await n.down(this.schema),await this.repository.delete({migration:e,batch:0})}async reset(){let e=[],t=await this.repository.getMigrations();if(t.length===0)return[];t.reverse();for(let n of t)await this.runDown(n.migration,!1),e.push(n.migration);return e}async dropAllTables(){let e=await this.connection.getTables();for(let t of e)await this.connection.query(`DROP TABLE IF EXISTS ${t}`)}async refresh(){return{rolledBack:await this.reset(),ran:await this.run()}}async getMigrationsForRollback(e){return e.step&&e.step>0?await this.repository.getMigrations(e.step):await this.repository.getLast()}async resolveMigration(e){let t=await this.findMigrationFile(e);if(!t)throw Error(`Migration file not found: ${e}`);let n=await import(t),r=n.default||Object.values(n)[0];if(!r)throw Error(`No migration class found in: ${e}`);return new r}async findMigrationFile(e){for(let t of this.paths){let n=r.join(t,e);if(i.existsSync(n+`.ts`))return n+`.ts`;if(i.existsSync(n+`.js`))return n+`.js`;if(i.existsSync(n))return n}return null}async getMigrationFiles(){let e=[];for(let t of this.paths){if(!i.existsSync(t))continue;let n=i.readdirSync(t);for(let t of n)t.match(/\.(ts|js)$/)&&e.push(t.replace(/\.(ts|js)$/,``))}return Array.from(new Set(e)).sort()}async getRan(){return await this.repository.getRan()}async getMigrationBatches(){return await this.repository.getMigrationBatches()}getRepository(){return this.repository}setPaths(e){this.paths=e}getPaths(){return this.paths}};exports.Migrator=a;
|
|
1
|
+
const e=require(`../../_virtual/_rolldown/runtime.cjs`),t=require(`./MigrationRepository.cjs`),n=require(`./SchemaBuilder.cjs`);let r=require(`path`);r=e.__toESM(r,1);let i=require(`fs`);i=e.__toESM(i,1);var a=class{connection;paths;repository;schema;constructor(e,r){this.connection=e,this.paths=r,this.repository=new t.MigrationRepository(e),this.schema=new n.SchemaBuilder(e)}async run(e={}){let t=[];await this.repository.createRepository();let n=await this.getMigrationFiles(),r=await this.repository.getRan(),i=n.filter(e=>!r.includes(e));if(i.length===0)return[];let a=await this.repository.getNextBatchNumber();for(let n of i)await this.runUp(n,a,e.pretend||!1),t.push(n);return t}async runUp(e,t,n){let r=await this.resolveMigration(e);if(n){console.log(`Would run: ${e}`);return}await r.up(this.schema),await this.repository.log(e,t)}async rollback(e={}){let t=[],n=await this.getMigrationsForRollback(e);if(n.length===0)return[];for(let r of n)await this.runDown(r.migration,e.pretend||!1),t.push(r.migration);return t}async runDown(e,t){let n=await this.resolveMigration(e);if(t){console.log(`Would rollback: ${e}`);return}await n.down(this.schema),await this.repository.delete({migration:e,batch:0})}async reset(){let e=[],t=await this.repository.getMigrations();if(t.length===0)return[];t.reverse();for(let n of t)await this.runDown(n.migration,!1),e.push(n.migration);return e}async dropAllTables(){let e=await this.connection.getTables();for(let t of e)await this.connection.query(`DROP TABLE IF EXISTS ${t}`)}async refresh(){return{rolledBack:await this.reset(),ran:await this.run()}}async getMigrationsForRollback(e){return e.step&&e.step>0?await this.repository.getMigrations(e.step):await this.repository.getLast()}async resolveMigration(e){let t=await this.findMigrationFile(e);if(!t)throw Error(`Migration file not found: ${e}`);let n=await import(t),r=n.default||Object.values(n)[0];if(!r)throw Error(`No migration class found in: ${e}`);return new r}async findMigrationFile(e){for(let t of this.paths){let n=r.join(t,e);if(i.existsSync(n+`.ts`))return n+`.ts`;if(i.existsSync(n+`.js`))return n+`.js`;if(i.existsSync(n))return n}return null}async getMigrationFiles(){let e=[];for(let t of this.paths){if(!i.existsSync(t))continue;let n=i.readdirSync(t);for(let t of n)t.match(/\.(ts|js)$/)&&e.push(t.replace(/\.(ts|js)$/,``))}return Array.from(new Set(e)).sort()}async getRan(){return await this.repository.getRan()}async getMigrationBatches(){return await this.repository.getMigrationBatches()}getRepository(){return this.repository}setPaths(e){this.paths=e}getPaths(){return this.paths}};exports.Migrator=a;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{MigrationRepository as e}from"./MigrationRepository.mjs";import{SchemaBuilder as t}from"./SchemaBuilder.mjs";import*as n from"path";import*as r from"fs";var i=class{repository;schema;constructor(n,r){this.connection=n,this.paths=r,this.repository=new e(n),this.schema=new t(n)}async run(e={}){let t=[];await this.repository.createRepository();let n=await this.getMigrationFiles(),r=await this.repository.getRan(),i=n.filter(e=>!r.includes(e));if(i.length===0)return[];let a=await this.repository.getNextBatchNumber();for(let n of i)await this.runUp(n,a,e.pretend||!1),t.push(n);return t}async runUp(e,t,n){let r=await this.resolveMigration(e);if(n){console.log(`Would run: ${e}`);return}await r.up(this.schema),await this.repository.log(e,t)}async rollback(e={}){let t=[],n=await this.getMigrationsForRollback(e);if(n.length===0)return[];for(let r of n)await this.runDown(r.migration,e.pretend||!1),t.push(r.migration);return t}async runDown(e,t){let n=await this.resolveMigration(e);if(t){console.log(`Would rollback: ${e}`);return}await n.down(this.schema),await this.repository.delete({migration:e,batch:0})}async reset(){let e=[],t=await this.repository.getMigrations();if(t.length===0)return[];t.reverse();for(let n of t)await this.runDown(n.migration,!1),e.push(n.migration);return e}async dropAllTables(){let e=await this.connection.getTables();for(let t of e)await this.connection.query(`DROP TABLE IF EXISTS ${t}`)}async refresh(){return{rolledBack:await this.reset(),ran:await this.run()}}async getMigrationsForRollback(e){return e.step&&e.step>0?await this.repository.getMigrations(e.step):await this.repository.getLast()}async resolveMigration(e){let t=await this.findMigrationFile(e);if(!t)throw Error(`Migration file not found: ${e}`);let n=await import(t),r=n.default||Object.values(n)[0];if(!r)throw Error(`No migration class found in: ${e}`);return new r}async findMigrationFile(e){for(let t of this.paths){let i=n.join(t,e);if(r.existsSync(i+`.ts`))return i+`.ts`;if(r.existsSync(i+`.js`))return i+`.js`;if(r.existsSync(i))return i}return null}async getMigrationFiles(){let e=[];for(let t of this.paths){if(!r.existsSync(t))continue;let n=r.readdirSync(t);for(let t of n)t.match(/\.(ts|js)$/)&&e.push(t.replace(/\.(ts|js)$/,``))}return Array.from(new Set(e)).sort()}async getRan(){return await this.repository.getRan()}async getMigrationBatches(){return await this.repository.getMigrationBatches()}getRepository(){return this.repository}setPaths(e){this.paths=e}getPaths(){return this.paths}};export{i as Migrator};
|
|
1
|
+
import{MigrationRepository as e}from"./MigrationRepository.mjs";import{SchemaBuilder as t}from"./SchemaBuilder.mjs";import*as n from"path";import*as r from"fs";var i=class{connection;paths;repository;schema;constructor(n,r){this.connection=n,this.paths=r,this.repository=new e(n),this.schema=new t(n)}async run(e={}){let t=[];await this.repository.createRepository();let n=await this.getMigrationFiles(),r=await this.repository.getRan(),i=n.filter(e=>!r.includes(e));if(i.length===0)return[];let a=await this.repository.getNextBatchNumber();for(let n of i)await this.runUp(n,a,e.pretend||!1),t.push(n);return t}async runUp(e,t,n){let r=await this.resolveMigration(e);if(n){console.log(`Would run: ${e}`);return}await r.up(this.schema),await this.repository.log(e,t)}async rollback(e={}){let t=[],n=await this.getMigrationsForRollback(e);if(n.length===0)return[];for(let r of n)await this.runDown(r.migration,e.pretend||!1),t.push(r.migration);return t}async runDown(e,t){let n=await this.resolveMigration(e);if(t){console.log(`Would rollback: ${e}`);return}await n.down(this.schema),await this.repository.delete({migration:e,batch:0})}async reset(){let e=[],t=await this.repository.getMigrations();if(t.length===0)return[];t.reverse();for(let n of t)await this.runDown(n.migration,!1),e.push(n.migration);return e}async dropAllTables(){let e=await this.connection.getTables();for(let t of e)await this.connection.query(`DROP TABLE IF EXISTS ${t}`)}async refresh(){return{rolledBack:await this.reset(),ran:await this.run()}}async getMigrationsForRollback(e){return e.step&&e.step>0?await this.repository.getMigrations(e.step):await this.repository.getLast()}async resolveMigration(e){let t=await this.findMigrationFile(e);if(!t)throw Error(`Migration file not found: ${e}`);let n=await import(t),r=n.default||Object.values(n)[0];if(!r)throw Error(`No migration class found in: ${e}`);return new r}async findMigrationFile(e){for(let t of this.paths){let i=n.join(t,e);if(r.existsSync(i+`.ts`))return i+`.ts`;if(r.existsSync(i+`.js`))return i+`.js`;if(r.existsSync(i))return i}return null}async getMigrationFiles(){let e=[];for(let t of this.paths){if(!r.existsSync(t))continue;let n=r.readdirSync(t);for(let t of n)t.match(/\.(ts|js)$/)&&e.push(t.replace(/\.(ts|js)$/,``))}return Array.from(new Set(e)).sort()}async getRan(){return await this.repository.getRan()}async getMigrationBatches(){return await this.repository.getMigrationBatches()}getRepository(){return this.repository}setPaths(e){this.paths=e}getPaths(){return this.paths}};export{i as Migrator};
|
|
2
2
|
//# sourceMappingURL=Migrator.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Migrator.mjs","names":[],"sources":["../../../src/Database/Migrations/Migrator.ts"],"sourcesContent":["/**\n * Migrator\n *\n * Handles running and rolling back migrations\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { Connection } from '@/Database/Connection';\nimport { Migration } from './Migration';\nimport { MigrationRepository } from './MigrationRepository';\nimport { SchemaBuilder } from './SchemaBuilder';\n\nexport interface MigrationOptions {\n step?: number;\n pretend?: boolean;\n}\n\nexport class Migrator {\n protected repository: MigrationRepository;\n protected schema: SchemaBuilder;\n\n constructor(\n protected connection: Connection,\n protected paths: string[]\n ) {\n this.repository = new MigrationRepository(connection);\n this.schema = new SchemaBuilder(connection);\n }\n\n /**\n * Run the pending migrations\n */\n async run(options: MigrationOptions = {}): Promise<string[]> {\n const ran: string[] = [];\n\n // Ensure the migrations repository exists\n await this.repository.createRepository();\n\n const files = await this.getMigrationFiles();\n const ranMigrations = await this.repository.getRan();\n\n const pending = files.filter((file) => !ranMigrations.includes(file));\n\n if (pending.length === 0) {\n return [];\n }\n\n const batch = await this.repository.getNextBatchNumber();\n\n for (const file of pending) {\n await this.runUp(file, batch, options.pretend || false);\n ran.push(file);\n }\n\n return ran;\n }\n\n /**\n * Run a single migration up\n */\n protected async runUp(file: string, batch: number, pretend: boolean): Promise<void> {\n const migration = await this.resolveMigration(file);\n\n if (pretend) {\n console.log(`Would run: ${file}`);\n return;\n }\n\n await migration.up(this.schema);\n await this.repository.log(file, batch);\n }\n\n /**\n * Rollback the last migration batch\n */\n async rollback(options: MigrationOptions = {}): Promise<string[]> {\n const rolledBack: string[] = [];\n\n const migrations = await this.getMigrationsForRollback(options);\n\n if (migrations.length === 0) {\n return [];\n }\n\n for (const migration of migrations) {\n await this.runDown(migration.migration, options.pretend || false);\n rolledBack.push(migration.migration);\n }\n\n return rolledBack;\n }\n\n /**\n * Run a single migration down\n */\n protected async runDown(file: string, pretend: boolean): Promise<void> {\n const migration = await this.resolveMigration(file);\n\n if (pretend) {\n console.log(`Would rollback: ${file}`);\n return;\n }\n\n await migration.down(this.schema);\n await this.repository.delete({ migration: file, batch: 0 });\n }\n\n /**\n * Reset all migrations\n */\n async reset(): Promise<string[]> {\n const rolledBack: string[] = [];\n\n const migrations = await this.repository.getMigrations();\n\n if (migrations.length === 0) {\n return [];\n }\n\n // Reverse the order for rollback\n migrations.reverse();\n\n for (const migration of migrations) {\n await this.runDown(migration.migration, false);\n rolledBack.push(migration.migration);\n }\n\n return rolledBack;\n }\n\n /**\n * Drop all tables in the connected database.\n *\n * Unlike reset(), this does not rely on migration records or down() methods.\n * It queries the database's own schema catalog for every table name and\n * issues a DROP TABLE IF EXISTS for each one, giving a truly clean slate\n * regardless of whether migrations were tracked.\n */\n async dropAllTables(): Promise<void> {\n const tables = await this.connection.getTables();\n\n for (const table of tables) {\n await this.connection.query(`DROP TABLE IF EXISTS ${table}`);\n }\n }\n\n /**\n * Refresh the database (reset and re-run all migrations)\n */\n async refresh(): Promise<{ rolledBack: string[]; ran: string[] }> {\n const rolledBack = await this.reset();\n const ran = await this.run();\n\n return { rolledBack, ran };\n }\n\n /**\n * Get migrations for rollback\n */\n protected async getMigrationsForRollback(options: MigrationOptions): Promise<any[]> {\n if (options.step && options.step > 0) {\n return await this.repository.getMigrations(options.step);\n }\n\n return await this.repository.getLast();\n }\n\n /**\n * Resolve a migration instance from a file\n */\n protected async resolveMigration(file: string): Promise<Migration> {\n const migrationPath = await this.findMigrationFile(file);\n\n if (!migrationPath) {\n throw new Error(`Migration file not found: ${file}`);\n }\n\n // Import the migration file\n const migrationModule = await import(migrationPath);\n\n // Get the default export or the first class export\n const MigrationClass = migrationModule.default || Object.values(migrationModule)[0];\n\n if (!MigrationClass) {\n throw new Error(`No migration class found in: ${file}`);\n }\n\n return new (MigrationClass as any)();\n }\n\n /**\n * Find a migration file in the paths\n */\n protected async findMigrationFile(file: string): Promise<string | null> {\n for (const searchPath of this.paths) {\n const fullPath = path.join(searchPath, file);\n\n // Try with .ts extension\n if (fs.existsSync(fullPath + '.ts')) {\n return fullPath + '.ts';\n }\n\n // Try with .js extension\n if (fs.existsSync(fullPath + '.js')) {\n return fullPath + '.js';\n }\n\n // Try without extension\n if (fs.existsSync(fullPath)) {\n return fullPath;\n }\n }\n\n return null;\n }\n\n /**\n * Get all migration files\n */\n async getMigrationFiles(): Promise<string[]> {\n const files: string[] = [];\n\n for (const searchPath of this.paths) {\n if (!fs.existsSync(searchPath)) {\n continue;\n }\n\n const dirFiles = fs.readdirSync(searchPath);\n\n for (const file of dirFiles) {\n if (file.match(/\\.(ts|js)$/)) {\n files.push(file.replace(/\\.(ts|js)$/, ''));\n }\n }\n }\n\n // Remove duplicates and sort\n return Array.from(new Set(files)).sort();\n }\n\n /**\n * Get the ran migrations\n */\n async getRan(): Promise<string[]> {\n return await this.repository.getRan();\n }\n\n /**\n * Get migrations with their batch numbers\n */\n async getMigrationBatches(): Promise<Record<string, number>> {\n return await this.repository.getMigrationBatches();\n }\n\n /**\n * Get the migration repository\n */\n getRepository(): MigrationRepository {\n return this.repository;\n }\n\n /**\n * Set the migration paths\n */\n setPaths(paths: string[]): void {\n this.paths = paths;\n }\n\n /**\n * Get the migration paths\n */\n getPaths(): string[] {\n return this.paths;\n }\n}\n"],"mappings":"gKAkBA,IAAa,EAAb,KAAsB,
|
|
1
|
+
{"version":3,"file":"Migrator.mjs","names":[],"sources":["../../../src/Database/Migrations/Migrator.ts"],"sourcesContent":["/**\n * Migrator\n *\n * Handles running and rolling back migrations\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { Connection } from '@/Database/Connection';\nimport { Migration } from './Migration';\nimport { MigrationRepository } from './MigrationRepository';\nimport { SchemaBuilder } from './SchemaBuilder';\n\nexport interface MigrationOptions {\n step?: number;\n pretend?: boolean;\n}\n\nexport class Migrator {\n protected repository: MigrationRepository;\n protected schema: SchemaBuilder;\n\n constructor(\n protected connection: Connection,\n protected paths: string[]\n ) {\n this.repository = new MigrationRepository(connection);\n this.schema = new SchemaBuilder(connection);\n }\n\n /**\n * Run the pending migrations\n */\n async run(options: MigrationOptions = {}): Promise<string[]> {\n const ran: string[] = [];\n\n // Ensure the migrations repository exists\n await this.repository.createRepository();\n\n const files = await this.getMigrationFiles();\n const ranMigrations = await this.repository.getRan();\n\n const pending = files.filter((file) => !ranMigrations.includes(file));\n\n if (pending.length === 0) {\n return [];\n }\n\n const batch = await this.repository.getNextBatchNumber();\n\n for (const file of pending) {\n await this.runUp(file, batch, options.pretend || false);\n ran.push(file);\n }\n\n return ran;\n }\n\n /**\n * Run a single migration up\n */\n protected async runUp(file: string, batch: number, pretend: boolean): Promise<void> {\n const migration = await this.resolveMigration(file);\n\n if (pretend) {\n console.log(`Would run: ${file}`);\n return;\n }\n\n await migration.up(this.schema);\n await this.repository.log(file, batch);\n }\n\n /**\n * Rollback the last migration batch\n */\n async rollback(options: MigrationOptions = {}): Promise<string[]> {\n const rolledBack: string[] = [];\n\n const migrations = await this.getMigrationsForRollback(options);\n\n if (migrations.length === 0) {\n return [];\n }\n\n for (const migration of migrations) {\n await this.runDown(migration.migration, options.pretend || false);\n rolledBack.push(migration.migration);\n }\n\n return rolledBack;\n }\n\n /**\n * Run a single migration down\n */\n protected async runDown(file: string, pretend: boolean): Promise<void> {\n const migration = await this.resolveMigration(file);\n\n if (pretend) {\n console.log(`Would rollback: ${file}`);\n return;\n }\n\n await migration.down(this.schema);\n await this.repository.delete({ migration: file, batch: 0 });\n }\n\n /**\n * Reset all migrations\n */\n async reset(): Promise<string[]> {\n const rolledBack: string[] = [];\n\n const migrations = await this.repository.getMigrations();\n\n if (migrations.length === 0) {\n return [];\n }\n\n // Reverse the order for rollback\n migrations.reverse();\n\n for (const migration of migrations) {\n await this.runDown(migration.migration, false);\n rolledBack.push(migration.migration);\n }\n\n return rolledBack;\n }\n\n /**\n * Drop all tables in the connected database.\n *\n * Unlike reset(), this does not rely on migration records or down() methods.\n * It queries the database's own schema catalog for every table name and\n * issues a DROP TABLE IF EXISTS for each one, giving a truly clean slate\n * regardless of whether migrations were tracked.\n */\n async dropAllTables(): Promise<void> {\n const tables = await this.connection.getTables();\n\n for (const table of tables) {\n await this.connection.query(`DROP TABLE IF EXISTS ${table}`);\n }\n }\n\n /**\n * Refresh the database (reset and re-run all migrations)\n */\n async refresh(): Promise<{ rolledBack: string[]; ran: string[] }> {\n const rolledBack = await this.reset();\n const ran = await this.run();\n\n return { rolledBack, ran };\n }\n\n /**\n * Get migrations for rollback\n */\n protected async getMigrationsForRollback(options: MigrationOptions): Promise<any[]> {\n if (options.step && options.step > 0) {\n return await this.repository.getMigrations(options.step);\n }\n\n return await this.repository.getLast();\n }\n\n /**\n * Resolve a migration instance from a file\n */\n protected async resolveMigration(file: string): Promise<Migration> {\n const migrationPath = await this.findMigrationFile(file);\n\n if (!migrationPath) {\n throw new Error(`Migration file not found: ${file}`);\n }\n\n // Import the migration file\n const migrationModule = await import(migrationPath);\n\n // Get the default export or the first class export\n const MigrationClass = migrationModule.default || Object.values(migrationModule)[0];\n\n if (!MigrationClass) {\n throw new Error(`No migration class found in: ${file}`);\n }\n\n return new (MigrationClass as any)();\n }\n\n /**\n * Find a migration file in the paths\n */\n protected async findMigrationFile(file: string): Promise<string | null> {\n for (const searchPath of this.paths) {\n const fullPath = path.join(searchPath, file);\n\n // Try with .ts extension\n if (fs.existsSync(fullPath + '.ts')) {\n return fullPath + '.ts';\n }\n\n // Try with .js extension\n if (fs.existsSync(fullPath + '.js')) {\n return fullPath + '.js';\n }\n\n // Try without extension\n if (fs.existsSync(fullPath)) {\n return fullPath;\n }\n }\n\n return null;\n }\n\n /**\n * Get all migration files\n */\n async getMigrationFiles(): Promise<string[]> {\n const files: string[] = [];\n\n for (const searchPath of this.paths) {\n if (!fs.existsSync(searchPath)) {\n continue;\n }\n\n const dirFiles = fs.readdirSync(searchPath);\n\n for (const file of dirFiles) {\n if (file.match(/\\.(ts|js)$/)) {\n files.push(file.replace(/\\.(ts|js)$/, ''));\n }\n }\n }\n\n // Remove duplicates and sort\n return Array.from(new Set(files)).sort();\n }\n\n /**\n * Get the ran migrations\n */\n async getRan(): Promise<string[]> {\n return await this.repository.getRan();\n }\n\n /**\n * Get migrations with their batch numbers\n */\n async getMigrationBatches(): Promise<Record<string, number>> {\n return await this.repository.getMigrationBatches();\n }\n\n /**\n * Get the migration repository\n */\n getRepository(): MigrationRepository {\n return this.repository;\n }\n\n /**\n * Set the migration paths\n */\n setPaths(paths: string[]): void {\n this.paths = paths;\n }\n\n /**\n * Get the migration paths\n */\n getPaths(): string[] {\n return this.paths;\n }\n}\n"],"mappings":"gKAkBA,IA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jC,OAAO,EAAW,MAIpB,GAAI,EAAG,WAAW,EAAS,CACzB,OAAO,EAIX,OAAO,KAMT,MAAM,mBAAuC,CAC3C,IAAM,EAAkB,EAAE,CAE1B,IAAK,IAAM,KAAc,KAAK,MAAO,CACnC,GAAI,CAAC,EAAG,WAAW,EAAW,CAC5B,SAGF,IAAM,EAAW,EAAG,YAAY,EAAW,CAE3C,IAAK,IAAM,KAAQ,EACb,EAAK,MAAM,aAAa,EAC1B,EAAM,KAAK,EAAK,QAAQ,aAAc,GAAG,CAAC,CAMhD,OAAO,MAAM,KAAK,IAAI,IAAI,EAAM,CAAC,CAAC,MAAM,CAM1C,MAAM,QAA4B,CAChC,OAAO,MAAM,KAAK,WAAW,QAAQ,CAMvC,MAAM,qBAAuD,CAC3D,OAAO,MAAM,KAAK,WAAW,qBAAqB,CAMpD,eAAqC,CACnC,OAAO,KAAK,WAMd,SAAS,EAAuB,CAC9B,KAAK,MAAQ,EAMf,UAAqB,CACnB,OAAO,KAAK"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
require(`../../_virtual/_rolldown/runtime.cjs`);const e=require(`./Blueprint.cjs`);var t=class{driver;constructor(e){this.connection=e,this.driver=e.getConfig().driver}async create(t,n){let r=new e.Blueprint(t);r.isCreate=!0,n(r);let i=this.compileCreate(r);await this.connection.query(i);for(let e of r.indexes){let n=this.compileIndex(t,e);n&&await this.connection.query(n)}for(let e of r.foreignKeys){let n=this.compileForeignKey(t,e);n&&await this.connection.query(n)}}async drop(e){let t=`DROP TABLE ${this.wrapTable(e)}`;await this.connection.query(t)}async dropIfExists(e){let t=`DROP TABLE IF EXISTS ${this.wrapTable(e)}`;await this.connection.query(t)}async rename(e,t){let n=this.compileRename(e,t);await this.connection.query(n)}async hasTable(e){let t=this.compileHasTable(e);return(await this.connection.select(t)).length>0}async hasColumn(e,t){let n=this.compileHasColumn(e,t);return(await this.connection.select(n)).length>0}async table(t,n){let r=new e.Blueprint(t);r.isCreate=!1,n(r);for(let e of r.columns){let n=this.compileAddColumn(t,e);await this.connection.query(n)}for(let e of r.commands){let n=this.compileCommand(t,e);n&&await this.connection.query(n)}for(let e of r.indexes){let n=this.compileIndex(t,e);n&&await this.connection.query(n)}for(let e of r.foreignKeys){let n=this.compileForeignKey(t,e);n&&await this.connection.query(n)}}compileCreate(e){let t=e.columns.map(e=>this.compileColumnDefinition(e)).join(`, `),n=`CREATE TABLE ${this.wrapTable(e.table)} (${t}`,r=e.indexes.find(e=>e.type===`primary`);return r&&(n+=`, PRIMARY KEY (${r.columns.map(e=>this.wrap(e)).join(`, `)})`),n+=`)`,n}compileColumnDefinition(e){let t=this.wrap(e.name)+` `+this.getColumnType(e);return e.isAutoIncrement&&(t+=this.getAutoIncrementClause(e)),!e.isNullable&&!e.isAutoIncrement&&(t+=` NOT NULL`),e.defaultValue!==void 0&&(t+=` DEFAULT `+this.getDefaultValue(e.defaultValue)),t}getColumnType(e){switch(this.driver){case`sqlite`:return this.getSQLiteColumnType(e);case`postgres`:case`postgresql`:return this.getPostgresColumnType(e);case`mysql`:return this.getMySQLColumnType(e);default:return this.getSQLiteColumnType(e)}}getSQLiteColumnType(e){switch(e.type){case`bigIncrements`:case`increments`:return`INTEGER`;case`bigInteger`:case`integer`:case`smallInteger`:case`tinyInteger`:return`INTEGER`;case`string`:case`uuid`:return e.length?`VARCHAR(${e.length})`:`VARCHAR(255)`;case`text`:case`mediumText`:case`longText`:return`TEXT`;case`decimal`:case`float`:case`double`:return`REAL`;case`boolean`:return`INTEGER`;case`date`:return`DATE`;case`datetime`:case`timestamp`:return`DATETIME`;case`json`:case`jsonb`:return`TEXT`;case`binary`:return`BLOB`;case`enum`:return`TEXT`;default:return`TEXT`}}getPostgresColumnType(e){switch(e.type){case`bigIncrements`:return`BIGSERIAL`;case`increments`:return`SERIAL`;case`bigInteger`:return`BIGINT`;case`integer`:return`INTEGER`;case`smallInteger`:return`SMALLINT`;case`tinyInteger`:return`SMALLINT`;case`string`:return e.length?`VARCHAR(${e.length})`:`VARCHAR(255)`;case`uuid`:return`UUID`;case`text`:return`TEXT`;case`mediumText`:case`longText`:return`TEXT`;case`decimal`:return e.precision&&e.scale?`DECIMAL(${e.precision}, ${e.scale})`:`DECIMAL(8, 2)`;case`float`:return`REAL`;case`double`:return`DOUBLE PRECISION`;case`boolean`:return`BOOLEAN`;case`date`:return`DATE`;case`datetime`:return e.precision?`TIMESTAMP(${e.precision})`:`TIMESTAMP`;case`timestamp`:return e.precision?`TIMESTAMP(${e.precision})`:`TIMESTAMP`;case`json`:return`JSON`;case`jsonb`:return`JSONB`;case`binary`:return`BYTEA`;case`enum`:return`VARCHAR(255)`;default:return`TEXT`}}getMySQLColumnType(e){switch(e.type){case`bigIncrements`:return`BIGINT UNSIGNED AUTO_INCREMENT`;case`increments`:return`INT UNSIGNED AUTO_INCREMENT`;case`bigInteger`:return e.isUnsigned?`BIGINT UNSIGNED`:`BIGINT`;case`integer`:return e.isUnsigned?`INT UNSIGNED`:`INT`;case`smallInteger`:return e.isUnsigned?`SMALLINT UNSIGNED`:`SMALLINT`;case`tinyInteger`:return e.isUnsigned?`TINYINT UNSIGNED`:`TINYINT`;case`string`:return e.length?`VARCHAR(${e.length})`:`VARCHAR(255)`;case`uuid`:return`CHAR(36)`;case`text`:return`TEXT`;case`mediumText`:return`MEDIUMTEXT`;case`longText`:return`LONGTEXT`;case`decimal`:return e.precision&&e.scale?`DECIMAL(${e.precision}, ${e.scale})`:`DECIMAL(8, 2)`;case`float`:return e.precision&&e.scale?`FLOAT(${e.precision}, ${e.scale})`:`FLOAT`;case`double`:return e.precision&&e.scale?`DOUBLE(${e.precision}, ${e.scale})`:`DOUBLE`;case`boolean`:return`TINYINT(1)`;case`date`:return`DATE`;case`datetime`:return e.precision?`DATETIME(${e.precision})`:`DATETIME`;case`timestamp`:return e.precision?`TIMESTAMP(${e.precision})`:`TIMESTAMP`;case`json`:return`JSON`;case`jsonb`:return`JSON`;case`binary`:return`BLOB`;case`enum`:return e.enumValues?`ENUM(${e.enumValues.map(e=>`'${e}'`).join(`, `)})`:`VARCHAR(255)`;default:return`TEXT`}}getAutoIncrementClause(e){switch(this.driver){case`sqlite`:return e.isPrimary?` PRIMARY KEY AUTOINCREMENT`:``;case`postgres`:case`postgresql`:return``;case`mysql`:return``;default:return e.isPrimary?` PRIMARY KEY AUTOINCREMENT`:``}}getDefaultValue(e){return e===null?`NULL`:typeof e==`string`?`'${e}'`:typeof e==`boolean`?this.driver===`postgres`||this.driver===`postgresql`?e?`TRUE`:`FALSE`:e?`1`:`0`:String(e)}compileAddColumn(e,t){let n=this.compileColumnDefinition(t);return`ALTER TABLE ${this.wrapTable(e)} ADD COLUMN ${n}`}compileCommand(e,t){switch(t.type){case`dropColumn`:return this.compileDropColumn(e,t.columns);case`dropIndex`:return this.compileDropIndex(e,t.name);case`dropForeign`:return this.compileDropForeign(e,t.name);case`renameColumn`:return this.compileRenameColumn(e,t.from,t.to);default:return null}}compileDropColumn(e,t){let n=t.map(e=>`DROP COLUMN ${this.wrap(e)}`).join(`, `);return`ALTER TABLE ${this.wrapTable(e)} ${n}`}compileDropIndex(e,t){return this.driver===`mysql`?`ALTER TABLE ${this.wrapTable(e)} DROP INDEX ${this.wrap(t)}`:`DROP INDEX ${this.wrap(t)}`}compileDropForeign(e,t){return`ALTER TABLE ${this.wrapTable(e)} DROP FOREIGN KEY ${this.wrap(t)}`}compileRenameColumn(e,t,n){return this.driver,`ALTER TABLE ${this.wrapTable(e)} RENAME COLUMN ${this.wrap(t)} TO ${this.wrap(n)}`}compileIndex(e,t){if(t.type===`primary`)return null;let n=t.columns.map(e=>this.wrap(e)).join(`, `),r=t.name||this.createIndexName(e,t.columns,t.type);return t.type===`unique`?`CREATE UNIQUE INDEX ${this.wrap(r)} ON ${this.wrapTable(e)} (${n})`:`CREATE INDEX ${this.wrap(r)} ON ${this.wrapTable(e)} (${n})`}compileForeignKey(e,t){if(!t.referencedTable||!t.referencedColumns)return null;let n=t.columns.map(e=>this.wrap(e)).join(`, `),r=t.referencedColumns.map(e=>this.wrap(e)).join(`, `),i=t.name||this.createForeignKeyName(e,t.columns),a=`ALTER TABLE ${this.wrapTable(e)} ADD CONSTRAINT ${this.wrap(i)} `;return a+=`FOREIGN KEY (${n}) REFERENCES ${this.wrapTable(t.referencedTable)} (${r})`,t.onDeleteAction&&(a+=` ON DELETE ${t.onDeleteAction.toUpperCase()}`),t.onUpdateAction&&(a+=` ON UPDATE ${t.onUpdateAction.toUpperCase()}`),a}compileRename(e,t){return`ALTER TABLE ${this.wrapTable(e)} RENAME TO ${this.wrapTable(t)}`}compileHasTable(e){switch(this.driver){case`sqlite`:return`SELECT name FROM sqlite_master WHERE type='table' AND name='${e}'`;case`postgres`:case`postgresql`:return`SELECT tablename FROM pg_tables WHERE tablename='${e}'`;case`mysql`:return`SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME='${e}'`;default:return`SELECT name FROM sqlite_master WHERE type='table' AND name='${e}'`}}compileHasColumn(e,t){switch(this.driver){case`sqlite`:return`PRAGMA table_info(${e})`;case`postgres`:case`postgresql`:return`SELECT column_name FROM information_schema.columns WHERE table_name='${e}' AND column_name='${t}'`;case`mysql`:return`SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_NAME='${e}' AND COLUMN_NAME='${t}'`;default:return`PRAGMA table_info(${e})`}}createIndexName(e,t,n){let r=n===`unique`?`unique`:`index`;return`${e}_${t.join(`_`)}_${r}`}createForeignKeyName(e,t){return`${e}_${t.join(`_`)}_foreign`}wrapTable(e){return this.wrap(e)}wrap(e){switch(this.driver){case`postgres`:case`postgresql`:return`"${e}"`;case`mysql`:return`\`${e}\``;default:return`"${e}"`}}};exports.SchemaBuilder=t;
|
|
1
|
+
require(`../../_virtual/_rolldown/runtime.cjs`);const e=require(`./Blueprint.cjs`);var t=class{connection;driver;constructor(e){this.connection=e,this.driver=e.getConfig().driver}async create(t,n){let r=new e.Blueprint(t);r.isCreate=!0,n(r);let i=this.compileCreate(r);await this.connection.query(i);for(let e of r.indexes){let n=this.compileIndex(t,e);n&&await this.connection.query(n)}for(let e of r.foreignKeys){let n=this.compileForeignKey(t,e);n&&await this.connection.query(n)}}async drop(e){let t=`DROP TABLE ${this.wrapTable(e)}`;await this.connection.query(t)}async dropIfExists(e){let t=`DROP TABLE IF EXISTS ${this.wrapTable(e)}`;await this.connection.query(t)}async rename(e,t){let n=this.compileRename(e,t);await this.connection.query(n)}async hasTable(e){let t=this.compileHasTable(e);return(await this.connection.select(t)).length>0}async hasColumn(e,t){let n=this.compileHasColumn(e,t);return(await this.connection.select(n)).length>0}async table(t,n){let r=new e.Blueprint(t);r.isCreate=!1,n(r);for(let e of r.columns){let n=this.compileAddColumn(t,e);await this.connection.query(n)}for(let e of r.commands){let n=this.compileCommand(t,e);n&&await this.connection.query(n)}for(let e of r.indexes){let n=this.compileIndex(t,e);n&&await this.connection.query(n)}for(let e of r.foreignKeys){let n=this.compileForeignKey(t,e);n&&await this.connection.query(n)}}compileCreate(e){let t=e.columns.map(e=>this.compileColumnDefinition(e)).join(`, `),n=`CREATE TABLE ${this.wrapTable(e.table)} (${t}`,r=e.indexes.find(e=>e.type===`primary`);return r&&(n+=`, PRIMARY KEY (${r.columns.map(e=>this.wrap(e)).join(`, `)})`),n+=`)`,n}compileColumnDefinition(e){let t=this.wrap(e.name)+` `+this.getColumnType(e);return e.isAutoIncrement&&(t+=this.getAutoIncrementClause(e)),!e.isNullable&&!e.isAutoIncrement&&(t+=` NOT NULL`),e.defaultValue!==void 0&&(t+=` DEFAULT `+this.getDefaultValue(e.defaultValue)),t}getColumnType(e){switch(this.driver){case`sqlite`:return this.getSQLiteColumnType(e);case`postgres`:case`postgresql`:return this.getPostgresColumnType(e);case`mysql`:return this.getMySQLColumnType(e);default:return this.getSQLiteColumnType(e)}}getSQLiteColumnType(e){switch(e.type){case`bigIncrements`:case`increments`:return`INTEGER`;case`bigInteger`:case`integer`:case`smallInteger`:case`tinyInteger`:return`INTEGER`;case`string`:case`uuid`:return e.length?`VARCHAR(${e.length})`:`VARCHAR(255)`;case`text`:case`mediumText`:case`longText`:return`TEXT`;case`decimal`:case`float`:case`double`:return`REAL`;case`boolean`:return`INTEGER`;case`date`:return`DATE`;case`datetime`:case`timestamp`:return`DATETIME`;case`json`:case`jsonb`:return`TEXT`;case`binary`:return`BLOB`;case`enum`:return`TEXT`;default:return`TEXT`}}getPostgresColumnType(e){switch(e.type){case`bigIncrements`:return`BIGSERIAL`;case`increments`:return`SERIAL`;case`bigInteger`:return`BIGINT`;case`integer`:return`INTEGER`;case`smallInteger`:return`SMALLINT`;case`tinyInteger`:return`SMALLINT`;case`string`:return e.length?`VARCHAR(${e.length})`:`VARCHAR(255)`;case`uuid`:return`UUID`;case`text`:return`TEXT`;case`mediumText`:case`longText`:return`TEXT`;case`decimal`:return e.precision&&e.scale?`DECIMAL(${e.precision}, ${e.scale})`:`DECIMAL(8, 2)`;case`float`:return`REAL`;case`double`:return`DOUBLE PRECISION`;case`boolean`:return`BOOLEAN`;case`date`:return`DATE`;case`datetime`:return e.precision?`TIMESTAMP(${e.precision})`:`TIMESTAMP`;case`timestamp`:return e.precision?`TIMESTAMP(${e.precision})`:`TIMESTAMP`;case`json`:return`JSON`;case`jsonb`:return`JSONB`;case`binary`:return`BYTEA`;case`enum`:return`VARCHAR(255)`;default:return`TEXT`}}getMySQLColumnType(e){switch(e.type){case`bigIncrements`:return`BIGINT UNSIGNED AUTO_INCREMENT`;case`increments`:return`INT UNSIGNED AUTO_INCREMENT`;case`bigInteger`:return e.isUnsigned?`BIGINT UNSIGNED`:`BIGINT`;case`integer`:return e.isUnsigned?`INT UNSIGNED`:`INT`;case`smallInteger`:return e.isUnsigned?`SMALLINT UNSIGNED`:`SMALLINT`;case`tinyInteger`:return e.isUnsigned?`TINYINT UNSIGNED`:`TINYINT`;case`string`:return e.length?`VARCHAR(${e.length})`:`VARCHAR(255)`;case`uuid`:return`CHAR(36)`;case`text`:return`TEXT`;case`mediumText`:return`MEDIUMTEXT`;case`longText`:return`LONGTEXT`;case`decimal`:return e.precision&&e.scale?`DECIMAL(${e.precision}, ${e.scale})`:`DECIMAL(8, 2)`;case`float`:return e.precision&&e.scale?`FLOAT(${e.precision}, ${e.scale})`:`FLOAT`;case`double`:return e.precision&&e.scale?`DOUBLE(${e.precision}, ${e.scale})`:`DOUBLE`;case`boolean`:return`TINYINT(1)`;case`date`:return`DATE`;case`datetime`:return e.precision?`DATETIME(${e.precision})`:`DATETIME`;case`timestamp`:return e.precision?`TIMESTAMP(${e.precision})`:`TIMESTAMP`;case`json`:return`JSON`;case`jsonb`:return`JSON`;case`binary`:return`BLOB`;case`enum`:return e.enumValues?`ENUM(${e.enumValues.map(e=>`'${e}'`).join(`, `)})`:`VARCHAR(255)`;default:return`TEXT`}}getAutoIncrementClause(e){switch(this.driver){case`sqlite`:return e.isPrimary?` PRIMARY KEY AUTOINCREMENT`:``;case`postgres`:case`postgresql`:return``;case`mysql`:return``;default:return e.isPrimary?` PRIMARY KEY AUTOINCREMENT`:``}}getDefaultValue(e){return e===null?`NULL`:typeof e==`string`?`'${e}'`:typeof e==`boolean`?this.driver===`postgres`||this.driver===`postgresql`?e?`TRUE`:`FALSE`:e?`1`:`0`:String(e)}compileAddColumn(e,t){let n=this.compileColumnDefinition(t);return`ALTER TABLE ${this.wrapTable(e)} ADD COLUMN ${n}`}compileCommand(e,t){switch(t.type){case`dropColumn`:return this.compileDropColumn(e,t.columns);case`dropIndex`:return this.compileDropIndex(e,t.name);case`dropForeign`:return this.compileDropForeign(e,t.name);case`renameColumn`:return this.compileRenameColumn(e,t.from,t.to);default:return null}}compileDropColumn(e,t){let n=t.map(e=>`DROP COLUMN ${this.wrap(e)}`).join(`, `);return`ALTER TABLE ${this.wrapTable(e)} ${n}`}compileDropIndex(e,t){return this.driver===`mysql`?`ALTER TABLE ${this.wrapTable(e)} DROP INDEX ${this.wrap(t)}`:`DROP INDEX ${this.wrap(t)}`}compileDropForeign(e,t){return`ALTER TABLE ${this.wrapTable(e)} DROP FOREIGN KEY ${this.wrap(t)}`}compileRenameColumn(e,t,n){return this.driver,`ALTER TABLE ${this.wrapTable(e)} RENAME COLUMN ${this.wrap(t)} TO ${this.wrap(n)}`}compileIndex(e,t){if(t.type===`primary`)return null;let n=t.columns.map(e=>this.wrap(e)).join(`, `),r=t.name||this.createIndexName(e,t.columns,t.type);return t.type===`unique`?`CREATE UNIQUE INDEX ${this.wrap(r)} ON ${this.wrapTable(e)} (${n})`:`CREATE INDEX ${this.wrap(r)} ON ${this.wrapTable(e)} (${n})`}compileForeignKey(e,t){if(!t.referencedTable||!t.referencedColumns)return null;let n=t.columns.map(e=>this.wrap(e)).join(`, `),r=t.referencedColumns.map(e=>this.wrap(e)).join(`, `),i=t.name||this.createForeignKeyName(e,t.columns),a=`ALTER TABLE ${this.wrapTable(e)} ADD CONSTRAINT ${this.wrap(i)} `;return a+=`FOREIGN KEY (${n}) REFERENCES ${this.wrapTable(t.referencedTable)} (${r})`,t.onDeleteAction&&(a+=` ON DELETE ${t.onDeleteAction.toUpperCase()}`),t.onUpdateAction&&(a+=` ON UPDATE ${t.onUpdateAction.toUpperCase()}`),a}compileRename(e,t){return`ALTER TABLE ${this.wrapTable(e)} RENAME TO ${this.wrapTable(t)}`}compileHasTable(e){switch(this.driver){case`sqlite`:return`SELECT name FROM sqlite_master WHERE type='table' AND name='${e}'`;case`postgres`:case`postgresql`:return`SELECT tablename FROM pg_tables WHERE tablename='${e}'`;case`mysql`:return`SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME='${e}'`;default:return`SELECT name FROM sqlite_master WHERE type='table' AND name='${e}'`}}compileHasColumn(e,t){switch(this.driver){case`sqlite`:return`PRAGMA table_info(${e})`;case`postgres`:case`postgresql`:return`SELECT column_name FROM information_schema.columns WHERE table_name='${e}' AND column_name='${t}'`;case`mysql`:return`SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_NAME='${e}' AND COLUMN_NAME='${t}'`;default:return`PRAGMA table_info(${e})`}}createIndexName(e,t,n){let r=n===`unique`?`unique`:`index`;return`${e}_${t.join(`_`)}_${r}`}createForeignKeyName(e,t){return`${e}_${t.join(`_`)}_foreign`}wrapTable(e){return this.wrap(e)}wrap(e){switch(this.driver){case`postgres`:case`postgresql`:return`"${e}"`;case`mysql`:return`\`${e}\``;default:return`"${e}"`}}};exports.SchemaBuilder=t;
|