* Sync all defined models to the DB. * * @param {object} [options={}] sync options * @param {boolean} [options.force=false] If force is true, each Model will run `DROP TABLE IF EXISTS`, before it tries to create its own table * @param {RegExp} [options.match] Match a regex against the da
(options)
| 786 | * @returns {Promise} |
| 787 | */ |
| 788 | async sync(options) { |
| 789 | options = { |
| 790 | ...this.options, |
| 791 | ...this.options.sync, |
| 792 | ...options, |
| 793 | hooks: options ? options.hooks !== false : true |
| 794 | }; |
| 795 | |
| 796 | if (options.match) { |
| 797 | if (!options.match.test(this.config.database)) { |
| 798 | throw new Error(`Database "${this.config.database}" does not match sync match parameter "${options.match}"`); |
| 799 | } |
| 800 | } |
| 801 | |
| 802 | if (options.hooks) { |
| 803 | await this.runHooks('beforeBulkSync', options); |
| 804 | } |
| 805 | |
| 806 | if (options.force) { |
| 807 | await this.drop(options); |
| 808 | } |
| 809 | |
| 810 | // no models defined, just authenticate |
| 811 | if (this.modelManager.models.length === 0) { |
| 812 | await this.authenticate(options); |
| 813 | } else { |
| 814 | const models = this.modelManager.getModelsTopoSortedByForeignKey(); |
| 815 | if (models == null) { |
| 816 | return this._syncModelsWithCyclicReferences(options); |
| 817 | } |
| 818 | |
| 819 | // reverse to start with the one model that does not depend on anything |
| 820 | models.reverse(); |
| 821 | |
| 822 | // Topologically sort by foreign key constraints to give us an appropriate |
| 823 | // creation order |
| 824 | for (const model of models) { |
| 825 | await model.sync(options); |
| 826 | } |
| 827 | } |
| 828 | |
| 829 | if (options.hooks) { |
| 830 | await this.runHooks('afterBulkSync', options); |
| 831 | } |
| 832 | |
| 833 | return this; |
| 834 | } |
| 835 | |
| 836 | /** |
| 837 | * Used instead of sync() when two models reference each-other, so their foreign keys cannot be created immediately. |
no test coverage detected