From 145ee860ccdb847bb30e5c05c76e02befa69c44c Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Sat, 16 Sep 2023 15:35:22 +0530 Subject: [PATCH 01/70] refactor: migrate connection and db modules --- .env | 52 +- .github/COMMIT_CONVENTION.md | 70 - .github/CONTRIBUTING.md | 46 - .github/ISSUE_TEMPLATE/bug_report.md | 29 - .github/ISSUE_TEMPLATE/feature_request.md | 28 - .github/PULL_REQUEST_TEMPLATE.md | 28 - .github/labels.json | 170 + .github/workflows/test.yml | 12 +- .husky/commit-msg | 7 +- LICENSE.md | 2 +- adonis-typings/container.ts | 32 +- adonis-typings/database.ts | 1420 ++++---- adonis-typings/events.ts | 8 +- adonis-typings/factory.ts | 643 ++-- adonis-typings/index.ts | 22 - adonis-typings/migrator.ts | 109 +- adonis-typings/model.ts | 2091 ++++++------ adonis-typings/orm.ts | 64 - adonis-typings/querybuilder.ts | 1507 +++++---- adonis-typings/relations.ts | 1724 +++++----- adonis-typings/schema.ts | 43 +- adonis-typings/seeder.ts | 36 +- adonis-typings/test-utils.ts | 21 - adonis-typings/test_utils.ts | 21 + adonis-typings/validator.ts | 34 +- bin/japaTypes.ts | 2 - bin/test.ts | 22 +- docker-compose.yml | 99 + package.json | 205 +- scripts/Dockerfile | 20 - scripts/docker-compose.yml | 75 - scripts/run-tests.sh | 9 - src/Factory/FactoryContext.ts | 5 +- src/Migrator/MigrationSource.ts | 5 +- src/Orm/Relations/HasMany/SubQueryBuilder.ts | 6 +- src/Orm/Relations/HasOne/SubQueryBuilder.ts | 6 +- src/Orm/Relations/KeysExtractor.ts | 41 +- src/Orm/Relations/ManyToMany/QueryClient.ts | 11 +- .../snake_case.ts} | 21 +- src/SeedsRunner/SeedersSource.ts | 5 +- src/TestUtils/Migration.ts | 5 +- src/TestUtils/Seeder.ts | 5 +- src/TestUtils/Truncator.ts | 5 +- src/{Connection => connection}/index.ts | 91 +- .../Logger.ts => connection/logger.ts} | 15 +- .../Manager.ts => connection/manager.ts} | 47 +- src/{Database => database}/index.ts | 123 +- .../paginator/simple_paginator.ts} | 54 +- .../query_builder/chainable.ts} | 351 +- .../query_builder/database.ts} | 65 +- .../query_builder/insert.ts} | 63 +- .../Raw.ts => database/query_builder/raw.ts} | 44 +- .../Raw.ts => database/static_builder/raw.ts} | 17 +- .../static_builder/reference.ts} | 19 +- .../SqliteBase.ts => dialects/base_sqlite.ts} | 47 +- .../better_sqlite.ts} | 8 +- src/{Dialects => dialects}/index.ts | 30 +- src/{Dialects/Mssql.ts => dialects/mssql.ts} | 49 +- src/{Dialects/Mysql.ts => dialects/mysql.ts} | 49 +- .../Oracle.ts => dialects/oracle.ts} | 40 +- src/{Dialects/Pg.ts => dialects/pg.ts} | 47 +- .../Redshift.ts => dialects/red_shift.ts} | 47 +- .../Sqlite.ts => dialects/sqlite.ts} | 8 +- .../pretty_print.ts} | 19 +- src/{Helpers => helpers}/scope.ts | 6 +- src/{QueryClient => query_client}/index.ts | 137 +- .../index.ts | 31 +- src/{QueryRunner => query_runner}/index.ts | 20 +- .../index.ts | 115 +- src/utils/index.ts | 108 +- test-helpers/index.ts | 151 +- test/connection/connection.spec.ts | 51 +- ...ger.spec.ts => connection_manager.spec.ts} | 63 +- test/database/database.spec.ts | 191 +- ...rop-tables.spec.ts => drop_tables.spec.ts} | 29 +- ...r.spec.ts => insert_query_builder.spec.ts} | 33 +- ...-builder.spec.ts => query_builder.spec.ts} | 2857 ++++++++--------- ...ry-client.spec.ts => query_client.spec.ts} | 126 +- test/database/transaction_client.spec.ts | 265 ++ test/database/transactions.spec.ts | 422 --- ...iews-types.spec.ts => views_types.spec.ts} | 41 +- test/orm/base-model.spec.ts | 7 +- tsconfig.json | 14 +- 83 files changed, 6749 insertions(+), 7917 deletions(-) delete mode 100644 .github/COMMIT_CONVENTION.md delete mode 100644 .github/CONTRIBUTING.md delete mode 100644 .github/ISSUE_TEMPLATE/bug_report.md delete mode 100644 .github/ISSUE_TEMPLATE/feature_request.md delete mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .github/labels.json delete mode 100644 adonis-typings/index.ts delete mode 100644 adonis-typings/orm.ts delete mode 100644 adonis-typings/test-utils.ts create mode 100644 adonis-typings/test_utils.ts delete mode 100644 bin/japaTypes.ts create mode 100644 docker-compose.yml delete mode 100644 scripts/Dockerfile delete mode 100644 scripts/docker-compose.yml delete mode 100644 scripts/run-tests.sh rename src/Orm/{NamingStrategies/SnakeCase.ts => naming_strategies/snake_case.ts} (79%) rename src/{Connection => connection}/index.ts (85%) rename src/{Connection/Logger.ts => connection/logger.ts} (64%) rename src/{Connection/Manager.ts => connection/manager.ts} (84%) rename src/{Database => database}/index.ts (72%) rename src/{Database/Paginator/SimplePaginator.ts => database/paginator/simple_paginator.ts} (75%) rename src/{Database/QueryBuilder/Chainable.ts => database/query_builder/chainable.ts} (81%) rename src/{Database/QueryBuilder/Database.ts => database/query_builder/database.ts} (84%) rename src/{Database/QueryBuilder/Insert.ts => database/query_builder/insert.ts} (74%) rename src/{Database/QueryBuilder/Raw.ts => database/query_builder/raw.ts} (71%) rename src/{Database/StaticBuilder/Raw.ts => database/static_builder/raw.ts} (70%) rename src/{Database/StaticBuilder/Reference.ts => database/static_builder/reference.ts} (66%) rename src/{Dialects/SqliteBase.ts => dialects/base_sqlite.ts} (71%) rename src/{Dialects/BetterSqlite.ts => dialects/better_sqlite.ts} (58%) rename src/{Dialects => dialects}/index.ts (56%) rename src/{Dialects/Mssql.ts => dialects/mssql.ts} (72%) rename src/{Dialects/Mysql.ts => dialects/mysql.ts} (76%) rename src/{Dialects/Oracle.ts => dialects/oracle.ts} (65%) rename src/{Dialects/Pg.ts => dialects/pg.ts} (74%) rename src/{Dialects/Redshift.ts => dialects/red_shift.ts} (77%) rename src/{Dialects/Sqlite.ts => dialects/sqlite.ts} (58%) rename src/{Helpers/prettyPrint.ts => helpers/pretty_print.ts} (75%) rename src/{Helpers => helpers}/scope.ts (68%) rename src/{QueryClient => query_client}/index.ts (62%) rename src/{QueryReporter => query_reporter}/index.ts (65%) rename src/{QueryRunner => query_runner}/index.ts (86%) rename src/{TransactionClient => transaction_client}/index.ts (66%) rename test/connection/{connection-manager.spec.ts => connection_manager.spec.ts} (77%) rename test/database/{drop-tables.spec.ts => drop_tables.spec.ts} (75%) rename test/database/{insert-query-builder.spec.ts => insert_query_builder.spec.ts} (75%) rename test/database/{query-builder.spec.ts => query_builder.spec.ts} (78%) rename test/database/{query-client.spec.ts => query_client.spec.ts} (70%) create mode 100644 test/database/transaction_client.spec.ts delete mode 100644 test/database/transactions.spec.ts rename test/database/{views-types.spec.ts => views_types.spec.ts} (71%) diff --git a/.env b/.env index 23d45e62..b2c94830 100644 --- a/.env +++ b/.env @@ -1,31 +1,39 @@ -DB=pg -DB_NAME=lucid +LEGACY_MYSQL_HOST=localhost +LEGACY_MYSQL_PASSWORD=secret +LEGACY_MYSQL_DATABASE=lucid +LEGACY_MYSQL_PORT=3306 +LEGACY_MYSQL_USER=virk + +LEGACY_MYSQL_READ_REPLICA_HOST=localhost +LEGACY_MYSQL_READ_REPLICA_PASSWORD=secret +LEGACY_MYSQL_READ_REPLICA_DATABASE=lucid +LEGACY_MYSQL_READ_REPLICA_PORT=3307 +LEGACY_MYSQL_READ_REPLICA_USER=virk MYSQL_HOST=localhost -MYSQL_PORT=3306 +MYSQL_PASSWORD=secret +MYSQL_DATABASE=lucid +MYSQL_PORT=3308 MYSQL_USER=virk -MYSQL_PASSWORD=password - -MYSQL_LEGACY_HOST=localhost -MYSQL_LEGACY_PORT=3306 -MYSQL_LEGACY_USER=virk -MYSQL_LEGACY_PASSWORD=password - -MYSQL_REPLICA_1_HOST=localhost -MYSQL_REPLICA_1_PORT=3306 -MYSQL_REPLICA_1_USER=virk -MYSQL_REPLICA_1_PASSWORD=password - -MYSQL_REPLICA_2_HOST=localhost -MYSQL_REPLICA_2_PORT=3306 -MYSQL_REPLICA_2_USER=virk -MYSQL_REPLICA_2_PASSWORD=password PG_HOST=localhost +PG_PASSWORD=secret +PG_DATABASE=lucid PG_PORT=5432 PG_USER=virk -PG_PASSWORD=password -MSSQL_SERVER=localhost +PG_READ_REPLICA_HOST=localhost +PG_READ_REPLICA_PASSWORD=secret +PG_READ_REPLICA_DATABASE=lucid +PG_READ_REPLICA_PORT=5433 +PG_READ_REPLICA_USER=virk + +MSSQL_HOST=localhost +MSSQL_PASSWORD=secrearandom&233passwordt +MSSQL_PORT=1433 MSSQL_USER=sa -MSSQL_PASSWORD=arandom&233password + +MSSQL_READ_REPLICA_HOST=localhost +MSSQL_READ_REPLICA_PASSWORD=secrearandom&233passwordt +MSSQL_READ_REPLICA_PORT=1434 +MSSQL_READ_REPLICA_USER=sa diff --git a/.github/COMMIT_CONVENTION.md b/.github/COMMIT_CONVENTION.md deleted file mode 100644 index fc852aff..00000000 --- a/.github/COMMIT_CONVENTION.md +++ /dev/null @@ -1,70 +0,0 @@ -## Git Commit Message Convention - -> This is adapted from [Angular's commit convention](https://github.com/conventional-changelog/conventional-changelog/tree/master/packages/conventional-changelog-angular). - -Using conventional commit messages, we can automate the process of generating the CHANGELOG file. All commits messages will automatically be validated against the following regex. - -``` js -/^(revert: )?(feat|fix|docs|style|refactor|perf|test|workflow|ci|chore|types|build|improvement)((.+))?: .{1,50}/ -``` - -## Commit Message Format -A commit message consists of a **header**, **body** and **footer**. The header has a **type**, **scope** and **subject**: - -> The **scope** is optional - -``` -feat(router): add support for prefix - -Prefix makes it easier to append a path to a group of routes -``` - -1. `feat` is type. -2. `router` is scope and is optional -3. `add support for prefix` is the subject -4. The **body** is followed by a blank line. -5. The optional **footer** can be added after the body, followed by a blank line. - -## Types -Only one type can be used at a time and only following types are allowed. - -- feat -- fix -- docs -- style -- refactor -- perf -- test -- workflow -- ci -- chore -- types -- build - -If a type is `feat`, `fix` or `perf`, then the commit will appear in the CHANGELOG.md file. However if there is any BREAKING CHANGE, the commit will always appear in the changelog. - -### Revert -If the commit reverts a previous commit, it should begin with `revert:`, followed by the header of the reverted commit. In the body it should say: `This reverts commit `., where the hash is the SHA of the commit being reverted. - -## Scope -The scope could be anything specifying place of the commit change. For example: `router`, `view`, `querybuilder`, `database`, `model` and so on. - -## Subject -The subject contains succinct description of the change: - -- use the imperative, present tense: "change" not "changed" nor "changes". -- don't capitalize first letter -- no dot (.) at the end - -## Body - -Just as in the **subject**, use the imperative, present tense: "change" not "changed" nor "changes". -The body should include the motivation for the change and contrast this with previous behavior. - -## Footer - -The footer should contain any information about **Breaking Changes** and is also the place to -reference GitHub issues that this commit **Closes**. - -**Breaking Changes** should start with the word `BREAKING CHANGE:` with a space or two newlines. The rest of the commit message is then used for this. - diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md deleted file mode 100644 index f0c5446f..00000000 --- a/.github/CONTRIBUTING.md +++ /dev/null @@ -1,46 +0,0 @@ -# Contributing - -AdonisJS is a community driven project. You are free to contribute in any of the following ways. - -- [Coding style](coding-style) -- [Fix bugs by creating PR's](fix-bugs-by-creating-prs) -- [Share an RFC for new features or big changes](share-an-rfc-for-new-features-or-big-changes) -- [Report security issues](report-security-issues) -- [Be a part of the community](be-a-part-of-community) - -## Coding style - -Majority of AdonisJS core packages are written in Typescript. Having a brief knowledge of Typescript is required to contribute to the core. - -## Fix bugs by creating PR's - -We appreciate every time you report a bug in the framework or related libraries. However, taking time to submit a PR can help us in fixing bugs quickly and ensure a healthy and stable eco-system. - -Go through the following points, before creating a new PR. - -1. Create an issue discussing the bug or short-coming in the framework. -2. Once approved, go ahead and fork the REPO. -3. Make sure to start from the `develop`, since this is the upto date branch. -4. Make sure to keep commits small and relevant. -5. We follow [conventional-commits](https://github.com/conventional-changelog/conventional-changelog) to structure our commit messages. Instead of running `git commit`, you must run `npm commit`, which will show you prompts to create a valid commit message. -6. Once done with all the changes, create a PR against the `develop` branch. - -## Share an RFC for new features or big changes - -Sharing PR's for small changes works great. However, when contributing big features to the framework, it is required to go through the RFC process. - -### What is an RFC? - -RFC stands for **Request for Commits**, a standard process followed by many other frameworks including [Ember](https://github.com/emberjs/rfcs), [yarn](https://github.com/yarnpkg/rfcs) and [rust](https://github.com/rust-lang/rfcs). - -In brief, RFC process allows you to talk about the changes with everyone in the community and get a view of the core team before dedicating your time to work on the feature. - -The RFC proposals are created as Pull Request on [adonisjs/rfcs](https://github.com/adonisjs/rfcs) repo. Make sure to read the README to learn about the process in depth. - -## Report security issues - -All of the security issues, must be reported via [email](mailto:virk@adonisjs.com) and not using any of the public channels. - -## Be a part of community - -We welcome you to participate in [GitHub Discussion](https://github.com/adonisjs/core/discussions) and the AdonisJS [Discord Server](https://discord.gg/vDcEjq6). You are free to ask your questions and share your work or contributions made to AdonisJS eco-system. diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index e65000c3..00000000 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -name: Bug report -about: Report identified bugs ---- - - - -## Prerequisites - -We do our best to reply to all the issues on time. If you will follow the given guidelines, the turn around time will be faster. - -- Lots of raised issues are directly not bugs but instead are design decisions taken by us. -- Make use of our [GH discussions](https://github.com/adonisjs/core/discussions), or [discord server](https://discord.me/adonisjs), if you are not sure that you are reporting a bug. -- Ensure the issue isn't already reported. -- Ensure you are reporting the bug in the correct repo. - -*Delete the above section and the instructions in the sections below before submitting* - -## Package version - - -## Node.js and npm version - - -## Sample Code (to reproduce the issue) - - -## BONUS (a sample repo to reproduce the issue) - diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md deleted file mode 100644 index abd44a59..00000000 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -name: Feature request -about: Propose changes for adding a new feature ---- - - - -## Prerequisites - -We do our best to reply to all the issues on time. If you will follow the given guidelines, the turn around time will be faster. - -## Consider an RFC - -Please create an [RFC](https://github.com/adonisjs/rfcs) instead, if - -- Feature introduces a breaking change -- Demands lots of time and changes in the current code base. - -*Delete the above section and the instructions in the sections below before submitting* - -## Why this feature is required (specific use-cases will be appreciated)? - - -## Have you tried any other work arounds? - - -## Are you willing to work on it with little guidance? - diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index ddaf1f2c..00000000 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,28 +0,0 @@ - - -## Proposed changes - -Describe the big picture of your changes here to communicate to the maintainers why we should accept this pull request. If it fixes a bug or resolves a feature request, be sure to link to that issue. - -## Types of changes - -What types of changes does your code introduce? - -_Put an `x` in the boxes that apply_ - -- [ ] Bugfix (non-breaking change which fixes an issue) -- [ ] New feature (non-breaking change which adds functionality) -- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - -## Checklist - -_Put an `x` in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your code._ - -- [ ] I have read the [CONTRIBUTING](https://github.com/adonisjs/lucid/blob/master/.github/CONTRIBUTING.md) doc -- [ ] Lint and unit tests pass locally with my changes -- [ ] I have added tests that prove my fix is effective or that my feature works. -- [ ] I have added necessary documentation (if appropriate) - -## Further comments - -If this is a relatively large or complex change, kick off the discussion by explaining why you chose the solution you did and what alternatives you considered, etc... diff --git a/.github/labels.json b/.github/labels.json new file mode 100644 index 00000000..ba001c60 --- /dev/null +++ b/.github/labels.json @@ -0,0 +1,170 @@ +[ + { + "name": "Priority: Critical", + "color": "ea0056", + "description": "The issue needs urgent attention", + "aliases": [] + }, + { + "name": "Priority: High", + "color": "5666ed", + "description": "Look into this issue before picking up any new work", + "aliases": [] + }, + { + "name": "Priority: Medium", + "color": "f4ff61", + "description": "Try to fix the issue for the next patch/minor release", + "aliases": [] + }, + { + "name": "Priority: Low", + "color": "87dfd6", + "description": "Something worth considering, but not a top priority for the team", + "aliases": [] + }, + { + "name": "Semver: Alpha", + "color": "008480", + "description": "Will make it's way to the next alpha version of the package", + "aliases": [] + }, + { + "name": "Semver: Major", + "color": "ea0056", + "description": "Has breaking changes", + "aliases": [] + }, + { + "name": "Semver: Minor", + "color": "fbe555", + "description": "Mainly new features and improvements", + "aliases": [] + }, + { + "name": "Semver: Next", + "color": "5666ed", + "description": "Will make it's way to the bleeding edge version of the package", + "aliases": [] + }, + { + "name": "Semver: Patch", + "color": "87dfd6", + "description": "A bug fix", + "aliases": [] + }, + { + "name": "Status: Abandoned", + "color": "ffffff", + "description": "Dropped and not into consideration", + "aliases": ["wontfix"] + }, + { + "name": "Status: Accepted", + "color": "e5fbf2", + "description": "The proposal or the feature has been accepted for the future versions", + "aliases": [] + }, + { + "name": "Status: Blocked", + "color": "ea0056", + "description": "The work on the issue or the PR is blocked. Check comments for reasoning", + "aliases": [] + }, + { + "name": "Status: Completed", + "color": "008672", + "description": "The work has been completed, but not released yet", + "aliases": [] + }, + { + "name": "Status: In Progress", + "color": "73dbc4", + "description": "Still banging the keyboard", + "aliases": ["in progress"] + }, + { + "name": "Status: On Hold", + "color": "f4ff61", + "description": "The work was started earlier, but is on hold now. Check comments for reasoning", + "aliases": ["On Hold"] + }, + { + "name": "Status: Review Needed", + "color": "fbe555", + "description": "Review from the core team is required before moving forward", + "aliases": [] + }, + { + "name": "Status: Awaiting More Information", + "color": "89f8ce", + "description": "Waiting on the issue reporter or PR author to provide more information", + "aliases": [] + }, + { + "name": "Status: Need Contributors", + "color": "7057ff", + "description": "Looking for contributors to help us move forward with this issue or PR", + "aliases": [] + }, + { + "name": "Type: Bug", + "color": "ea0056", + "description": "The issue has indentified a bug", + "aliases": ["bug"] + }, + { + "name": "Type: Security", + "color": "ea0056", + "description": "Spotted security vulnerability and is a top priority for the core team", + "aliases": [] + }, + { + "name": "Type: Duplicate", + "color": "00837e", + "description": "Already answered or fixed previously", + "aliases": ["duplicate"] + }, + { + "name": "Type: Enhancement", + "color": "89f8ce", + "description": "Improving an existing feature", + "aliases": ["enhancement"] + }, + { + "name": "Type: Feature Request", + "color": "483add", + "description": "Request to add a new feature to the package", + "aliases": [] + }, + { + "name": "Type: Invalid", + "color": "dbdbdb", + "description": "Doesn't really belong here. Maybe use discussion threads?", + "aliases": ["invalid"] + }, + { + "name": "Type: Question", + "color": "eceafc", + "description": "Needs clarification", + "aliases": ["help wanted", "question"] + }, + { + "name": "Type: Documentation Change", + "color": "7057ff", + "description": "Documentation needs some improvements", + "aliases": ["documentation"] + }, + { + "name": "Type: Dependencies Update", + "color": "00837e", + "description": "Bump dependencies", + "aliases": ["dependencies"] + }, + { + "name": "Good First Issue", + "color": "008480", + "description": "Want to contribute? Just filter by this label", + "aliases": ["good first issue"] + } +] diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b2ffb9fe..096083b8 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -10,7 +10,7 @@ jobs: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: - node-version: 16 + node-version: 20 - run: npm install - run: npm run lint @@ -20,7 +20,7 @@ jobs: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: - node-version: 16 + node-version: 20 - run: npm install - run: npx tsc @@ -29,7 +29,7 @@ jobs: strategy: fail-fast: false matrix: - node-version: [14, 16, 18] + node-version: [18, 20] postgres-version: [11, 14] services: postgres: @@ -56,7 +56,7 @@ jobs: fail-fast: false matrix: mysql: [{ version: '5.7', command: 'mysql_legacy' }, { version: '8.0', command: 'mysql' }] - node-version: [14, 16, 18] + node-version: [18, 20] services: mysql: image: mysql:${{ matrix.mysql.version }} @@ -83,7 +83,7 @@ jobs: fail-fast: false matrix: lib: ['sqlite', 'better_sqlite'] - node-version: [14, 16, 18] + node-version: [18, 20] steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 @@ -99,7 +99,7 @@ jobs: strategy: fail-fast: false matrix: - node-version: [16, 18] + node-version: [18, 20] services: mssql: image: mcr.microsoft.com/mssql/server:2019-latest diff --git a/.husky/commit-msg b/.husky/commit-msg index 4654c12c..4002db71 100755 --- a/.husky/commit-msg +++ b/.husky/commit-msg @@ -1,3 +1,4 @@ -#!/bin/sh -. "$(dirname "$0")/_/husky.sh" -HUSKY_GIT_PARAMS=$1 node ./node_modules/@adonisjs/mrm-preset/validate-commit/conventional/validate.js +#!/usr/bin/env sh +. "$(dirname -- "$0")/_/husky.sh" + +npx --no -- commitlint --edit diff --git a/LICENSE.md b/LICENSE.md index 1c194285..381426b8 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,6 +1,6 @@ # The MIT License -Copyright 2022 Harminder Virk, contributors +Copyright (c) 2023 Harminder Virk Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: diff --git a/adonis-typings/container.ts b/adonis-typings/container.ts index 9a1df147..91459a87 100644 --- a/adonis-typings/container.ts +++ b/adonis-typings/container.ts @@ -7,20 +7,20 @@ * file that was distributed with this source code. */ -declare module '@ioc:Adonis/Core/Application' { - import * as Orm from '@ioc:Adonis/Lucid/Orm' - import Migrator from '@ioc:Adonis/Lucid/Migrator' - import { DatabaseContract } from '@ioc:Adonis/Lucid/Database' - import { FactoryManagerContract } from '@ioc:Adonis/Lucid/Factory' - import { SchemaConstructorContract } from '@ioc:Adonis/Lucid/Schema' - import { SeederConstructorContract } from '@ioc:Adonis/Lucid/Seeder' +// declare module '@ioc:Adonis/Core/Application' { +// import * as Orm from '@ioc:Adonis/Lucid/Orm' +// import Migrator from '@ioc:Adonis/Lucid/Migrator' +// import { DatabaseContract } from '@ioc:Adonis/Lucid/Database' +// import { FactoryManagerContract } from '@ioc:Adonis/Lucid/Factory' +// import { SchemaConstructorContract } from '@ioc:Adonis/Lucid/Schema' +// import { SeederConstructorContract } from '@ioc:Adonis/Lucid/Seeder' - export interface ContainerBindings { - 'Adonis/Lucid/Database': DatabaseContract - 'Adonis/Lucid/Factory': FactoryManagerContract - 'Adonis/Lucid/Orm': typeof Orm - 'Adonis/Lucid/Migrator': typeof Migrator - 'Adonis/Lucid/Schema': SchemaConstructorContract - 'Adonis/Lucid/Seeder': SeederConstructorContract - } -} +// export interface ContainerBindings { +// 'Adonis/Lucid/Database': DatabaseContract +// 'Adonis/Lucid/Factory': FactoryManagerContract +// 'Adonis/Lucid/Orm': typeof Orm +// 'Adonis/Lucid/Migrator': typeof Migrator +// 'Adonis/Lucid/Schema': SchemaConstructorContract +// 'Adonis/Lucid/Seeder': SeederConstructorContract +// } +// } diff --git a/adonis-typings/database.ts b/adonis-typings/database.ts index 0fe1c446..b3fe9ad3 100644 --- a/adonis-typings/database.ts +++ b/adonis-typings/database.ts @@ -7,882 +7,716 @@ * file that was distributed with this source code. */ -/// - -declare module '@ioc:Adonis/Lucid/Database' { - import { Knex } from 'knex' - import { Pool } from 'tarn' - import { EventEmitter } from 'events' - import { ConnectionOptions } from 'tls' - import { EmitterContract } from '@ioc:Adonis/Core/Event' - import { MacroableConstructorContract } from 'macroable' - import { LoggerContract } from '@ioc:Adonis/Core/Logger' - import { HealthReportEntry } from '@ioc:Adonis/Core/HealthCheck' - import { LucidModel, ModelQueryBuilderContract } from '@ioc:Adonis/Lucid/Orm' - import { ProfilerRowContract, ProfilerContract } from '@ioc:Adonis/Core/Profiler' - - /** - * Same as knex. Need to redefine, as knex doesn't export this - * type - */ - export type IsolationLevels = - | 'read uncommitted' - | 'read committed' - | 'snapshot' - | 'repeatable read' - | 'serializable' - - /** - * Migration node returned by the migration source - * implementation - */ - export type FileNode = { - absPath: string - name: string - getSource: () => T | Promise - } +import type { Knex } from 'knex' +import type { Pool } from 'tarn' +import type { EventEmitter } from 'node:events' +import type { ConnectionOptions } from 'node:tls' +import type { Emitter } from '@adonisjs/core/events' +import { LucidModel, ModelQueryBuilderContract } from './model.js' +import { + DatabaseQueryBuilderContract, + FromTable, + InsertQueryBuilderContract, + RawBuilderContract, + RawQueryBindings, + RawQueryBuilderContract, + ReferenceBuilderContract, +} from './querybuilder.js' + +/** + * Same as knex. Need to redefine, as knex doesn't export this + * type + */ +export type IsolationLevels = + | 'read uncommitted' + | 'read committed' + | 'snapshot' + | 'repeatable read' + | 'serializable' + +/** + * Migration node returned by the migration source + * implementation + */ +export type FileNode = { + absPath: string + name: string + getSource: () => T | Promise +} + +/** + * Dialect specific methods + */ +export interface DialectContract { + readonly name: + | 'mssql' + | 'mysql' + | 'oracledb' + | 'postgres' + | 'redshift' + | 'sqlite3' + | 'better-sqlite3' + readonly dateTimeFormat: string + + readonly version?: string + readonly supportsAdvisoryLocks: boolean + readonly supportsViews: boolean + readonly supportsTypes: boolean + readonly supportsReturningStatement: boolean + + getAllTables(schemas?: string[]): Promise + dropAllTables(schemas?: string[]): Promise + + getAllViews(schemas?: string[]): Promise + dropAllViews(schemas?: string[]): Promise + + getAllTypes(schemas?: string[]): Promise + dropAllTypes(schemas?: string[]): Promise + + truncate(table: string, cascade?: boolean): Promise + + getAdvisoryLock(key: string | number, timeout?: number): Promise + releaseAdvisoryLock(key: string | number): Promise +} + +/** + * Shape of the transaction function to create a new transaction + */ +export interface TransactionFn { + ( + callback: (trx: TransactionClientContract) => Promise, + options?: { isolationLevel?: IsolationLevels } + ): Promise + (options?: { isolationLevel?: IsolationLevels }): Promise +} + +/** + * Shape of the query client, that is used to retrive instances + * of query builder + */ +export interface QueryClientContract { + emitter: Emitter /** - * Dialect specific methods + * Tells if client is a transaction client or not */ - export interface DialectContract { - readonly name: - | 'mssql' - | 'mysql' - | 'oracledb' - | 'postgres' - | 'redshift' - | 'sqlite3' - | 'better-sqlite3' - readonly dateTimeFormat: string + readonly isTransaction: boolean - readonly version?: string - readonly supportsAdvisoryLocks: boolean - readonly supportsViews: boolean - readonly supportsTypes: boolean - readonly supportsReturningStatement: boolean + /** + * The database dialect in use + */ + readonly dialect: DialectContract - getAllTables(schemas?: string[]): Promise - dropAllTables(schemas?: string[]): Promise + /** + * The client mode in which it is execute queries + */ + readonly mode: 'dual' | 'write' | 'read' - getAllViews(schemas?: string[]): Promise - dropAllViews(schemas?: string[]): Promise + /** + * The name of the connnection from which the client + * was originated + */ + readonly connectionName: string - getAllTypes(schemas?: string[]): Promise - dropAllTypes(schemas?: string[]): Promise + /** + * Is debug enabled on the connnection or not. Also opens up the API to + * disable debug for a given client + */ + debug: boolean - truncate(table: string, cascade?: boolean): Promise + /** + * Returns schema instance for the write client + */ + schema: Knex.SchemaBuilder - getAdvisoryLock(key: string | number, timeout?: number): Promise - releaseAdvisoryLock(key: string | number): Promise - } + /** + * Returns the read and write clients + */ + getReadClient(): Knex + getWriteClient(): Knex /** - * Shape of the transaction function to create a new transaction + * Returns the query builder for a given model */ - export interface TransactionFn { - ( - callback: (trx: TransactionClientContract) => Promise, - options?: { isolationLevel?: IsolationLevels } - ): Promise - (options?: { isolationLevel?: IsolationLevels }): Promise - } + modelQuery(model: T): ModelQueryBuilderContract /** - * Shape of the query client, that is used to retrive instances - * of query builder - */ - export interface QueryClientContract { - emitter: EmitterContract - - /** - * Custom profiler to time queries - */ - profiler?: ProfilerRowContract | ProfilerContract - - /** - * Tells if client is a transaction client or not - */ - readonly isTransaction: boolean - - /** - * The database dialect in use - */ - readonly dialect: DialectContract - - /** - * The client mode in which it is execute queries - */ - readonly mode: 'dual' | 'write' | 'read' - - /** - * The name of the connnection from which the client - * was originated - */ - readonly connectionName: string - - /** - * Is debug enabled on the connnection or not. Also opens up the API to - * disable debug for a given client - */ - debug: boolean - - /** - * Returns schema instance for the write client - */ - schema: Knex.SchemaBuilder - - /** - * Returns the read and write clients - */ - getReadClient(): Knex - getWriteClient(): Knex - - /** - * Returns the query builder for a given model - */ - modelQuery(model: T): ModelQueryBuilderContract - - /** - * Returns the knex query builder instance - */ - knexQuery(): Knex.QueryBuilder - - /** - * Returns the knex raw query builder instance - */ - knexRawQuery(sql: string, bindings?: RawQueryBindings): Knex.Raw - - /** - * Get new query builder instance for select, update and - * delete calls - */ - query(): DatabaseQueryBuilderContract - - /** - * Get new query builder instance inserts - */ - insertQuery(): InsertQueryBuilderContract - - /** - * Get raw query builder instance - */ - rawQuery( - sql: string, - bindings?: RawQueryBindings - ): RawQueryBuilderContract - - /** - * Returns instance of reference builder - */ - ref(reference: string): ReferenceBuilderContract - - /** - * Returns instance of raw builder - */ - raw(sql: string, bindings?: RawQueryBindings): RawBuilderContract - - /** - * Truncate a given table - */ - truncate(table: string, cascade?: boolean): Promise - - /** - * Returns columns info for a given table - */ - columnsInfo(table: string): Promise<{ [column: string]: Knex.ColumnInfo }> - columnsInfo(table: string, column: string): Promise - - /** - * Get all tables of the database - */ - getAllTables(schemas?: string[]): Promise - - /** - * Returns an array of all views names for one or many schemas - */ - getAllViews(schemas?: string[]): Promise - - /** - * Returns an array of all types names - */ - getAllTypes(schemas?: string[]): Promise - - /** - * Drop all tables inside database - */ - dropAllTables(schemas?: string[]): Promise - - /** - * Drop all views inside the database - */ - dropAllViews(schemas?: string[]): Promise - - /** - * Drop all types inside the database - */ - dropAllTypes(schemas?: string[]): Promise - - /** - * Same as `query()`, but also selects the table for the query. The `from` method - * doesn't allow defining the return type and one must use `query` to define - * that. - */ - from: FromTable> - - /** - * Same as `insertQuery()`, but also selects the table for the query. - * The `table` method doesn't allow defining the return type and - * one must use `insertQuery` to define that. - */ - table: (table: string) => InsertQueryBuilderContract - - /** - * Get instance of transaction client - */ - transaction: TransactionFn - - /** - * Work with advisory locks - */ - getAdvisoryLock(key: string | number, timeout?: number): Promise - releaseAdvisoryLock(key: string | number): Promise - } + * Returns the knex query builder instance + */ + knexQuery(): Knex.QueryBuilder /** - * The shape of transaction client to run queries under a given - * transaction on a single connection + * Returns the knex raw query builder instance */ - export interface TransactionClientContract extends QueryClientContract, EventEmitter { - knexClient: Knex.Transaction + knexRawQuery(sql: string, bindings?: RawQueryBindings): Knex.Raw - /** - * Custom profiler to time queries - */ - profiler?: ProfilerRowContract + /** + * Get new query builder instance for select, update and + * delete calls + */ + query(): DatabaseQueryBuilderContract - /** - * Is transaction completed or not - */ - isCompleted: boolean + /** + * Get new query builder instance inserts + */ + insertQuery(): InsertQueryBuilderContract - /** - * Commit transaction - */ - commit(): Promise + /** + * Get raw query builder instance + */ + rawQuery(sql: string, bindings?: RawQueryBindings): RawQueryBuilderContract - /** - * Rollback transaction - */ - rollback(): Promise + /** + * Returns instance of reference builder + */ + ref(reference: string): ReferenceBuilderContract - /** - * Returns the read and write transaction clients - */ - getReadClient(): Knex.Transaction - getWriteClient(): Knex.Transaction + /** + * Returns instance of raw builder + */ + raw(sql: string, bindings?: RawQueryBindings): RawBuilderContract - /** - * Transaction named events - */ - on(event: 'commit', handler: (client: this) => void): this - on(event: 'rollback', handler: (client: this) => void): this + /** + * Truncate a given table + */ + truncate(table: string, cascade?: boolean): Promise - once(event: 'commit', handler: (client: this) => void): this - once(event: 'rollback', handler: (client: this) => void): this + /** + * Returns columns info for a given table + */ + columnsInfo(table: string): Promise<{ [column: string]: Knex.ColumnInfo }> + columnsInfo(table: string, column: string): Promise - after(event: 'rollback' | 'commit', handler: () => void | Promise): this - } + /** + * Get all tables of the database + */ + getAllTables(schemas?: string[]): Promise /** - * Connection node used by majority of database - * clients + * Returns an array of all views names for one or many schemas */ - type SharedConnectionNode = { - host?: string - user?: string - password?: string - database?: string - port?: number - } + getAllViews(schemas?: string[]): Promise /** - * Shape of the report node for the database connection report + * Returns an array of all types names */ - export type ReportNode = { - connection: string - message: string - error: any - } + getAllTypes(schemas?: string[]): Promise /** - * Migrations config + * Drop all tables inside database */ - export type MigratorConfig = { - disableTransactions?: boolean - paths?: string[] - tableName?: string - disableRollbacksInProduction?: boolean - naturalSort?: boolean - } + dropAllTables(schemas?: string[]): Promise /** - * Seeders config + * Drop all views inside the database */ - export type SeedersConfig = { - paths: string[] - } + dropAllViews(schemas?: string[]): Promise /** - * Shared config options for all clients + * Drop all types inside the database */ - export type SharedConfigNode = { - useNullAsDefault?: boolean - debug?: boolean - asyncStackTraces?: boolean - revision?: number - healthCheck?: boolean - migrations?: MigratorConfig - seeders?: SeedersConfig - wipe?: { ignoreTables?: string[] } - pool?: { - afterCreate?: (conn: any, done: any) => void - min?: number - max?: number - acquireTimeoutMillis?: number - createTimeoutMillis?: number - idleTimeoutMillis?: number - createRetryIntervalMillis?: number - reapIntervalMillis?: number - log?: (msg: string) => any - validate?: (resource: any) => boolean - propagateCreateError?: boolean - } - } + dropAllTypes(schemas?: string[]): Promise /** - * The Sqlite specific config options are taken directly from the - * driver. https://github.com/mapbox/node-sqlite3/wiki/API#new-sqlite3databasefilename-mode-callback - * - * Knex forwards all config options to the driver directly. So feel - * free to define them (let us know, in case any options are missing) + * Same as `query()`, but also selects the table for the query. The `from` method + * doesn't allow defining the return type and one must use `query` to define + * that. */ - export type SqliteConfig = SharedConfigNode & { - client: 'sqlite' | 'sqlite3' | 'better-sqlite3' - connection: { - filename: string - flags?: string[] - debug?: boolean - mode?: any - } - replicas?: never - } + from: FromTable> /** - * The MYSQL specific config options are taken directly from the - * driver. https://www.npmjs.com/package/mysql#connection-options - * - * Knex forwards all config options to the driver directly. So feel - * free to define them (let us know, in case any options are missing) - */ - type MysqlConnectionNode = { - socketPath?: string - localAddress?: string - charset?: string - timezone?: string - stringifyObjects?: boolean - insecureAuth?: boolean - typeCast?: boolean - supportBigNumbers?: boolean - bigNumberStrings?: boolean - dateStrings?: boolean | string[] - flags?: string - ssl?: any - } - export type MysqlConfig = SharedConfigNode & { - client: 'mysql' | 'mysql2' - version?: string - connection?: SharedConnectionNode & MysqlConnectionNode - replicas?: { - write: { - connection: MysqlConfig['connection'] - pool?: MysqlConfig['pool'] - } - read: { - connection: MysqlConfig['connection'][] - pool?: MysqlConfig['pool'] - } - } - } + * Same as `insertQuery()`, but also selects the table for the query. + * The `table` method doesn't allow defining the return type and + * one must use `insertQuery` to define that. + */ + table: (table: string) => InsertQueryBuilderContract /** - * Config is picked from PostgreSQL driver, just refer their docs - * https://node-postgres.com/features/connecting#programmatic. - * - * - `returning` is added by knex and not driver. - * - `searchPath` is also added by Knex. - * - * Knex forwards all config options to the driver directly. So feel - * free to define them (let us know, in case any options are missing) + * Get instance of transaction client */ - type PostgresConnectionNode = { - ssl?: boolean | ConnectionOptions - } - export type PostgreConfig = SharedConfigNode & { - client: 'pg' | 'postgres' | 'postgresql' - version?: string - returning?: string - connection?: string | (SharedConnectionNode & PostgresConnectionNode) - replicas?: { - write: { - connection: PostgreConfig['connection'] - pool?: PostgreConfig['pool'] - } - read: { - connection: PostgreConfig['connection'][] - pool?: PostgreConfig['pool'] - } - } - searchPath?: string[] - wrapIdentifier?: (value: string) => string - } + transaction: TransactionFn /** - * Redshift uses `pg` driver. So config options are same as Postgres. - * https://node-postgres.com/features/connecting#programmatic. - * - * Knex forwards all config options to the driver directly. So feel - * free to define them (let us know, in case any options are missing) + * Work with advisory locks */ - export type RedshiftConfig = PostgreConfig & { - client: 'redshift' - } + getAdvisoryLock(key: string | number, timeout?: number): Promise + releaseAdvisoryLock(key: string | number): Promise +} + +/** + * The shape of transaction client to run queries under a given + * transaction on a single connection + */ +export interface TransactionClientContract extends QueryClientContract, EventEmitter { + knexClient: Knex.Transaction + + /** + * Is transaction completed or not + */ + isCompleted: boolean + + /** + * Commit transaction + */ + commit(): Promise + + /** + * Rollback transaction + */ + rollback(): Promise + + /** + * Returns the read and write transaction clients + */ + getReadClient(): Knex.Transaction + getWriteClient(): Knex.Transaction /** - * Please install `oracledb` driver and not the `oracle`. The later is - * deprecated. Config is only allowed for `oracledb`. - * - * Please refer to the driver configuration docs to learn more about the - * config values. - * https://oracle.github.io/node-oracledb/doc/api.html#oracledbproperties - */ - type OracleConnectionNode = { - autoCommit?: boolean - connectionClass?: string - edition?: string - externalAuth?: boolean - fetchArraySize?: number - fetchAsBuffer?: any[] - lobPrefetchSize?: number - maxRows?: number - oracleClientVersion?: number - connectString?: string + * Transaction named events + */ + on(event: 'commit', handler: (client: this) => void): this + on(event: 'rollback', handler: (client: this) => void): this + + once(event: 'commit', handler: (client: this) => void): this + once(event: 'rollback', handler: (client: this) => void): this + + after(event: 'rollback' | 'commit', handler: () => void | Promise): this +} + +/** + * Connection node used by majority of database + * clients + */ +type SharedConnectionNode = { + host?: string + user?: string + password?: string + database?: string + port?: number +} + +/** + * Shape of the report node for the database connection report + */ +export type ReportNode = { + connection: string + message: string + error: any +} + +/** + * Migrations config + */ +export type MigratorConfig = { + disableTransactions?: boolean + paths?: string[] + tableName?: string + disableRollbacksInProduction?: boolean + naturalSort?: boolean +} + +/** + * Seeders config + */ +export type SeedersConfig = { + paths: string[] +} + +/** + * Shared config options for all clients + */ +export type SharedConfigNode = { + useNullAsDefault?: boolean + debug?: boolean + asyncStackTraces?: boolean + revision?: number + healthCheck?: boolean + migrations?: MigratorConfig + seeders?: SeedersConfig + wipe?: { ignoreTables?: string[] } + pool?: { + afterCreate?: (conn: any, done: any) => void + min?: number + max?: number + acquireTimeoutMillis?: number + createTimeoutMillis?: number + idleTimeoutMillis?: number + createRetryIntervalMillis?: number + reapIntervalMillis?: number + log?: (msg: string) => any + validate?: (resource: any) => boolean + propagateCreateError?: boolean + } +} + +/** + * The Sqlite specific config options are taken directly from the + * driver. https://github.com/mapbox/node-sqlite3/wiki/API#new-sqlite3databasefilename-mode-callback + * + * Knex forwards all config options to the driver directly. So feel + * free to define them (let us know, in case any options are missing) + */ +export type SqliteConfig = SharedConfigNode & { + client: 'sqlite' | 'sqlite3' | 'better-sqlite3' + connection: { + filename: string + flags?: string[] + debug?: boolean + mode?: any } - export type OracleConfig = SharedConfigNode & { - client: 'oracledb' - connection?: SharedConnectionNode & OracleConnectionNode - replicas?: { - write: { - connection: OracleConfig['connection'] - pool?: OracleConfig['pool'] - } - read: { - connection: OracleConfig['connection'][] - pool?: OracleConfig['pool'] - } + replicas?: never +} + +/** + * The MYSQL specific config options are taken directly from the + * driver. https://www.npmjs.com/package/mysql#connection-options + * + * Knex forwards all config options to the driver directly. So feel + * free to define them (let us know, in case any options are missing) + */ +type MysqlConnectionNode = { + socketPath?: string + localAddress?: string + charset?: string + timezone?: string + stringifyObjects?: boolean + insecureAuth?: boolean + typeCast?: boolean + supportBigNumbers?: boolean + bigNumberStrings?: boolean + dateStrings?: boolean | string[] + flags?: string + ssl?: any +} +export type MysqlConfig = SharedConfigNode & { + client: 'mysql' | 'mysql2' + version?: string + connection?: SharedConnectionNode & MysqlConnectionNode + replicas?: { + write: { + connection: MysqlConfig['connection'] + pool?: MysqlConfig['pool'] + } + read: { + connection: MysqlConfig['connection'][] + pool?: MysqlConfig['pool'] } - fetchAsString?: any[] } +} - /** - * Config values are taken directly from the driver config. - * https://www.npmjs.com/package/mssql#config. - * - * Knex forwards all config options to the driver directly. So feel - * free to define them (let us know, in case any options are missing) - */ - type MssqlConnectionNode = { - server: string - domain?: string - connectionTimeout?: number - requestTimeout?: number - parseJSON?: boolean - options?: { - encrypt?: boolean - useUTC?: boolean - tdsVersion?: string - appName?: string - abortTransactionOnError?: boolean - trustedConnection?: boolean - enableArithAbort?: boolean - isolationLevel?: - | 'READ_UNCOMMITTED' - | 'READ_COMMITTED' - | 'REPEATABLE_READ' - | 'SERIALIZABLE' - | 'SNAPSHOT' - maxRetriesOnTransientErrors?: number - multiSubnetFailover?: boolean - packetSize?: number - trustServerCertificate?: boolean +/** + * Config is picked from PostgreSQL driver, just refer their docs + * https://node-postgres.com/features/connecting#programmatic. + * + * - `returning` is added by knex and not driver. + * - `searchPath` is also added by Knex. + * + * Knex forwards all config options to the driver directly. So feel + * free to define them (let us know, in case any options are missing) + */ +type PostgresConnectionNode = { + ssl?: boolean | ConnectionOptions +} +export type PostgreConfig = SharedConfigNode & { + client: 'pg' | 'postgres' | 'postgresql' + version?: string + returning?: string + connection?: string | (SharedConnectionNode & PostgresConnectionNode) + replicas?: { + write: { + connection: PostgreConfig['connection'] + pool?: PostgreConfig['pool'] + } + read: { + connection: PostgreConfig['connection'][] + pool?: PostgreConfig['pool'] } } - export type MssqlConfig = SharedConfigNode & { - client: 'mssql' - version?: string - connection?: SharedConnectionNode & MssqlConnectionNode - replicas?: { - write: { - connection: MssqlConfig['connection'] - pool?: MssqlConfig['pool'] - } - read: { - connection: MssqlConfig['connection'][] - pool?: MssqlConfig['pool'] - } + searchPath?: string[] + wrapIdentifier?: (value: string) => string +} + +/** + * Redshift uses `pg` driver. So config options are same as Postgres. + * https://node-postgres.com/features/connecting#programmatic. + * + * Knex forwards all config options to the driver directly. So feel + * free to define them (let us know, in case any options are missing) + */ +export type RedshiftConfig = PostgreConfig & { + client: 'redshift' +} + +/** + * Please install `oracledb` driver and not the `oracle`. The later is + * deprecated. Config is only allowed for `oracledb`. + * + * Please refer to the driver configuration docs to learn more about the + * config values. + * https://oracle.github.io/node-oracledb/doc/api.html#oracledbproperties + */ +type OracleConnectionNode = { + autoCommit?: boolean + connectionClass?: string + edition?: string + externalAuth?: boolean + fetchArraySize?: number + fetchAsBuffer?: any[] + lobPrefetchSize?: number + maxRows?: number + oracleClientVersion?: number + connectString?: string +} +export type OracleConfig = SharedConfigNode & { + client: 'oracledb' + connection?: SharedConnectionNode & OracleConnectionNode + replicas?: { + write: { + connection: OracleConfig['connection'] + pool?: OracleConfig['pool'] + } + read: { + connection: OracleConfig['connection'][] + pool?: OracleConfig['pool'] + } + } + fetchAsString?: any[] +} + +/** + * Config values are taken directly from the driver config. + * https://www.npmjs.com/package/mssql#config. + * + * Knex forwards all config options to the driver directly. So feel + * free to define them (let us know, in case any options are missing) + */ +type MssqlConnectionNode = { + server: string + domain?: string + connectionTimeout?: number + requestTimeout?: number + parseJSON?: boolean + options?: { + encrypt?: boolean + useUTC?: boolean + tdsVersion?: string + appName?: string + abortTransactionOnError?: boolean + trustedConnection?: boolean + enableArithAbort?: boolean + isolationLevel?: + | 'READ_UNCOMMITTED' + | 'READ_COMMITTED' + | 'REPEATABLE_READ' + | 'SERIALIZABLE' + | 'SNAPSHOT' + maxRetriesOnTransientErrors?: number + multiSubnetFailover?: boolean + packetSize?: number + trustServerCertificate?: boolean + } +} +export type MssqlConfig = SharedConfigNode & { + client: 'mssql' + version?: string + connection?: SharedConnectionNode & MssqlConnectionNode + replicas?: { + write: { + connection: MssqlConfig['connection'] + pool?: MssqlConfig['pool'] + } + read: { + connection: MssqlConfig['connection'][] + pool?: MssqlConfig['pool'] } } +} +/** + * Connection config must be the config from one of the + * available dialects + */ +export type ConnectionConfig = + | SqliteConfig + | MysqlConfig + | PostgreConfig + | OracleConfig + | RedshiftConfig + | MssqlConfig + +/** + * Shape of config inside the database config file + */ +export type DatabaseConfig = { + connection: string + connections: { [key: string]: ConnectionConfig } +} + +/** + * The shape of a connection within the connection manager + */ +export type ConnectionNode = { + name: string + config: ConnectionConfig + connection?: ConnectionContract + state: 'registered' | 'migrating' | 'open' | 'closing' | 'closed' +} + +/** + * Connection manager to manage one or more database + * connections. + */ +export interface ConnectionManagerContract { /** - * Connection config must be the config from one of the - * available dialects + * List of registered connection. You must check the connection state + * to understand, if it is connected or not */ - export type ConnectionConfig = - | SqliteConfig - | MysqlConfig - | PostgreConfig - | OracleConfig - | RedshiftConfig - | MssqlConfig + connections: Map /** - * Shape of config inside the database config file + * Add a new connection to the list of managed connection. You must call + * connect separately to instantiate a connection instance */ - export type DatabaseConfig = { - connection: string - connections: { [key: string]: ConnectionConfig } - } + add(connectionName: string, config: ConnectionConfig): void /** - * The shape of a connection within the connection manager + * Instantiate a connection. It is a noop, when connection for the given + * name is already instantiated */ - export type ConnectionNode = { - name: string - config: ConnectionConfig - connection?: ConnectionContract - state: 'registered' | 'migrating' | 'open' | 'closing' | 'closed' - } + connect(connectionName: string): void /** - * Connection manager to manage one or more database - * connections. - */ - export interface ConnectionManagerContract { - /** - * List of registered connection. You must check the connection state - * to understand, if it is connected or not - */ - connections: Map - - /** - * Add a new connection to the list of managed connection. You must call - * connect separately to instantiate a connection instance - */ - add(connectionName: string, config: ConnectionConfig): void - - /** - * Instantiate a connection. It is a noop, when connection for the given - * name is already instantiated - */ - connect(connectionName: string): void - - /** - * Get connection node - */ - get(connectionName: string): ConnectionNode | undefined - - /** - * Find if a connection name is managed by the manager or not - */ - has(connectionName: string): boolean - - /** - * Patch the existing connection config. This triggers the disconnect on the - * old connection - */ - patch(connectionName: string, config: ConnectionConfig): void - - /** - * Find if a managed connection is instantiated or not - */ - isConnected(connectionName: string): boolean - - /** - * Close a given connection. This is also kill the underlying knex connection - * pool - */ - close(connectionName: string, release?: boolean): Promise - - /** - * Close all managed connections - */ - closeAll(release?: boolean): Promise - - /** - * Release a given connection. Releasing a connection means, you will have to - * re-add it using the `add` method - */ - release(connectionName: string): Promise - - /** - * Returns the health check report for registered connections - */ - report(): Promise - } + * Get connection node + */ + get(connectionName: string): ConnectionNode | undefined /** - * Connection represents a single knex instance with inbuilt - * pooling capabilities. - */ - export interface ConnectionContract extends EventEmitter { - client?: Knex - readClient?: Knex - - readonly dialectName: - | 'mssql' - | 'mysql' - | 'mysql2' - | 'oracledb' - | 'postgres' - | 'redshift' - | 'sqlite3' - - /** - * Property to find if explicit read/write is enabled - */ - readonly hasReadWriteReplicas: boolean - - /** - * Read/write connection pools - */ - pool: null | Pool - readPool: null | Pool - - /** - * Name of the connection - */ - readonly name: string - - /** - * Find if connection is ready or not - */ - readonly ready: boolean - - /** - * Untouched config - */ - config: ConnectionConfig - - /** - * List of emitted events - */ - on(event: 'connect', callback: (connection: ConnectionContract) => void): this - on(event: 'error', callback: (error: Error, connection: ConnectionContract) => void): this - on(event: 'disconnect', callback: (connection: ConnectionContract) => void): this - on( - event: 'disconnect:error', - callback: (error: Error, connection: ConnectionContract) => void - ): this - - /** - * Make knex connection - */ - connect(): void - - /** - * Disconnect knex - */ - disconnect(): Promise - - /** - * Returns the connection report - */ - getReport(): Promise - } + * Find if a connection name is managed by the manager or not + */ + has(connectionName: string): boolean /** - * Options when retrieving new query client from the database - * query builder + * Patch the existing connection config. This triggers the disconnect on the + * old connection */ - export type DatabaseClientOptions = Partial<{ - mode: 'read' | 'write' - profiler: ProfilerRowContract | ProfilerContract - }> + patch(connectionName: string, config: ConnectionConfig): void /** - * Shape of the data emitted by the `db:query event` + * Find if a managed connection is instantiated or not */ - export type DbQueryEventNode = { - connection: string - model?: string - ddl?: boolean - duration?: [number, number] - method: string - sql: string - bindings?: any[] - inTransaction?: boolean - } + isConnected(connectionName: string): boolean /** - * Database contract serves as the main API to interact with multiple - * database connections + * Close a given connection. This is also kill the underlying knex connection + * pool */ - export interface DatabaseContract { - Database: MacroableConstructorContract & { - new ( - config: DatabaseConfig, - logger: LoggerContract, - profiler: ProfilerContract, - emitter: EmitterContract - ): DatabaseContract - } - DatabaseQueryBuilder: MacroableConstructorContract - InsertQueryBuilder: MacroableConstructorContract - ModelQueryBuilder: MacroableConstructorContract> - SimplePaginator: { - namingStrategy: { - paginationMetaKeys(): SimplePaginatorMetaKeys - } - new ( - total: number, - perPage: number, - currentPage: number, - ...rows: Row[] - ): SimplePaginatorContract - } + close(connectionName: string, release?: boolean): Promise - hasHealthChecksEnabled: boolean - - /** - * Pretty print query logs - */ - prettyPrint: (queryLog: DbQueryEventNode) => void - - /** - * Name of the primary connection defined inside `config/database.ts` - * file - */ - primaryConnectionName: string - - /** - * Reference to the connection manager - */ - manager: ConnectionManagerContract - - /** - * Returns the raw connection instance - */ - getRawConnection: ConnectionManagerContract['get'] - - /** - * Get query client for a given connection. Optionally one can also define - * the mode of the connection and profiler row - */ - connection(connectionName?: string, options?: DatabaseClientOptions): QueryClientContract - - /** - * Returns the knex query builder instance - */ - knexQuery(): Knex.QueryBuilder - - /** - * Returns the knex raw query builder instance - */ - knexRawQuery(sql: string, bindings?: RawQueryBindings): Knex.Raw - - /** - * Returns the query builder for a given model - */ - modelQuery( - model: T, - options?: DatabaseClientOptions - ): ModelQueryBuilderContract - - /** - * Get query builder instance for a given connection. - */ - query(options?: DatabaseClientOptions): DatabaseQueryBuilderContract - - /** - * Get insert query builder instance for a given connection. - */ - insertQuery( - options?: DatabaseClientOptions - ): InsertQueryBuilderContract - - /** - * Get raw query builder instance - */ - rawQuery( - sql: string, - bindings?: RawQueryBindings, - options?: DatabaseClientOptions - ): RawQueryBuilderContract - - /** - * Returns instance of reference builder - */ - ref(reference: string): ReferenceBuilderContract - - /** - * Returns instance of raw builder - */ - raw(sql: string, bindings?: RawQueryBindings): RawBuilderContract - - /** - * Selects a table on the default connection by instantiating a new query - * builder instance. This method provides no control over the client - * mode and one must use `query` for that - */ - from: QueryClientContract['from'] - - /** - * Selects a table on the default connection by instantiating a new query - * builder instance. This method provides no control over the client - * mode and one must use `insertQuery` for that - */ - table: QueryClientContract['table'] - - /** - * Start a new transaction - */ - transaction: TransactionFn - - /** - * Returns the health check report for registered connections - */ - report(): Promise - - /** - * Begin a new global transaction. Multiple calls to this - * method is a noop - */ - beginGlobalTransaction( - connectionName?: string, - options?: Exclude - ): Promise - - /** - * Commit an existing global transaction - */ - commitGlobalTransaction(connectionName?: string): Promise - - /** - * Rollback an existing global transaction - */ - rollbackGlobalTransaction(connectionName?: string): Promise - } + /** + * Close all managed connections + */ + closeAll(release?: boolean): Promise + + /** + * Release a given connection. Releasing a connection means, you will have to + * re-add it using the `add` method + */ + release(connectionName: string): Promise + + /** + * Returns the health check report for registered connections + */ + report(): Promise +} + +/** + * Connection represents a single knex instance with inbuilt + * pooling capabilities. + */ +export interface ConnectionContract extends EventEmitter { + client?: Knex + readClient?: Knex + + readonly dialectName: + | 'mssql' + | 'mysql' + | 'mysql2' + | 'oracledb' + | 'postgres' + | 'redshift' + | 'sqlite3' + + /** + * Property to find if explicit read/write is enabled + */ + readonly hasReadWriteReplicas: boolean + + /** + * Read/write connection pools + */ + pool: null | Pool + readPool: null | Pool + + /** + * Name of the connection + */ + readonly name: string + + /** + * Find if connection is ready or not + */ + readonly ready: boolean + + /** + * Untouched config + */ + config: ConnectionConfig + + /** + * List of emitted events + */ + on(event: 'connect', callback: (connection: ConnectionContract) => void): this + on(event: 'error', callback: (error: Error, connection: ConnectionContract) => void): this + on(event: 'disconnect', callback: (connection: ConnectionContract) => void): this + on( + event: 'disconnect:error', + callback: (error: Error, connection: ConnectionContract) => void + ): this + + /** + * Make knex connection + */ + connect(): void + + /** + * Disconnect knex + */ + disconnect(): Promise + + /** + * Returns the connection report + */ + getReport(): Promise +} - const Database: DatabaseContract - export default Database +/** + * Options when retrieving new query client from the database + * query builder + */ +export type DatabaseClientOptions = Partial<{ + mode: 'read' | 'write' +}> + +/** + * Shape of the data emitted by the `db:query event` + */ +export type DbQueryEventNode = { + connection: string + model?: string + ddl?: boolean + duration?: [number, number] + method: string + sql: string + bindings?: any[] + inTransaction?: boolean } diff --git a/adonis-typings/events.ts b/adonis-typings/events.ts index 647fb971..7fc968fa 100644 --- a/adonis-typings/events.ts +++ b/adonis-typings/events.ts @@ -7,9 +7,7 @@ * file that was distributed with this source code. */ -declare module '@ioc:Adonis/Core/Event' { - import { DbQueryEventNode } from '@ioc:Adonis/Lucid/Database' - interface EventsList { - 'db:query': DbQueryEventNode - } +import { DbQueryEventNode } from './database.js' +export interface EventsList { + 'db:query': DbQueryEventNode } diff --git a/adonis-typings/factory.ts b/adonis-typings/factory.ts index deddb27f..b6d686b8 100644 --- a/adonis-typings/factory.ts +++ b/adonis-typings/factory.ts @@ -7,412 +7,377 @@ * file that was distributed with this source code. */ -declare module '@ioc:Adonis/Lucid/Factory' { - import { faker } from '@faker-js/faker' - import { - OneOrMany, - QueryClientContract, - TransactionClientContract, - } from '@ioc:Adonis/Lucid/Database' - import { - LucidRow, - LucidModel, - ModelAttributes, - ModelAdapterOptions, - RelationshipsContract, - ExtractModelRelations, - ModelObject, - } from '@ioc:Adonis/Lucid/Orm' +import { faker } from '@faker-js/faker' +import { OneOrMany } from './querybuilder.js' +import { RelationshipsContract, ExtractModelRelations } from './relations.js' +import { QueryClientContract, TransactionClientContract } from './database.js' +import { LucidRow, LucidModel, ModelAttributes, ModelAdapterOptions, ModelObject } from './model.js' + +/** + * ------------------------------------------------------ + * Helpers + * ------------------------------------------------------ + */ + +/** + * Extracts the attributes accepted by the lucid model set on a + * factory + */ +export type ExtractFactoryAttributes = Partial< + ModelAttributes> +> + +/** + * ------------------------------------------------------ + * Callbacks + * ------------------------------------------------------ + */ + +/** + * Function to return the model attributes. + */ +export type DefineCallback = ( + ctx: FactoryContextContract +) => + | Promise>>> + | Partial>> + +/** + * Function to generate custom stub ids + */ +export type StubIdCallback = (counter: number, model: LucidRow) => any + +/** + * Function to initiate a model instance. It will receive the + * attributes returned by the `define` method + */ +export type NewUpCallback> = ( + attributes: ExtractFactoryAttributes, + ctx: FactoryContextContract, + model: Model, + builder: FactoryBuilderContract +) => InstanceType + +/** + * Function to merge attributes defined during runtime + */ +export type MergeCallback> = ( + row: InstanceType, + attributes: ExtractFactoryAttributes, + ctx: FactoryContextContract, + builder: FactoryBuilderContract +) => void + +/** + * Callback to define a new model state + */ +export type StateCallback = ( + row: InstanceType, + ctx: FactoryContextContract, + builder: FactoryBuilderContract> +) => any | Promise + +/** + * ------------------------------------------------------ + * Hooks + * ------------------------------------------------------ + */ + +/** + * List of events for which a factory will trigger hooks + */ +export type EventsList = 'makeStubbed' | 'create' | 'make' + +/** + * Shape of hooks handler + */ +export type HooksHandler> = ( + builder: FactoryBuilderContract, + row: InstanceType, + ctx: FactoryContextContract +) => void | Promise + +/** + * ------------------------------------------------------ + * Runtime context + * ------------------------------------------------------ + */ + +/** + * The runtime context of the factory builder. A new state is constructed + * for each `create/make` operation and passed down to relationships + * as well. + */ +export interface FactoryContextContract { + faker: typeof faker + isStubbed: boolean + $trx: TransactionClientContract | undefined +} + +/** + * ------------------------------------------------------ + * Relationships + * ------------------------------------------------------ + */ + +/** + * Callback accepted by the `with` method and relationships + * `create` and `make` methods + */ +export type RelationCallback = ( + builder: FactoryBuilderContract> +) => void + +/** + * Shape of the factory relationships. To keep relationships slim, we will have + * a common interface for relationships vs fine tuning API for each type of + * relationship + */ +export interface FactoryRelationContract { + parent: LucidRow /** - * ------------------------------------------------------ - * Helpers - * ------------------------------------------------------ + * Reference to the Lucid model relationship */ + relation: RelationshipsContract /** - * Extracts the attributes accepted by the lucid model set on a - * factory + * Merge attributes with the relationship and its children */ - export type ExtractFactoryAttributes> = Partial< - ModelAttributes> - > + merge(attributes: any): this /** - * ------------------------------------------------------ - * Callbacks - * ------------------------------------------------------ + * Define custom pivot attributes for many to many + * relationship */ + pivotAttributes?(attributes: ModelObject | ModelObject[]): this /** - * Function to return the model attributes. + * Pass context to the relationship. Must be done everytime, so that + * relationships uses the same transaction as the parent model */ - export type DefineCallback = ( - ctx: FactoryContextContract - ) => - | Promise>>> - | Partial>> + useCtx(ctx: FactoryContextContract): this /** - * Function to generate custom stub ids + * Create and persist */ - export type StubIdCallback = (counter: number, model: LucidRow) => any + create(parent: LucidRow, callback?: RelationCallback, count?: number): Promise /** - * Function to initiate a model instance. It will receive the - * attributes returned by the `define` method + * Create and stub */ - export type NewUpCallback> = ( - attributes: ExtractFactoryAttributes, - ctx: FactoryContextContract, - model: T['model'], - builder: FactoryBuilderContract - ) => InstanceType + make(parent: LucidRow, callback?: RelationCallback, count?: number): Promise +} +/** + * ------------------------------------------------------ + * Runtime builder + * ------------------------------------------------------ + */ + +/** + * Factory builder uses the factory model to create/make + * instances of lucid models + */ +export interface FactoryBuilderContract< + Model extends LucidModel, + FactoryModel extends FactoryModelContract, +> { /** - * Function to merge attributes defined during runtime + * Reference to the factory */ - export type MergeCallback> = ( - row: InstanceType, - attributes: ExtractFactoryAttributes, - ctx: FactoryContextContract, - builder: FactoryBuilderContract - ) => void + factory: FactoryModel /** - * Callback to define a new model state + * Define custom database connection */ - export type StateCallback = ( - row: InstanceType, - ctx: FactoryContextContract, - builder: FactoryBuilderContract> - ) => any | Promise + connection(connection: string): this /** - * ------------------------------------------------------ - * Hooks - * ------------------------------------------------------ + * Define custom query client */ + client(client: QueryClientContract): this /** - * List of events for which a factory will trigger hooks + * Apply pre-defined state */ - export type EventsList = 'makeStubbed' | 'create' | 'make' + apply(...states: K[]): this /** - * Shape of hooks handler + * Create/make relationships for explicitly defined related factories */ - export type HooksHandler> = ( - builder: FactoryBuilderContract, - row: InstanceType, - ctx: FactoryContextContract - ) => void | Promise + with( + relation: K, + count?: number, + callback?: ( + /** + * Receives the explicitly defined factory + */ + builder: FactoryModel['relations'][K] extends () => FactoryBuilderContract + ? ReturnType & { + parent: InstanceType + } + : never + ) => void + ): this /** - * ------------------------------------------------------ - * Runtime context - * ------------------------------------------------------ + * Define pivot attributes when persisting a many to many + * relationship. Results in a noop, when not called + * for a many to many relationship */ + pivotAttributes(attributes: ModelObject | ModelObject[]): this /** - * The runtime context of the factory builder. A new state is constructed - * for each `create/make` operation and passed down to relationships - * as well. + * Merge custom set of attributes. They are passed to the merge method of + * the model factory + * + * For `createMany` and `makeMany`, you can pass an array of attributes mapped + * according to the array index. */ - export interface FactoryContextContract { - faker: typeof faker - isStubbed: boolean - $trx: TransactionClientContract | undefined - } + merge(attributes: OneOrMany>): this /** - * ------------------------------------------------------ - * Relationships - * ------------------------------------------------------ + * Merge custom set of attributes with the correct factory builder + * model and all of its relationships as well */ + mergeRecursive(attributes: any): this /** - * Callback accepted by the `with` method and relationships - * `create` and `make` methods + * Define custom runtime context. This method is usually called by + * the relationships to ensure a single context is used by the + * parent and relationship factories. + * + * Do not define a custom context, unless you know what you are really + * doing. */ - export type RelationCallback = ( - builder: FactoryBuilderContract> - ) => void + useCtx(ctx: FactoryContextContract): this /** - * Shape of the factory relationships. To keep relationships slim, we will have - * a common interface for relationships vs fine tuning API for each type of - * relationship + * Tap into the persistence layer of factory builder. Allows one + * to modify the model instance just before it is persisted + * to the database + */ + tap( + callback: ( + row: InstanceType, + ctx: FactoryContextContract, + builder: this + ) => void + ): this + + /** + * Make model instance without persitance. The make method + * doesn't process relationships + */ + make(): Promise> + + /** + * Create model instance and stub out the persistance + * mechanism + */ + makeStubbed(): Promise> + + /** + * Create and persist model instance + */ + create(): Promise> + + /** + * Make model instance without persitance. The makeMany method + * doesn't process relationships + */ + makeMany(count: number): Promise[]> + + /** + * Create one or more model instances and stub + * out the persistance mechanism. + */ + makeStubbedMany(count: number): Promise[]> + + /** + * Create and persist more than one model instance + */ + createMany(count: number): Promise[]> +} + +/** + * Query contract that initiates the factory builder. Since the factory builder + * API surface is small, we also proxy all of it's methods for a nicer DX + */ +export interface FactoryBuilderQueryContract< + Model extends LucidModel, + FactoryModel extends FactoryModelContract, +> extends FactoryBuilderContract { + query( + options?: ModelAdapterOptions, + viaRelation?: FactoryRelationContract + ): FactoryBuilderContract +} + +/** + * ------------------------------------------------------ + * Factory model + * ------------------------------------------------------ + */ + +/** + * Factory model exposes the API to defined a model factory with states + * and relationships + */ +export interface FactoryModelContract { + /** + * Reference to the underlying lucid model used by the factory + * model */ - export interface FactoryRelationContract { - parent: LucidRow - - /** - * Reference to the Lucid model relationship - */ - relation: RelationshipsContract - - /** - * Merge attributes with the relationship and its children - */ - merge(attributes: any): this - - /** - * Define custom pivot attributes for many to many - * relationship - */ - pivotAttributes?(attributes: ModelObject | ModelObject[]): this - - /** - * Pass context to the relationship. Must be done everytime, so that - * relationships uses the same transaction as the parent model - */ - useCtx(ctx: FactoryContextContract): this - - /** - * Create and persist - */ - create(parent: LucidRow, callback?: RelationCallback, count?: number): Promise - - /** - * Create and stub - */ - make(parent: LucidRow, callback?: RelationCallback, count?: number): Promise - } + model: Model /** - * ------------------------------------------------------ - * Runtime builder - * ------------------------------------------------------ + * Mainly for types support. Not used at runtime to derive any + * logic. Sorry, at times have to hack into typescript to + * get the desired output. :) */ + states: unknown + relations: unknown /** - * Factory builder uses the factory model to create/make - * instances of lucid models + * Optionally define a custom method to instantiate the model + * instance and manage merging attributes */ - export interface FactoryBuilderContract> { - /** - * Reference to the factory - */ - factory: FactoryModel - - /** - * Define custom database connection - */ - connection(connection: string): this - - /** - * Define custom query client - */ - client(client: QueryClientContract): this - - /** - * Apply pre-defined state - */ - apply(...states: K[]): this - - /** - * Create/make relationships for explicitly defined related factories - */ - with( - relation: K, - count?: number, - callback?: ( - /** - * Receives the explicitly defined factory - */ - builder: FactoryModel['relations'][K] extends () => FactoryBuilderContract - ? ReturnType & { - parent: InstanceType - } - : never - ) => void - ): this - - /** - * Define pivot attributes when persisting a many to many - * relationship. Results in a noop, when not called - * for a many to many relationship - */ - pivotAttributes(attributes: ModelObject | ModelObject[]): this - - /** - * Merge custom set of attributes. They are passed to the merge method of - * the model factory - * - * For `createMany` and `makeMany`, you can pass an array of attributes mapped - * according to the array index. - */ - merge(attributes: OneOrMany>): this - - /** - * Merge custom set of attributes with the correct factory builder - * model and all of its relationships as well - */ - mergeRecursive(attributes: any): this - - /** - * Define custom runtime context. This method is usually called by - * the relationships to ensure a single context is used by the - * parent and relationship factories. - * - * Do not define a custom context, unless you know what you are really - * doing. - */ - useCtx(ctx: FactoryContextContract): this - - /** - * Tap into the persistence layer of factory builder. Allows one - * to modify the model instance just before it is persisted - * to the database - */ - tap( - callback: ( - row: InstanceType, - ctx: FactoryContextContract, - builder: this - ) => void - ): this - - /** - * Make model instance without persitance. The make method - * doesn't process relationships - */ - make(): Promise> - - /** - * Create model instance and stub out the persistance - * mechanism - */ - makeStubbed(): Promise> - - /** - * Create and persist model instance - */ - create(): Promise> - - /** - * Make model instance without persitance. The makeMany method - * doesn't process relationships - */ - makeMany(count: number): Promise[]> - - /** - * Create one or more model instances and stub - * out the persistance mechanism. - */ - makeStubbedMany(count: number): Promise[]> - - /** - * Create and persist more than one model instance - */ - createMany(count: number): Promise[]> - } + newUp(callback: NewUpCallback): this + merge(callback: MergeCallback): this /** - * Query contract that initiates the factory builder. Since the factory builder - * API surface is small, we also proxy all of it's methods for a nicer DX + * Define custom state for the factory. When executing the factory, + * you can apply the pre-defined states */ - export interface FactoryBuilderQueryContract< - FactoryModel extends FactoryModelContract - > extends FactoryBuilderContract { - query( - options?: ModelAdapterOptions, - viaRelation?: FactoryRelationContract - ): FactoryBuilderContract - } + state( + state: K, + callback: StateCallback + ): this & { states: { [P in K]: StateCallback } } /** - * ------------------------------------------------------ - * Factory model - * ------------------------------------------------------ + * Define a relationship on another factory */ + relation>, Relation>( + relation: K, + callback: Relation + ): this & { relations: { [P in K]: Relation } } /** - * Factory model exposes the API to defined a model factory with states - * and relationships + * Define before hooks. Only `create` event is invoked + * during the before lifecycle */ - export interface FactoryModelContract { - /** - * Reference to the underlying lucid model used by the factory - * model - */ - model: Model - - /** - * Mainly for types support. Not used at runtime to derive any - * logic. Sorry, at times have to hack into typescript to - * get the desired output. :) - */ - states: unknown - relations: unknown - - /** - * Optionally define a custom method to instantiate the model - * instance and manage merging attributes - */ - newUp(callback: NewUpCallback): this - merge(callback: MergeCallback): this - - /** - * Define custom state for the factory. When executing the factory, - * you can apply the pre-defined states - */ - state( - state: K, - callback: StateCallback - ): this & { states: { [P in K]: StateCallback } } - - /** - * Define a relationship on another factory - */ - relation>, Relation>( - relation: K, - callback: Relation - ): this & { relations: { [P in K]: Relation } } - - /** - * Define before hooks. Only `create` event is invoked - * during the before lifecycle - */ - before(event: Exclude, handler: HooksHandler): this - - /** - * Define after hooks. - */ - after(event: EventsList, handler: HooksHandler): this - - /** - * Build model factory. This method returns the factory builder, which can be used to - * execute model queries - */ - build(): FactoryBuilderQueryContract - } + before(event: Exclude, handler: HooksHandler): this /** - * ------------------------------------------------------ - * Manager to register new factories - * ------------------------------------------------------ + * Define after hooks. */ + after(event: EventsList, handler: HooksHandler): this /** - * Factory manager to define new factories + * Build model factory. This method returns the factory builder, which can be used to + * execute model queries */ - export interface FactoryManagerContract { - /** - * Define a custom factory - */ - define( - model: Model, - callback: DefineCallback - ): FactoryModelContract - - /** - * Define a custom callback to generate stub ids - */ - stubId(callback: StubIdCallback): void - } - - const Factory: FactoryManagerContract - export default Factory + build(): FactoryBuilderQueryContract } diff --git a/adonis-typings/index.ts b/adonis-typings/index.ts deleted file mode 100644 index 64bf5ef0..00000000 --- a/adonis-typings/index.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// diff --git a/adonis-typings/migrator.ts b/adonis-typings/migrator.ts index 94949778..a628cc2a 100644 --- a/adonis-typings/migrator.ts +++ b/adonis-typings/migrator.ts @@ -7,81 +7,42 @@ * file that was distributed with this source code. */ -declare module '@ioc:Adonis/Lucid/Migrator' { - import { EventEmitter } from 'events' - import { ApplicationContract } from '@ioc:Adonis/Core/Application' - import { FileNode, DatabaseContract } from '@ioc:Adonis/Lucid/Database' +import type { FileNode } from './database.js' - /** - * Options accepted by migrator constructor - */ - export type MigratorOptions = - | { - direction: 'up' - connectionName?: string - dryRun?: boolean - disableLocks?: boolean - } - | { - direction: 'down' - batch?: number - connectionName?: string - dryRun?: boolean - disableLocks?: boolean - } - - /** - * Shape of migrated file within migrator - */ - export type MigratedFileNode = { - status: 'completed' | 'error' | 'pending' - queries: string[] - file: FileNode - batch: number - } - - /** - * Shape of migrated file within migrator - */ - export type MigrationListNode = { - name: string - status: 'pending' | 'migrated' | 'corrupt' - batch?: number - migrationTime?: Date - } - - /** - * Shape of the migrator - */ - export interface MigratorContract extends EventEmitter { - dryRun: boolean - disableLocks: boolean - version: number - direction: 'up' | 'down' - status: 'completed' | 'skipped' | 'pending' | 'error' - error: null | Error - migratedFiles: { [file: string]: MigratedFileNode } - run(): Promise - getList(): Promise - close(): Promise - on(event: 'start', callback: () => void): this - on(event: 'end', callback: () => void): this - on(event: 'acquire:lock', callback: () => void): this - on(event: 'release:lock', callback: () => void): this - on(event: 'create:schema:table', callback: () => void): this - on(event: 'create:schema_versions:table', callback: () => void): this - on(event: 'upgrade:version', callback: (payload: { from: number; to: number }) => void): this - on(event: 'migration:start', callback: (file: MigratedFileNode) => void): this - on(event: 'migration:completed', callback: (file: MigratedFileNode) => void): this - on(event: 'migration:error', callback: (file: MigratedFileNode) => void): this - } +/** + * Options accepted by migrator constructor + */ +export type MigratorOptions = + | { + direction: 'up' + connectionName?: string + dryRun?: boolean + disableLocks?: boolean + } + | { + direction: 'down' + batch?: number + connectionName?: string + dryRun?: boolean + disableLocks?: boolean + } - /** - * Migrator class constructor - */ - const Migrator: { - new (db: DatabaseContract, app: ApplicationContract, options: MigratorOptions): MigratorContract - } +/** + * Shape of migrated file within migrator + */ +export type MigratedFileNode = { + status: 'completed' | 'error' | 'pending' + queries: string[] + file: FileNode + batch: number +} - export default Migrator +/** + * Shape of migrated file within migrator + */ +export type MigrationListNode = { + name: string + status: 'pending' | 'migrated' | 'corrupt' + batch?: number + migrationTime?: Date } diff --git a/adonis-typings/model.ts b/adonis-typings/model.ts index 4c513a82..8a5510b1 100644 --- a/adonis-typings/model.ts +++ b/adonis-typings/model.ts @@ -7,1181 +7,1190 @@ * file that was distributed with this source code. */ -declare module '@ioc:Adonis/Lucid/Orm' { - import { DateTime } from 'luxon' - import { Hooks } from '@poppinss/hooks' - import { ProfilerContract, ProfilerRowContract } from '@ioc:Adonis/Core/Profiler' - import { - Update, - Counter, - OneOrMany, - Aggregate, - Returning, - DialectContract, - ChainableContract, - QueryClientContract, - SimplePaginatorMetaKeys, - SimplePaginatorContract, - TransactionClientContract, - ExcutableQueryBuilderContract, - } from '@ioc:Adonis/Lucid/Database' +import { DateTime } from 'luxon' +import type Hooks from '@poppinss/hooks' +import { DialectContract, QueryClientContract, TransactionClientContract } from './database.js' + +import { + Update, + Counter, + OneOrMany, + Aggregate, + Returning, + ChainableContract, + SimplePaginatorMetaKeys, + SimplePaginatorContract, + ExcutableQueryBuilderContract, +} from './querybuilder.js' +import { + ExtractModelRelations, + Has, + ManyToManyRelationOptions, + ModelRelationTypes, + ModelRelations, + Preload, + PreloaderContract, + RelationOptions, + RelationshipsContract, + ThroughRelationOptions, + WhereHas, + WithAggregate, + WithCount, +} from './relations.js' + +/** + * ------------------------------------------------------ + * Helpers + * ------------------------------------------------------ + */ + +/** + * Same as [[Parameters]] but omits the first parameter + */ +type OmitFirst any> = T extends (x: any, ...args: infer P) => any + ? P + : never + +/** + * Same as [[Pick]] but picks by value and not the key + */ +type PickProperties = Pick + +/** + * Decorator function + */ +export type DecoratorFn = (target: any, property: any) => void + +/** + * Typed decorator + */ +export type TypedDecorator = < + TKey extends string, + TTarget extends { [K in TKey]: PropType }, +>( + target: TTarget, + property: TKey +) => void + +/** + * Typed decorator that also represents an optional property + */ +export type OptionalTypedDecorator = < + TKey extends string, + TTarget extends { [K in TKey]?: PropType }, +>( + target: TTarget, + property: TKey +) => void + +/** + * A complex type that filters out functions and relationships from the + * model attributes and consider all other properties as database + * columns. Alternatively, the user can self define a `$columns` + * property. + */ +export type ModelAttributes = Model['$columns'] extends undefined + ? { + [Filtered in { + [P in keyof Model]: P extends keyof LucidRow | 'serializeExtras' + ? never + : Model[P] extends Function | ModelRelationTypes + ? never + : P + }[keyof Model]]: Model[Filtered] + } + : Model['$columns'] + +/** + * Extract the query scopes of a model + */ +export type ExtractScopes = { + [Scope in keyof PickProperties>>]: ( + ...args: Model[Scope] extends QueryScopeCallback ? OmitFirst : never + ) => ExtractScopes +} + +/** + * Reusable interface to define an object. + */ +export interface ModelObject { + [key: string]: any +} + +/** + * Shape of cache node to keep getters optimized + */ +export type CacheNode = { + original: any + resolved: any + getter: (value: any) => any +} + +/** + * Shape for cherry picking fields + */ +export type CherryPickFields = + | string[] + | { + pick?: string[] + omit?: string[] + } + +/** + * Shape for cherry picking fields on nested relationships + */ +export type CherryPick = { + fields?: CherryPickFields + relations?: { [relation: string]: CherryPick } +} + +/** + * List of events for which a model will trigger hooks + */ +export type EventsList = 'save' | 'create' | 'update' | 'delete' | 'fetch' | 'find' | 'paginate' +export type HooksHandler = + | ((data: Data, event: Event) => Promise | void) + | string + +/** + * ------------------------------------------------------ + * Query Scope + * ------------------------------------------------------ + */ + +/** + * Generic query scope callback + */ +export type QueryScopeCallback = ( + query: ModelQueryBuilderContract, + ...args: any[] +) => void + +/** + * Query scope + */ +export type QueryScope< + Model extends LucidModel, + Scope extends QueryScopeCallback, +> = Scope & { + readonly isQueryScope: true +} + +/** + * A function to mark a method as query scope + */ +export type ScopeFn = < + Model extends LucidModel, + Scope extends QueryScopeCallback = QueryScopeCallback, +>( + callback: Scope +) => QueryScope + +/** + * ------------------------------------------------------ + * Decorators and Options + * ------------------------------------------------------ + */ + +/** + * Options for defining a column + */ +export type ColumnOptions = { + columnName: string // database column name + serializeAs: string | null // null means do not serialize column + isPrimary: boolean + meta?: any + + /** + * Invoked before serializing process happens + */ + serialize?: (value: any, attribute: string, model: LucidRow) => any + + /** + * Invoked before create or update happens + */ + prepare?: (value: any, attribute: string, model: LucidRow) => any + + /** + * Invoked when row is fetched from the database + */ + consume?: (value: any, attribute: string, model: LucidRow) => any +} + +/** + * Shape of column options after they have set on the model + */ +export type ModelColumnOptions = ColumnOptions & { + hasGetter: boolean + hasSetter: boolean +} + +/** + * Represents a computed property on the model + */ +export type ComputedOptions = { + serializeAs: string | null + meta?: any +} + +/** + * Options accepted by the Model.$addRelation method + */ +export type ModelRelationOptions = + | RelationOptions + | ManyToManyRelationOptions + | ThroughRelationOptions + +/** + * Signature for column decorator function + */ +export type ColumnDecorator = (options?: Partial) => DecoratorFn + +/** + * Signature for computed decorator function + */ +export type ComputedDecorator = (options?: Partial) => DecoratorFn + +/** + * Decorator for defining date columns + */ +export type DateColumnDecorator = ( + options?: Partial< + ColumnOptions & { + autoCreate: boolean + autoUpdate: boolean + } + > +) => OptionalTypedDecorator + +/** + * Decorator for defining date time columns. It is same as + * date column as of now + */ +export type DateTimeColumnDecorator = DateColumnDecorator + +/** + * Decorator for defining hooks. The generics enforces that + * decorator is used on static properties only + */ +export type HooksDecorator = () => ( + target: Model, + property: string +) => void + +/** + * ------------------------------------------------------ + * Model Options + * ------------------------------------------------------ + */ + +/** + * Model options to be used when making queries + */ +export type ModelOptions = { + connection?: string +} + +/** + * Adapter also accepts a client directly + */ +export type ModelAdapterOptions = ModelOptions & { + client?: QueryClientContract +} + +/** + * Options used by the method that internally invokes + * the merge method. +] */ +export type ModelAssignOptions = ModelAdapterOptions & { + allowExtraProperties?: boolean +} + +/** + * Preload function on a model instance + */ +export interface LucidRowPreload extends Preload> { + (callback: (preloader: PreloaderContract) => void): Promise +} + +export interface LucidRowAggregate extends Preload> { + (callback: (preloader: PreloaderContract) => void): Promise +} + +/** + * An extension of the simple paginator with support for serializing models + */ +export interface ModelPaginatorContract + extends Omit, 'toJSON'> { + serialize(cherryPick?: CherryPick): { meta: any; data: ModelObject[] } + toJSON(): { meta: any; data: ModelObject[] } +} + +/** + * Lazy load aggregates for a given model instance + */ +export interface LazyLoadAggregatesContract extends Promise { + loadAggregate: WithAggregate + loadCount: WithCount + exec(): Promise +} + +/** + * ------------------------------------------------------ + * Model Query Builder + * ------------------------------------------------------ + */ + +/** + * Model query builder will have extras methods on top of the Database query builder + */ +export interface ModelQueryBuilderContract> + extends ChainableContract, + ExcutableQueryBuilderContract { + model: Model + returning: Returning + + /** + * Define a callback to transform a row + */ + rowTransformer(callback: (row: LucidRow) => void): this + + /** + * Define a custom preloader for the current query + */ + usePreloader(preloader: PreloaderContract): this + + /** + * Whether or not the query is a child query generated for `.where` + * callbacks + */ + isChildQuery: boolean + + /** + * Alias for the @withScopes method + */ + apply>(callback: (scopes: Scopes) => void): this + + /** + * Apply model query scopes on the query bulder + */ + withScopes>(callback: (scopes: Scopes) => void): this + + /** + * A copy of client options. + */ + readonly clientOptions: ModelAdapterOptions + + /** + * Reference to query client used for making queries + */ + client: QueryClientContract + + /** + * Clone query builder instance + */ + clone(): ModelQueryBuilderContract + + /** + * A custom set of sideloaded properties defined on the query + * builder, this will be passed to the model instance created + * by the query builder + */ + sideload(value: ModelObject): this + + /** + * Execute and get first result + */ + first(): Promise + + /** + * Return the first matching row or fail + */ + firstOrFail(): Promise + + /** + * Perform delete operation + */ + del(returning?: OneOrMany): ModelQueryBuilderContract + delete(returning?: OneOrMany): ModelQueryBuilderContract + + /** + * A shorthand to define limit and offset based upon the + * current page + */ + forPage(page: number, perPage?: number): this + + /** + * Execute query with pagination + */ + paginate( + page: number, + perPage?: number + ): Promise< + Result extends LucidRow ? ModelPaginatorContract : SimplePaginatorContract + > + + /** + * Mutations (update and increment can be one query aswell) + */ + update: Update> + increment: Counter> + decrement: Counter> + + /** + * Fetch relationship count + */ + withCount: WithCount, this> + + /** + * Fetch aggregate value for a given relationship + */ + withAggregate: WithAggregate, this> + + /** + * Add where constraint using the relationship + */ + has: Has, this> + orHas: Has, this> + andHas: Has, this> + doesntHave: Has, this> + orDoesntHave: Has, this> + andDoesntHave: Has, this> + + /** + * Add where constraint using the relationship with a custom callback + */ + whereHas: WhereHas, this> + orWhereHas: WhereHas, this> + andWhereHas: WhereHas, this> + whereDoesntHave: WhereHas, this> + orWhereDoesntHave: WhereHas, this> + andWhereDoesntHave: WhereHas, this> + + /** + * Define relationships to be preloaded + */ + preload: Preload, this> + + /** + * Aggregates + */ + count: Aggregate + countDistinct: Aggregate + min: Aggregate + max: Aggregate + sum: Aggregate + sumDistinct: Aggregate + avg: Aggregate + avgDistinct: Aggregate /** - * ------------------------------------------------------ - * Helpers - * ------------------------------------------------------ + * Executes the callback when dialect matches one of the mentioned + * dialects */ + ifDialect( + dialect: DialectContract['name'] | DialectContract['name'][], + matchCallback: (query: this) => any, + noMatchCallback?: (query: this) => any + ): this /** - * Same as [[Parameters]] but omits the first parameter + * Executes the callback when dialect matches doesn't all the mentioned + * dialects */ - type OmitFirst any> = T extends (x: any, ...args: infer P) => any - ? P - : never + unlessDialect( + dialect: DialectContract['name'] | DialectContract['name'][], + matchCallback: (query: this) => any, + noMatchCallback?: (query: this) => any + ): this /** - * Same as [[Pick]] but picks by value and not the key + * Get rows back as a plain javascript object and not an array + * of model instances */ - type PickProperties = Pick + pojo(): ModelQueryBuilderContract +} + +/** + * Shape of model keys + */ +export interface ModelKeysContract { + add(key: string, value: string): void + get(key: string, defaultValue: string): string + get(key: string, defaultValue?: string): string | undefined + resolve(key: string): string + all(): ModelObject +} + +/** + * ------------------------------------------------------ + * Shape of Model instance + * ------------------------------------------------------ + */ + +/** + * Shape of the model instance. We prefix the properties with a `$` to + * differentiate between special properties provided by the base + * model but with exception to `save`, `delete`, `fill`, `merge` + * and `toJSON`. + * + * @note: Since the interface name appears next to the inherited model + * methods, we have to choose a succinct name + */ +export interface LucidRow { + $attributes: ModelObject + $extras: ModelObject + $original: ModelObject + $preloaded: { [relation: string]: LucidRow | LucidRow[] } + + /** + * Columns is a property to get type information for model + * attributes. This must be declared by the end user + */ + $columns: undefined + + $sideloaded: ModelObject + $primaryKeyValue?: number | string + $isPersisted: boolean + $isNew: boolean + $isLocal: boolean + $dirty: ModelObject + $isDirty: boolean + $isDeleted: boolean + + $options?: ModelOptions + $trx?: TransactionClientContract + $setOptionsAndTrx(options?: ModelAdapterOptions): void + + useTransaction(trx: TransactionClientContract): this + useConnection(connection: string): this + + /** + * Gives an option to the end user to define constraints for update, insert + * and delete queries. Since the query builder for these queries aren't + * exposed to the end user, this method opens up the API to build + * custom queries. + */ + $getQueryFor( + action: 'insert', + client: QueryClientContract + ): ReturnType + $getQueryFor( + action: 'update' | 'delete' | 'refresh', + client: QueryClientContract + ): ModelQueryBuilderContract /** - * Decorator function + * Read/write attributes. Following methods are intentionally loosely typed, + * so that one can bypass the public facing API and type checking for + * advanced use cases */ - export type DecoratorFn = (target: any, property: any) => void + $setAttribute(key: string, value: any): void + $getAttribute(key: string): any + $getAttributeFromCache(key: string, callback: CacheNode['getter']): any /** - * Typed decorator + * Read/write realtionships. Following methods are intentionally loosely typed, + * so that one can bypass the public facing API and type checking for + * advanced use cases */ - export type TypedDecorator = < - TKey extends string, - TTarget extends { [K in TKey]: PropType } + $hasRelated(key: string): boolean + $setRelated(key: string, result: OneOrMany | null): void + $pushRelated(key: string, result: OneOrMany | null): void + $getRelated(key: string, defaultValue?: any): OneOrMany | undefined | null + + /** + * Consume the adapter result and hydrate the model + */ + $consumeAdapterResult(adapterResult: ModelObject, sideloadAttributes?: ModelObject): void + $hydrateOriginals(): void + + fill(value: Partial>, allowExtraProperties?: boolean): this + merge(value: Partial>, allowExtraProperties?: boolean): this + + /** + * Enable force update even when no attributes + * are dirty + */ + enableForceUpdate(): this + + /** + * Actions to perform on the instance + */ + save(): Promise + delete(): Promise + refresh(): Promise + + /** + * Load relationships onto the instance + */ + load: LucidRowPreload + + /** + * Alias for "load" + * @deprecated + */ + preload: LucidRowPreload + + /** + * Load aggregates + */ + loadAggregate: < + Self extends this, + Name extends ExtractModelRelations, + RelatedBuilder = Self[Name] extends ModelRelations ? Self[Name]['subQuery'] : never, >( - target: TTarget, - property: TKey - ) => void + name: Name, + callback: (builder: RelatedBuilder) => void + ) => LazyLoadAggregatesContract /** - * Typed decorator that also represents an optional property + * Load count */ - export type OptionalTypedDecorator = < - TKey extends string, - TTarget extends { [K in TKey]?: PropType } + loadCount: < + Self extends this, + Name extends ExtractModelRelations, + RelatedBuilder = Self[Name] extends ModelRelations ? Self[Name]['subQuery'] : never, >( - target: TTarget, - property: TKey - ) => void - - /** - * A complex type that filters out functions and relationships from the - * model attributes and consider all other properties as database - * columns. Alternatively, the user can self define a `$columns` - * property. - */ - export type ModelAttributes = Model['$columns'] extends undefined - ? { - [Filtered in { - [P in keyof Model]: P extends keyof LucidRow | 'serializeExtras' - ? never - : Model[P] extends Function | ModelRelationTypes - ? never - : P - }[keyof Model]]: Model[Filtered] - } - : Model['$columns'] - - /** - * Extract the query scopes of a model - */ - export type ExtractScopes = { - [Scope in keyof PickProperties>]: ( - ...args: Model[Scope] extends QueryScopeCallback ? OmitFirst : never - ) => ExtractScopes - } + name: Name, + callback?: (builder: RelatedBuilder) => void + ) => LazyLoadAggregatesContract /** - * Reusable interface to define an object. + * Serialize attributes to a plain object */ - export interface ModelObject { - [key: string]: any - } + serializeAttributes(fields?: CherryPickFields, raw?: boolean): ModelObject /** - * Shape of cache node to keep getters optimized + * Serialize computed properties to a plain object */ - export type CacheNode = { - original: any - resolved: any - getter: (value: any) => any - } + serializeComputed(fields?: CherryPickFields): ModelObject /** - * Shape for cherry picking fields + * Serialize relationships to key-value pair of model instances and + * their serializeAs keys */ - export type CherryPickFields = - | string[] - | { - pick?: string[] - omit?: string[] - } + serializeRelations(fields: undefined, raw: true): { [key: string]: LucidRow | LucidRow[] } /** - * Shape for cherry picking fields on nested relationships + * Serialize relationships to key-value pair of plain nested objects */ - export type CherryPick = { - fields?: CherryPickFields - relations?: { [relation: string]: CherryPick } - } + serializeRelations( + cherryPick: CherryPick['relations'] | undefined, + raw: false | undefined + ): ModelObject + + serializeRelations(cherryPick?: CherryPick['relations'], raw?: boolean): ModelObject /** - * List of events for which a model will trigger hooks + * Serialize model to a plain object */ - export type EventsList = 'save' | 'create' | 'update' | 'delete' | 'fetch' | 'find' | 'paginate' - export type HooksHandler = - | ((data: Data, event: Event) => Promise | void) - | string + serialize(cherryPick?: CherryPick): ModelObject /** - * ------------------------------------------------------ - * Query Scope - * ------------------------------------------------------ + * Converts model to an object. It just returns the properties + * of the model, along with preloaded relationships */ + toObject(): ModelObject /** - * Generic query scope callback + * Serialize everything */ - export type QueryScopeCallback = ( - query: ModelQueryBuilderContract, - ...args: any[] - ) => void + toJSON(): ModelObject /** - * Query scope + * Returns related model for a given relationship */ - export type QueryScope = Scope & { readonly isQueryScope: true } + related>( + relation: Name + ): this[Name] extends ModelRelations ? this[Name]['client'] : never +} +/** + * ------------------------------------------------------ + * Shape of Model constructor + * ------------------------------------------------------ + */ + +/** + * Shape of the model static properties. The `$` prefix is to denote + * special properties from the base model. + * + * @note: Since the interface name appears next to the inherited model + * methods, we have to choose a succinct name + */ +export interface LucidModel { /** - * A function to mark a method as query scope + * Whether or not model has been booted. After this model configurations + * are ignored */ - export type ScopeFn = < - Model extends LucidModel, - Scope extends QueryScopeCallback = QueryScopeCallback - >( - callback: Scope - ) => QueryScope + readonly booted: boolean /** - * ------------------------------------------------------ - * Decorators and Options - * ------------------------------------------------------ + * A map of defined columns */ + $columnsDefinitions: Map /** - * Options for defining a column + * A map of defined relationships */ - export type ColumnOptions = { - columnName: string // database column name - serializeAs: string | null // null means do not serialize column - isPrimary: boolean - meta?: any + $relationsDefinitions: Map - /** - * Invoked before serializing process happens - */ - serialize?: (value: any, attribute: string, model: LucidRow) => any + /** + * A map of computed properties + */ + $computedDefinitions: Map - /** - * Invoked before create or update happens - */ - prepare?: (value: any, attribute: string, model: LucidRow) => any + /** + * The primary key for finding unique referencing to a + * model + */ + primaryKey: string - /** - * Invoked when row is fetched from the database - */ - consume?: (value: any, attribute: string, model: LucidRow) => any - } + /** + * Custom database connection to use + */ + connection?: string /** - * Shape of column options after they have set on the model + * Naming strategy to use */ - export type ModelColumnOptions = ColumnOptions & { - hasGetter: boolean - hasSetter: boolean - } + namingStrategy: NamingStrategyContract /** - * Represents a computed property on the model + * Database table to use */ - export type ComputedOptions = { - serializeAs: string | null - meta?: any + table: string + + /** + * Self assign the primary instead of relying on the database to + * return it back + */ + selfAssignPrimaryKey: boolean + + /** + * Adapter to work as a bridge between query builder and the model + */ + $adapter: AdapterContract + + /** + * Reference to hooks + */ + $hooks: Hooks + + /** + * A copy of internal keys mapping. One should be able to resolve between + * all key versions + */ + $keys: { + attributesToColumns: ModelKeysContract + attributesToSerialized: ModelKeysContract + columnsToAttributes: ModelKeysContract + columnsToSerialized: ModelKeysContract + serializedToColumns: ModelKeysContract + serializedToAttributes: ModelKeysContract } /** - * Options accepted by the Model.$addRelation method + * Creating model from adapter results + */ + $createFromAdapterResult( + this: T, + result?: ModelObject, + sideloadAttributes?: ModelObject, + options?: ModelAdapterOptions + ): null | InstanceType + + /** + * Creating multiple model instances from an array of adapter + * result + */ + $createMultipleFromAdapterResult( + this: T, + results: ModelObject[], + sideloadAttributes?: ModelObject, + options?: ModelAdapterOptions + ): InstanceType[] + + /** + * Managing columns + */ + $addColumn(name: string, options: Partial): ColumnOptions + $hasColumn(name: string): boolean + $getColumn(name: string): ModelColumnOptions | undefined + + /** + * Managing computed columns */ - export type ModelRelationOptions = - | RelationOptions - | ManyToManyRelationOptions - | ThroughRelationOptions + $addComputed(name: string, options: Partial): ComputedOptions + $hasComputed(name: string): boolean + $getComputed(name: string): ComputedOptions | undefined /** - * Signature for column decorator function + * Managing relationships */ - export type ColumnDecorator = (options?: Partial) => DecoratorFn + $addRelation( + name: string, + type: ModelRelationTypes['__opaque_type'], + relatedModel: () => LucidModel, + options: ModelRelationOptions + ): void /** - * Signature for computed decorator function + * Find if a relationship exists */ - export type ComputedDecorator = (options?: Partial) => DecoratorFn + $hasRelation(name: string): boolean /** - * Decorator for defining date columns + * Get relationship declaration */ - export type DateColumnDecorator = ( - options?: Partial< - ColumnOptions & { - autoCreate: boolean - autoUpdate: boolean - } + $getRelation>>( + this: Model, + name: Name + ): InstanceType[Name] extends ModelRelations + ? InstanceType[Name]['client']['relation'] + : RelationshipsContract + $getRelation(this: Model, name: string): RelationshipsContract + + /** + * Define a static property on the model using the inherit or + * define strategy. + * + * Inherit strategy will clone the property from the parent model + * and will set it on the current model + */ + $defineProperty( + this: Model, + propertyName: Prop, + defaultValue: Model[Prop], + strategy: 'inherit' | 'define' | ((value: Model[Prop]) => Model[Prop]) + ): void + + /** + * Boot model + */ + boot(): void + + /** + * Register a before hook + */ + before( + this: Model, + event: Event, + handler: HooksHandler, Event> + ): void + before( + this: Model, + event: 'paginate', + handler: HooksHandler< + [ModelQueryBuilderContract, ModelQueryBuilderContract], + 'paginate' > - ) => OptionalTypedDecorator + ): void + before( + this: Model, + event: Event, + handler: HooksHandler, Event> + ): void /** - * Decorator for defining date time columns. It is same as - * date column as of now + * Register an after hook */ - export type DateTimeColumnDecorator = DateColumnDecorator + after( + this: Model, + event: 'fetch', + handler: HooksHandler[], 'fetch'> + ): void + after( + this: Model, + event: 'paginate', + handler: HooksHandler>, 'paginate'> + ): void + after( + this: Model, + event: Event, + handler: HooksHandler, Event> + ): void /** - * Decorator for defining hooks. The generics enforces that - * decorator is used on static properties only + * Create model and return its instance back */ - export type HooksDecorator = () => ( - target: Model, - property: string - ) => void + create( + this: T, + values: Partial>>, + options?: ModelAssignOptions + ): Promise> /** - * ------------------------------------------------------ - * Model Options - * ------------------------------------------------------ + * Create many of model instances */ + createMany( + this: T, + values: Partial>>[], + options?: ModelAssignOptions + ): Promise[]> /** - * Model options to be used when making queries + * Find one using the primary key */ - export type ModelOptions = { - connection?: string - profiler?: ProfilerContract | ProfilerRowContract - } + find( + this: T, + value: any, + options?: ModelAdapterOptions + ): Promise> /** - * Adapter also accepts a client directly + * Find one using the primary key or fail */ - export type ModelAdapterOptions = ModelOptions & { - client?: QueryClientContract - } + findOrFail( + this: T, + value: any, + options?: ModelAdapterOptions + ): Promise> /** - * Options used by the method that internally invokes - * the merge method. -] */ - export type ModelAssignOptions = ModelAdapterOptions & { - allowExtraProperties?: boolean - } + * Find one using a key-value pair + */ + findBy( + this: T, + key: string, + value: any, + options?: ModelAdapterOptions + ): Promise> /** - * Preload function on a model instance + * Find one using a key-value pair or fail */ - interface LucidRowPreload extends Preload> { - (callback: (preloader: PreloaderContract) => void): Promise - } + findByOrFail( + this: T, + key: string, + value: any, + options?: ModelAdapterOptions + ): Promise> - interface LucidRowAggregate extends Preload> { - (callback: (preloader: PreloaderContract) => void): Promise - } + /** + * Same as `query().first()` + */ + first( + this: T, + options?: ModelAdapterOptions + ): Promise> /** - * An extension of the simple paginator with support for serializing models + * Same as `query().firstOrFail()` */ - export interface ModelPaginatorContract - extends Omit, 'toJSON'> { - serialize(cherryPick?: CherryPick): { meta: any; data: ModelObject[] } - toJSON(): { meta: any; data: ModelObject[] } - } + firstOrFail( + this: T, + options?: ModelAdapterOptions + ): Promise> /** - * Lazy load aggregates for a given model instance + * Find many using an array of primary keys */ - export interface LazyLoadAggregatesContract extends Promise { - loadAggregate: WithAggregate - loadCount: WithCount - exec(): Promise - } + findMany( + this: T, + value: any[], + options?: ModelAdapterOptions + ): Promise[]> /** - * ------------------------------------------------------ - * Model Query Builder - * ------------------------------------------------------ + * Returns the first row or create a new instance of model without + * persisting it */ + firstOrNew( + this: T, + searchPayload: Partial>>, + savePayload?: Partial>>, + options?: ModelAssignOptions + ): Promise> /** - * Model query builder will have extras methods on top of the Database query builder + * Returns the first row or save it to the database */ - export interface ModelQueryBuilderContract> - extends ChainableContract, - ExcutableQueryBuilderContract { - model: Model - returning: Returning + firstOrCreate( + this: T, + searchPayload: Partial>>, + savePayload?: Partial>>, + options?: ModelAssignOptions + ): Promise> - /** - * Define a callback to transform a row - */ - rowTransformer(callback: (row: LucidRow) => void): this + /** + * Returns the first row or save it to the database + */ + updateOrCreate( + this: T, + searchPayload: Partial>>, + updatePayload: Partial>>, + options?: ModelAssignOptions + ): Promise> - /** - * Define a custom preloader for the current query - */ - usePreloader(preloader: PreloaderContract): this + /** + * Find rows or create in-memory instances of the missing + * one's. + */ + fetchOrNewUpMany( + this: T, + predicate: keyof ModelAttributes> | (keyof ModelAttributes>)[], + payload: Partial>>[], + options?: ModelAssignOptions + ): Promise[]> - /** - * Whether or not the query is a child query generated for `.where` - * callbacks - */ - isChildQuery: boolean + /** + * Find rows or create many when missing. One db call is invoked + * for each create + */ + fetchOrCreateMany( + this: T, + predicate: keyof ModelAttributes> | (keyof ModelAttributes>)[], + payload: Partial>>[], + options?: ModelAssignOptions + ): Promise[]> - /** - * Alias for the @withScopes method - */ - apply>(callback: (scopes: Scopes) => void): this + /** + * Update existing rows or create new one's. + */ + updateOrCreateMany( + this: T, + predicate: keyof ModelAttributes> | (keyof ModelAttributes>)[], + payload: Partial>>[], + options?: ModelAssignOptions + ): Promise[]> - /** - * Apply model query scopes on the query bulder - */ - withScopes>(callback: (scopes: Scopes) => void): this + /** + * Fetch all rows + */ + all(this: T, options?: ModelAdapterOptions): Promise[]> - /** - * A copy of client options. - */ - readonly clientOptions: ModelAdapterOptions + /** + * Returns the query for fetching a model instance + */ + query>( + this: Model, + options?: ModelAdapterOptions + ): ModelQueryBuilderContract - /** - * Reference to query client used for making queries - */ - client: QueryClientContract + /** + * Truncate model table + */ + truncate(cascade?: boolean): Promise - /** - * Clone query builder instance - */ - clone(): ModelQueryBuilderContract - - /** - * A custom set of sideloaded properties defined on the query - * builder, this will be passed to the model instance created - * by the query builder - */ - sideload(value: ModelObject): this - - /** - * Execute and get first result - */ - first(): Promise - - /** - * Return the first matching row or fail - */ - firstOrFail(): Promise - - /** - * Perform delete operation - */ - del(returning?: OneOrMany): ModelQueryBuilderContract - delete(returning?: OneOrMany): ModelQueryBuilderContract - - /** - * A shorthand to define limit and offset based upon the - * current page - */ - forPage(page: number, perPage?: number): this - - /** - * Execute query with pagination - */ - paginate( - page: number, - perPage?: number - ): Promise< - Result extends LucidRow ? ModelPaginatorContract : SimplePaginatorContract - > + new (): LucidRow +} - /** - * Mutations (update and increment can be one query aswell) - */ - update: Update> - increment: Counter> - decrement: Counter> - - /** - * Fetch relationship count - */ - withCount: WithCount, this> - - /** - * Fetch aggregate value for a given relationship - */ - withAggregate: WithAggregate, this> - - /** - * Add where constraint using the relationship - */ - has: Has, this> - orHas: Has, this> - andHas: Has, this> - doesntHave: Has, this> - orDoesntHave: Has, this> - andDoesntHave: Has, this> - - /** - * Add where constraint using the relationship with a custom callback - */ - whereHas: WhereHas, this> - orWhereHas: WhereHas, this> - andWhereHas: WhereHas, this> - whereDoesntHave: WhereHas, this> - orWhereDoesntHave: WhereHas, this> - andWhereDoesntHave: WhereHas, this> - - /** - * Define relationships to be preloaded - */ - preload: Preload, this> - - /** - * Aggregates - */ - count: Aggregate - countDistinct: Aggregate - min: Aggregate - max: Aggregate - sum: Aggregate - sumDistinct: Aggregate - avg: Aggregate - avgDistinct: Aggregate - - /** - * Executes the callback when dialect matches one of the mentioned - * dialects - */ - ifDialect( - dialect: DialectContract['name'] | DialectContract['name'][], - matchCallback: (query: this) => any, - noMatchCallback?: (query: this) => any - ): this - - /** - * Executes the callback when dialect matches doesn't all the mentioned - * dialects - */ - unlessDialect( - dialect: DialectContract['name'] | DialectContract['name'][], - matchCallback: (query: this) => any, - noMatchCallback?: (query: this) => any - ): this - - /** - * Get rows back as a plain javascript object and not an array - * of model instances - */ - pojo(): ModelQueryBuilderContract - } +/** + * ------------------------------------------------------ + * Database Adapter + * ------------------------------------------------------ + */ +/** + * Every adapter must adhere to the Adapter contract + */ +export interface AdapterContract { /** - * Shape of model keys + * Returns query client for a model instance by inspecting it's options */ - export interface ModelKeysContract { - add(key: string, value: string): void - get(key: string, defaultValue: string): string - get(key: string, defaultValue?: string): string | undefined - resolve(key: string): string - all(): ModelObject - } + modelClient(instance: LucidRow): QueryClientContract /** - * ------------------------------------------------------ - * Shape of Model instance - * ------------------------------------------------------ + * Returns query client for a model constructor */ + modelConstructorClient( + modelConstructor: LucidModel, + options?: ModelAdapterOptions + ): QueryClientContract /** - * Shape of the model instance. We prefix the properties with a `$` to - * differentiate between special properties provided by the base - * model but with exception to `save`, `delete`, `fill`, `merge` - * and `toJSON`. - * - * @note: Since the interface name appears next to the inherited model - * methods, we have to choose a succinct name - */ - export interface LucidRow { - $attributes: ModelObject - $extras: ModelObject - $original: ModelObject - $preloaded: { [relation: string]: LucidRow | LucidRow[] } - - /** - * Columns is a property to get type information for model - * attributes. This must be declared by the end user - */ - $columns: undefined - - $sideloaded: ModelObject - $primaryKeyValue?: number | string - $isPersisted: boolean - $isNew: boolean - $isLocal: boolean - $dirty: ModelObject - $isDirty: boolean - $isDeleted: boolean - - $options?: ModelOptions - $trx?: TransactionClientContract - $setOptionsAndTrx(options?: ModelAdapterOptions): void - - useTransaction(trx: TransactionClientContract): this - useConnection(connection: string): this - - /** - * Gives an option to the end user to define constraints for update, insert - * and delete queries. Since the query builder for these queries aren't - * exposed to the end user, this method opens up the API to build - * custom queries. - */ - $getQueryFor( - action: 'insert', - client: QueryClientContract - ): ReturnType - $getQueryFor( - action: 'update' | 'delete' | 'refresh', - client: QueryClientContract - ): ModelQueryBuilderContract - - /** - * Read/write attributes. Following methods are intentionally loosely typed, - * so that one can bypass the public facing API and type checking for - * advanced use cases - */ - $setAttribute(key: string, value: any): void - $getAttribute(key: string): any - $getAttributeFromCache(key: string, callback: CacheNode['getter']): any - - /** - * Read/write realtionships. Following methods are intentionally loosely typed, - * so that one can bypass the public facing API and type checking for - * advanced use cases - */ - $hasRelated(key: string): boolean - $setRelated(key: string, result: OneOrMany | null): void - $pushRelated(key: string, result: OneOrMany | null): void - $getRelated(key: string, defaultValue?: any): OneOrMany | undefined | null - - /** - * Consume the adapter result and hydrate the model - */ - $consumeAdapterResult(adapterResult: ModelObject, sideloadAttributes?: ModelObject): void - $hydrateOriginals(): void - - fill(value: Partial>, allowExtraProperties?: boolean): this - merge(value: Partial>, allowExtraProperties?: boolean): this - - /** - * Enable force update even when no attributes - * are dirty - */ - enableForceUpdate(): this - - /** - * Actions to perform on the instance - */ - save(): Promise - delete(): Promise - refresh(): Promise - - /** - * Load relationships onto the instance - */ - load: LucidRowPreload - - /** - * Alias for "load" - * @deprecated - */ - preload: LucidRowPreload - - /** - * Load aggregates - */ - loadAggregate: < - Self extends this, - Name extends ExtractModelRelations, - RelatedBuilder = Self[Name] extends ModelRelations ? Self[Name]['subQuery'] : never - >( - name: Name, - callback: (builder: RelatedBuilder) => void - ) => LazyLoadAggregatesContract - - /** - * Load count - */ - loadCount: < - Self extends this, - Name extends ExtractModelRelations, - RelatedBuilder = Self[Name] extends ModelRelations ? Self[Name]['subQuery'] : never - >( - name: Name, - callback?: (builder: RelatedBuilder) => void - ) => LazyLoadAggregatesContract - - /** - * Serialize attributes to a plain object - */ - serializeAttributes(fields?: CherryPickFields, raw?: boolean): ModelObject - - /** - * Serialize computed properties to a plain object - */ - serializeComputed(fields?: CherryPickFields): ModelObject - - /** - * Serialize relationships to key-value pair of model instances and - * their serializeAs keys - */ - serializeRelations(fields: undefined, raw: true): { [key: string]: LucidRow | LucidRow[] } - - /** - * Serialize relationships to key-value pair of plain nested objects - */ - serializeRelations( - cherryPick: CherryPick['relations'] | undefined, - raw: false | undefined - ): ModelObject - - serializeRelations(cherryPick?: CherryPick['relations'], raw?: boolean): ModelObject - - /** - * Serialize model to a plain object - */ - serialize(cherryPick?: CherryPick): ModelObject - - /** - * Converts model to an object. It just returns the properties - * of the model, along with preloaded relationships - */ - toObject(): ModelObject - - /** - * Serialize everything - */ - toJSON(): ModelObject - - /** - * Returns related model for a given relationship - */ - related>( - relation: Name - ): this[Name] extends ModelRelations ? this[Name]['client'] : never - } + * Delete model instance + */ + delete(instance: LucidRow): Promise /** - * ------------------------------------------------------ - * Shape of Model constructor - * ------------------------------------------------------ + * Refresh model instance to reflect new values + * from the database */ + refresh(instance: LucidRow): Promise /** - * Shape of the model static properties. The `$` prefix is to denote - * special properties from the base model. - * - * @note: Since the interface name appears next to the inherited model - * methods, we have to choose a succinct name - */ - export interface LucidModel { - /** - * Whether or not model has been booted. After this model configurations - * are ignored - */ - readonly booted: boolean - - /** - * A map of defined columns - */ - $columnsDefinitions: Map - - /** - * A map of defined relationships - */ - $relationsDefinitions: Map - - /** - * A map of computed properties - */ - $computedDefinitions: Map - - /** - * The primary key for finding unique referencing to a - * model - */ - primaryKey: string - - /** - * Custom database connection to use - */ - connection?: string - - /** - * Naming strategy to use - */ - namingStrategy: NamingStrategyContract - - /** - * Database table to use - */ - table: string - - /** - * Self assign the primary instead of relying on the database to - * return it back - */ - selfAssignPrimaryKey: boolean - - /** - * Adapter to work as a bridge between query builder and the model - */ - $adapter: AdapterContract - - /** - * Reference to hooks - */ - $hooks: Hooks - - /** - * A copy of internal keys mapping. One should be able to resolve between - * all key versions - */ - $keys: { - attributesToColumns: ModelKeysContract - attributesToSerialized: ModelKeysContract - columnsToAttributes: ModelKeysContract - columnsToSerialized: ModelKeysContract - serializedToColumns: ModelKeysContract - serializedToAttributes: ModelKeysContract - } + * Perform insert + */ + insert(instance: LucidRow, attributes: ModelObject): Promise - /** - * Creating model from adapter results - */ - $createFromAdapterResult( - this: T, - result?: ModelObject, - sideloadAttributes?: ModelObject, - options?: ModelAdapterOptions - ): null | InstanceType - - /** - * Creating multiple model instances from an array of adapter - * result - */ - $createMultipleFromAdapterResult( - this: T, - results: ModelObject[], - sideloadAttributes?: ModelObject, - options?: ModelAdapterOptions - ): InstanceType[] - - /** - * Managing columns - */ - $addColumn(name: string, options: Partial): ColumnOptions - $hasColumn(name: string): boolean - $getColumn(name: string): ModelColumnOptions | undefined - - /** - * Managing computed columns - */ - $addComputed(name: string, options: Partial): ComputedOptions - $hasComputed(name: string): boolean - $getComputed(name: string): ComputedOptions | undefined - - /** - * Managing relationships - */ - $addRelation( - name: string, - type: ModelRelationTypes['__opaque_type'], - relatedModel: () => LucidModel, - options: ModelRelationOptions - ): void - - /** - * Find if a relationship exists - */ - $hasRelation(name: string): boolean - - /** - * Get relationship declaration - */ - $getRelation>>( - this: Model, - name: Name - ): InstanceType[Name] extends ModelRelations - ? InstanceType[Name]['client']['relation'] - : RelationshipsContract - $getRelation(this: Model, name: string): RelationshipsContract - - /** - * Define a static property on the model using the inherit or - * define strategy. - * - * Inherit strategy will clone the property from the parent model - * and will set it on the current model - */ - $defineProperty( - this: Model, - propertyName: Prop, - defaultValue: Model[Prop], - strategy: 'inherit' | 'define' | ((value: Model[Prop]) => Model[Prop]) - ): void - - /** - * Boot model - */ - boot(): void - - /** - * Register a before hook - */ - before( - this: Model, - event: Event, - handler: HooksHandler, Event> - ): void - before( - this: Model, - event: 'paginate', - handler: HooksHandler< - [ModelQueryBuilderContract, ModelQueryBuilderContract], - 'paginate' - > - ): void - before( - this: Model, - event: Event, - handler: HooksHandler, Event> - ): void - - /** - * Register an after hook - */ - after( - this: Model, - event: 'fetch', - handler: HooksHandler[], 'fetch'> - ): void - after( - this: Model, - event: 'paginate', - handler: HooksHandler>, 'paginate'> - ): void - after( - this: Model, - event: Event, - handler: HooksHandler, Event> - ): void - - /** - * Create model and return its instance back - */ - create( - this: T, - values: Partial>>, - options?: ModelAssignOptions - ): Promise> - - /** - * Create many of model instances - */ - createMany( - this: T, - values: Partial>>[], - options?: ModelAssignOptions - ): Promise[]> - - /** - * Find one using the primary key - */ - find( - this: T, - value: any, - options?: ModelAdapterOptions - ): Promise> - - /** - * Find one using the primary key or fail - */ - findOrFail( - this: T, - value: any, - options?: ModelAdapterOptions - ): Promise> - - /** - * Find one using a key-value pair - */ - findBy( - this: T, - key: string, - value: any, - options?: ModelAdapterOptions - ): Promise> - - /** - * Find one using a key-value pair or fail - */ - findByOrFail( - this: T, - key: string, - value: any, - options?: ModelAdapterOptions - ): Promise> - - /** - * Same as `query().first()` - */ - first( - this: T, - options?: ModelAdapterOptions - ): Promise> - - /** - * Same as `query().firstOrFail()` - */ - firstOrFail( - this: T, - options?: ModelAdapterOptions - ): Promise> - - /** - * Find many using an array of primary keys - */ - findMany( - this: T, - value: any[], - options?: ModelAdapterOptions - ): Promise[]> - - /** - * Returns the first row or create a new instance of model without - * persisting it - */ - firstOrNew( - this: T, - searchPayload: Partial>>, - savePayload?: Partial>>, - options?: ModelAssignOptions - ): Promise> - - /** - * Returns the first row or save it to the database - */ - firstOrCreate( - this: T, - searchPayload: Partial>>, - savePayload?: Partial>>, - options?: ModelAssignOptions - ): Promise> - - /** - * Returns the first row or save it to the database - */ - updateOrCreate( - this: T, - searchPayload: Partial>>, - updatePayload: Partial>>, - options?: ModelAssignOptions - ): Promise> - - /** - * Find rows or create in-memory instances of the missing - * one's. - */ - fetchOrNewUpMany( - this: T, - predicate: - | keyof ModelAttributes> - | (keyof ModelAttributes>)[], - payload: Partial>>[], - options?: ModelAssignOptions - ): Promise[]> - - /** - * Find rows or create many when missing. One db call is invoked - * for each create - */ - fetchOrCreateMany( - this: T, - predicate: - | keyof ModelAttributes> - | (keyof ModelAttributes>)[], - payload: Partial>>[], - options?: ModelAssignOptions - ): Promise[]> - - /** - * Update existing rows or create new one's. - */ - updateOrCreateMany( - this: T, - predicate: - | keyof ModelAttributes> - | (keyof ModelAttributes>)[], - payload: Partial>>[], - options?: ModelAssignOptions - ): Promise[]> - - /** - * Fetch all rows - */ - all(this: T, options?: ModelAdapterOptions): Promise[]> - - /** - * Returns the query for fetching a model instance - */ - query>( - this: Model, - options?: ModelAdapterOptions - ): ModelQueryBuilderContract - - /** - * Truncate model table - */ - truncate(cascade?: boolean): Promise - - new (): LucidRow - } + /** + * Perform update + */ + update(instance: LucidRow, attributes: ModelObject): Promise /** - * ------------------------------------------------------ - * Database Adapter - * ------------------------------------------------------ - */ - - /** - * Every adapter must adhere to the Adapter contract - */ - export interface AdapterContract { - /** - * Returns query client for a model instance by inspecting it's options - */ - modelClient(instance: LucidRow): QueryClientContract - - /** - * Returns query client for a model constructor - */ - modelConstructorClient( - modelConstructor: LucidModel, - options?: ModelAdapterOptions - ): QueryClientContract - - /** - * Delete model instance - */ - delete(instance: LucidRow): Promise - - /** - * Refresh model instance to reflect new values - * from the database - */ - refresh(instance: LucidRow): Promise - - /** - * Perform insert - */ - insert(instance: LucidRow, attributes: ModelObject): Promise - - /** - * Perform update - */ - update(instance: LucidRow, attributes: ModelObject): Promise - - /** - * Must return the query builder for the model - */ - query( - modelConstructor: LucidModel, - options?: ModelAdapterOptions - ): ModelQueryBuilderContract - } + * Must return the query builder for the model + */ + query( + modelConstructor: LucidModel, + options?: ModelAdapterOptions + ): ModelQueryBuilderContract +} +/** + * Naming strategy for model + */ +export interface NamingStrategyContract { /** - * Naming strategy for model - */ - export interface NamingStrategyContract { - /** - * The default table name for the given model - */ - tableName(model: LucidModel): string - - /** - * The database column name for a given model attribute - */ - columnName(model: LucidModel, attributeName: string): string - - /** - * The post serialization name for a given model attribute - */ - serializedName(model: LucidModel, attributeName: string): string - - /** - * The local key for a given model relationship - */ - relationLocalKey( - relation: ModelRelations['__opaque_type'], - model: LucidModel, - relatedModel: LucidModel, - relationName: string - ): string - - /** - * The foreign key for a given model relationship - */ - relationForeignKey( - relation: ModelRelations['__opaque_type'], - model: LucidModel, - relatedModel: LucidModel, - relationName: string - ): string - - /** - * Pivot table name for many to many relationship - */ - relationPivotTable( - relation: 'manyToMany', - model: LucidModel, - relatedModel: LucidModel, - relationName: string - ): string - - /** - * Pivot foreign key for many to many relationship - */ - relationPivotForeignKey( - relation: 'manyToMany', - model: LucidModel, - relatedModel: LucidModel, - relationName: string - ): string - - /** - * Keys for the pagination meta - */ - paginationMetaKeys(): SimplePaginatorMetaKeys - } + * The default table name for the given model + */ + tableName(model: LucidModel): string + + /** + * The database column name for a given model attribute + */ + columnName(model: LucidModel, attributeName: string): string + + /** + * The post serialization name for a given model attribute + */ + serializedName(model: LucidModel, attributeName: string): string + + /** + * The local key for a given model relationship + */ + relationLocalKey( + relation: ModelRelations['__opaque_type'], + model: LucidModel, + relatedModel: LucidModel, + relationName: string + ): string + + /** + * The foreign key for a given model relationship + */ + relationForeignKey( + relation: ModelRelations['__opaque_type'], + model: LucidModel, + relatedModel: LucidModel, + relationName: string + ): string + + /** + * Pivot table name for many to many relationship + */ + relationPivotTable( + relation: 'manyToMany', + model: LucidModel, + relatedModel: LucidModel, + relationName: string + ): string + + /** + * Pivot foreign key for many to many relationship + */ + relationPivotForeignKey( + relation: 'manyToMany', + model: LucidModel, + relatedModel: LucidModel, + relationName: string + ): string + + /** + * Keys for the pagination meta + */ + paginationMetaKeys(): SimplePaginatorMetaKeys } diff --git a/adonis-typings/orm.ts b/adonis-typings/orm.ts deleted file mode 100644 index abb6cb1d..00000000 --- a/adonis-typings/orm.ts +++ /dev/null @@ -1,64 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -declare module '@ioc:Adonis/Lucid/Orm' { - import { SimplePaginatorMetaKeys } from '@ioc:Adonis/Lucid/Database' - export const SnakeCaseNamingStrategy: { - new (): NamingStrategyContract - } - export const scope: ScopeFn - export const BaseModel: LucidModel - - /** - * Relationships - */ - export const hasOne: HasOneDecorator - export const belongsTo: BelongsToDecorator - export const hasMany: HasManyDecorator - export const manyToMany: ManyToManyDecorator - export const hasManyThrough: HasManyThroughDecorator - - /** - * Hooks - */ - export const beforeSave: HooksDecorator - export const afterSave: HooksDecorator - export const beforeCreate: HooksDecorator - export const afterCreate: HooksDecorator - export const beforeUpdate: HooksDecorator - export const afterUpdate: HooksDecorator - export const beforeDelete: HooksDecorator - export const afterDelete: HooksDecorator - export const beforeFind: HooksDecorator - export const afterFind: HooksDecorator - export const beforeFetch: HooksDecorator - export const afterFetch: HooksDecorator - export const beforePaginate: HooksDecorator - export const afterPaginate: HooksDecorator - export const ModelPaginator: { - namingStrategy: { - paginationMetaKeys(): SimplePaginatorMetaKeys - } - new ( - total: number, - perPage: number, - currentPage: number, - ...rows: Row[] - ): ModelPaginatorContract - } - - /** - * Columns and computed - */ - export const column: ColumnDecorator & { - date: DateColumnDecorator - dateTime: DateTimeColumnDecorator - } - export const computed: ComputedDecorator -} diff --git a/adonis-typings/querybuilder.ts b/adonis-typings/querybuilder.ts index 8dd6747c..6c2a2566 100644 --- a/adonis-typings/querybuilder.ts +++ b/adonis-typings/querybuilder.ts @@ -7,910 +7,897 @@ * file that was distributed with this source code. */ -declare module '@ioc:Adonis/Lucid/Database' { - import { Knex } from 'knex' - import { - DialectContract, - QueryClientContract, - TransactionClientContract, - } from '@ioc:Adonis/Lucid/Database' +import { Knex } from 'knex' +import { DialectContract, QueryClientContract, TransactionClientContract } from './database.js' - /** - * Extracted from ts-essentials - */ - type Dictionary = { [key in K]: T } +/** + * Extracted from ts-essentials + */ +export type Dictionary = { [key in K]: T } - /** - * Get one or many of a generic - */ - type OneOrMany = T | T[] +/** + * Get one or many of a generic + */ +export type OneOrMany = T | T[] - /** - * Allowing a generic value along with raw query instance or a subquery - * instance - */ - export type ValueWithSubQueries = T | ChainableContract | RawQuery +/** + * Allowing a generic value along with raw query instance or a subquery + * instance + */ +export type ValueWithSubQueries = T | ChainableContract | RawQuery + +/** + * Acceptable raw queries + */ +export type RawQuery = + | RawBuilderContract + | RawQueryBuilderContract + | Knex.Raw + | Knex.RawQueryBuilder + +/** + * A known set of values allowed when defining values for different + * clauses + */ +export type StrictValues = + | string + | number + | boolean + | Date + | Array + | Array + | Array + | Array + | Buffer + | RawQuery + | ReferenceBuilderContract + +/** + * Strict set of allowed values except the raw queries + */ +export type StrictValuesWithoutRaw = Exclude +/** + * Shape of raw query bindings + */ +export type RawQueryBindings = { [key: string]: StrictValues } | StrictValues[] + +/** + * A builder method to allow raw queries. However, the return type is the + * instance of current query builder. This is used for `.{verb}Raw` methods. + */ +export interface RawQueryFn { + (sql: string | RawQuery): Builder + (sql: string, bindings: RawQueryBindings): Builder +} + +/** + * Query callback is used to write wrapped queries. We get rid of `this` from + * knex, since it makes everything confusing. + */ +export type QueryCallback = (builder: Builder) => void + +/** + * Shape of the function accepted by the chainable query builder to + * pass lucid query builder to wrapped callbacks like + * `.where(function () {})`. + * + * - This method will accept the wrapped callback + * - Return a new method, that is accepted by Knex. + * - When knex calls that method, this method will invoke the user wrapped + * callback, but instead of passing the knex query builder, it will + * pass the appropriate lucid query builder. + */ +export type DBQueryCallback = ( + userFn: QueryCallback, + keysResolver?: (columnName: string) => string +) => (builder: Knex.QueryBuilder) => void + +/** + * Possible signatures for a select method on database query builder. + */ +export interface DatabaseQueryBuilderSelect { /** - * Acceptable raw queries + * Selecting columns as a dictionary with key as the alias and value is + * the original column. */ - export type RawQuery = - | RawBuilderContract - | RawQueryBuilderContract - | Knex.Raw - | Knex.RawQueryBuilder + (columns: Dictionary): Builder /** - * A known set of values allowed when defining values for different - * clauses + * An array of values with subqueries */ - export type StrictValues = - | string - | number - | boolean - | Date - | Array - | Array - | Array - | Array - | Buffer - | RawQuery - | ReferenceBuilderContract + (columns: ValueWithSubQueries[]): Builder /** - * Strict set of allowed values except the raw queries + * A spread of array arguments */ - export type StrictValuesWithoutRaw = Exclude + (...columns: ValueWithSubQueries[]): Builder /** - * Shape of raw query bindings + * Wildcard selector. */ - export type RawQueryBindings = { [key: string]: StrictValues } | StrictValues[] + (column: '*'): Builder +} +/** + * Possible signatures for adding a where clause + */ +export interface Where { /** - * A builder method to allow raw queries. However, the return type is the - * instance of current query builder. This is used for `.{verb}Raw` methods. + * Callback for wrapped clauses */ - interface RawQueryFn { - (sql: string | RawQuery): Builder - (sql: string, bindings: RawQueryBindings): Builder - } + (callback: QueryCallback): Builder /** - * Query callback is used to write wrapped queries. We get rid of `this` from - * knex, since it makes everything confusing. + * Passing an object of named key-value pair */ - type QueryCallback = (builder: Builder) => void + (clause: Dictionary): Builder /** - * Shape of the function accepted by the chainable query builder to - * pass lucid query builder to wrapped callbacks like - * `.where(function () {})`. - * - * - This method will accept the wrapped callback - * - Return a new method, that is accepted by Knex. - * - When knex calls that method, this method will invoke the user wrapped - * callback, but instead of passing the knex query builder, it will - * pass the appropriate lucid query builder. + * Key-value pair. The value can also be a subquery */ - type DBQueryCallback = ( - userFn: QueryCallback, - keysResolver?: (columnName: string) => string - ) => (builder: Knex.QueryBuilder) => void + (key: string | RawQuery, value: StrictValues | ChainableContract): Builder + (key: string | RawQuery, operator: string, value: StrictValues | ChainableContract): Builder +} +/** + * Possible signatures for adding a whereLike clause + */ +export interface WhereLike { /** - * Possible signatures for a select method on database query builder. + * Key-value pair. The value can also be a subquery */ - interface DatabaseQueryBuilderSelect { - /** - * Selecting columns as a dictionary with key as the alias and value is - * the original column. - */ - (columns: Dictionary): Builder - - /** - * An array of values with subqueries - */ - (columns: ValueWithSubQueries[]): Builder - - /** - * A spread of array arguments - */ - (...columns: ValueWithSubQueries[]): Builder - - /** - * Wildcard selector. - */ - (column: '*'): Builder - } + (key: string, value: StrictValues | ChainableContract): Builder +} +/** + * Possible signatures for adding a whereLike clause + */ +export interface WhereJson { /** - * Possible signatures for adding a where clause + * Key-value pair. The value can also be a subquery */ - interface Where { - /** - * Callback for wrapped clauses - */ - (callback: QueryCallback): Builder - - /** - * Passing an object of named key-value pair - */ - (clause: Dictionary): Builder + (column: string, value: Record | ChainableContract | QueryCallback): Builder +} - /** - * Key-value pair. The value can also be a subquery - */ - (key: string | RawQuery, value: StrictValues | ChainableContract): Builder - (key: string | RawQuery, operator: string, value: StrictValues | ChainableContract): Builder - } +export interface WhereJsonPath { + ( + column: string, + jsonPath: string, + value: + | string + | number + | boolean + | string[] + | number[] + | boolean[] + | Record + | ChainableContract + | QueryCallback + ): Builder + ( + column: string, + jsonPath: string, + operator: string, + value: + | string + | number + | boolean + | string[] + | number[] + | boolean[] + | Record + | ChainableContract + | QueryCallback + ): Builder +} +/** + * Possible signatures for adding a where column clause + */ +export interface WhereColumn { /** - * Possible signatures for adding a whereLike clause + * Key-value pair. */ - interface WhereLike { - /** - * Key-value pair. The value can also be a subquery - */ - (key: string, value: StrictValues | ChainableContract): Builder - } + (column: string | RawQuery, comparisonColumn: string): Builder + (column: string | RawQuery, operator: string, comparisonColumn: string): Builder +} +/** + * Possible signatures for adding where in clause. + */ +export interface WhereIn { /** - * Possible signatures for adding a whereLike clause + * Column name and array of values */ - interface WhereJson { - /** - * Key-value pair. The value can also be a subquery - */ - ( - column: string, - value: Record | ChainableContract | QueryCallback - ): Builder - } - - interface WhereJsonPath { - ( - column: string, - jsonPath: string, - value: - | string - | number - | boolean - | string[] - | number[] - | boolean[] - | Record - | ChainableContract - | QueryCallback - ): Builder - ( - column: string, - jsonPath: string, - operator: string, - value: - | string - | number - | boolean - | string[] - | number[] - | boolean[] - | Record - | ChainableContract - | QueryCallback - ): Builder - } + (K: string | RawQuery, value: StrictValues[]): Builder /** - * Possible signatures for adding a where column clause + * Column names and array of values as an 2d array */ - interface WhereColumn { - /** - * Key-value pair. - */ - (column: string | RawQuery, comparisonColumn: string): Builder - (column: string | RawQuery, operator: string, comparisonColumn: string): Builder - } + (K: string[], value: StrictValues[][]): Builder - /** - * Possible signatures for adding where in clause. - */ - interface WhereIn { - /** - * Column name and array of values - */ - (K: string | RawQuery, value: StrictValues[]): Builder - - /** - * Column names and array of values as an 2d array - */ - (K: string[], value: StrictValues[][]): Builder - - /** - * Column name with a subquery for a callback that yields an array of - * results - */ - ( - k: string | RawQuery, - subquery: ChainableContract | QueryCallback | RawBuilderContract | RawQuery - ): Builder - - /** - * Column names along with a subquery that yields an array - */ - (k: string[], subquery: ChainableContract | RawBuilderContract | RawQuery): Builder - } + (k: string | RawQuery, callback: QueryCallback): Builder /** - * Possible signatures for adding whereNull clause. + * Column name with a subquery for a callback that yields an array of + * results */ - interface WhereNull { - (key: string | RawQuery): Builder - } + (k: string | RawQuery, subquery: ChainableContract | RawBuilderContract | RawQuery): Builder /** - * Possibles signatures for adding a where exists clause + * Column names along with a subquery that yields an array */ - interface WhereExists { - (callback: QueryCallback | ChainableContract | RawBuilderContract | RawQuery): Builder - } + (k: string[], subquery: ChainableContract | RawBuilderContract | RawQuery): Builder +} +/** + * Possible signatures for adding whereNull clause. + */ +export interface WhereNull { + (key: string | RawQuery): Builder +} + +/** + * Possibles signatures for adding a where exists clause + */ +export interface WhereExists { + (callback: QueryCallback): Builder + (callback: ChainableContract | RawBuilderContract | RawQuery): Builder +} + +/** + * Possibles signatures for adding a where between clause + */ +export interface WhereBetween { /** - * Possibles signatures for adding a where between clause + * Accept any string as a key for supporting prefix columns */ - interface WhereBetween { - /** - * Accept any string as a key for supporting prefix columns - */ - ( - key: string | RawQuery, - value: [StrictValues | ChainableContract, StrictValues | ChainableContract] - ): Builder - } + ( + key: string | RawQuery, + value: [StrictValues | ChainableContract, StrictValues | ChainableContract] + ): Builder +} +/** + * Possible signatures for join query + */ +export interface Join { /** - * Possible signatures for join query - */ - interface Join { - /** - * Defining the join table with primary and secondary columns - * to match - */ - (table: string, primaryColumn: string, secondaryColumn: string): Builder - - /** - * Defining the join table with primary and secondary columns - * to match, where secondary column is output of a raw query - */ - (table: string, primaryColumn: string, raw: RawQuery): Builder - - /** - * Defining the join table with primary and secondary columns - * to match with a custom operator - */ - (table: string, primaryColumn: string, operator: string, secondaryColumn: string): Builder - - /** - * Join with a callback. The callback receives an array of join class from - * knex directly. - */ - (table: string, callback: Knex.JoinCallback): Builder - } + * Defining the join table with primary and secondary columns + * to match + */ + (table: string, primaryColumn: string, secondaryColumn: string): Builder /** - * Possible signatures for a distinct clause + * Defining the join table with primary and secondary columns + * to match, where secondary column is output of a raw query */ - interface Distinct { - (columns: string[]): Builder - (...columns: string[]): Builder - (column: '*'): Builder - } + (table: string, primaryColumn: string, raw: RawQuery): Builder /** - * The signatures are same as the `distinct` method. For subqueries and - * raw queries, one must use `groupByRaw`. + * Defining the join table with primary and secondary columns + * to match with a custom operator */ - interface GroupBy extends Distinct {} + (table: string, primaryColumn: string, operator: string, secondaryColumn: string): Builder /** - * Possible signatures for aggregate functions. Aggregates will push to the - * result set. Unlike knex, we force defining aliases for each aggregate. + * Join with a callback. The callback receives an array of join class from + * knex directly. */ - interface Aggregate { - /** - * Accepting column with the alias for the count. - */ - (column: OneOrMany>, alias?: string): Builder + (table: string, callback: Knex.JoinCallback): Builder +} - /** - * Accepting an object for multiple counts in a single query. - */ - (columns: Dictionary>, string>): Builder - } +/** + * Possible signatures for a distinct clause + */ +export interface Distinct { + (columns: string[]): Builder + (...columns: string[]): Builder + (column: '*'): Builder +} - /** - * Possible signatures for orderBy method. - */ - interface OrderBy { - /** - * Order by a column and optional direction - */ - ( - column: string | ChainableContract | RawBuilderContract | RawQuery, - direction?: 'asc' | 'desc' - ): Builder - - /** - * Order by multiple columns in default direction - */ - (columns: string[]): Builder - - /** - * Order by multiple columns and custom direction for each of them - */ - ( - columns: { - column: string | ChainableContract | RawBuilderContract | RawQuery - order?: 'asc' | 'desc' - }[] - ): Builder - } +/** + * The signatures are same as the `distinct` method. For subqueries and + * raw queries, one must use `groupByRaw`. + */ +export interface GroupBy extends Distinct {} +/** + * Possible signatures for aggregate functions. Aggregates will push to the + * result set. Unlike knex, we force defining aliases for each aggregate. + */ +export interface Aggregate { /** - * Possible signatures for a union clause + * Accepting column with the alias for the count. */ - interface Union { - (callback: OneOrMany>, wrap?: boolean): Builder - (subquery: OneOrMany, wrap?: boolean): Builder - } + (column: OneOrMany>, alias?: string): Builder /** - * Same signature as union + * Accepting an object for multiple counts in a single query. */ - interface UnionAll extends Union {} + (columns: Dictionary>, string>): Builder +} +/** + * Possible signatures for orderBy method. + */ +export interface OrderBy { /** - * Same signature as union + * Order by a column and optional direction */ - interface Intersect extends Union {} + ( + column: string | ChainableContract | RawBuilderContract | RawQuery, + direction?: 'asc' | 'desc' + ): Builder /** - * Possible signatures for having clause + * Order by multiple columns in default direction */ - interface Having { - /** - * A subquery callback - */ - (callback: QueryCallback | RawBuilderContract | RawQuery): Builder - - /** - * Key operator and value. Value can be a subquery as well - */ - ( - key: string | RawQuery, - operator: string, - value: StrictValues | ChainableContract | RawBuilderContract | RawQuery - ): Builder - } + (columns: string[]): Builder /** - * Possible signatures for `having in` clause. + * Order by multiple columns and custom direction for each of them */ - interface HavingIn { - /** - * Key and an array of literal values, raw queries or - * subqueries. - */ - ( - key: string | RawQuery, - value: (StrictValues | ChainableContract | RawBuilderContract | RawQuery)[] - ): Builder + ( + columns: { + column: string | ChainableContract | RawBuilderContract | RawQuery + order?: 'asc' | 'desc' + }[] + ): Builder +} - /** - * Key, along with a query callback - */ - (key: string | RawQuery, callback: QueryCallback): Builder - } +/** + * Possible signatures for a union clause + */ +export interface Union { + (callback: OneOrMany>, wrap?: boolean): Builder + (subquery: OneOrMany, wrap?: boolean): Builder +} + +/** + * Same signature as union + */ +interface UnionAll extends Union {} +/** + * Same signature as union + */ +export interface Intersect extends Union {} + +/** + * Possible signatures for having clause + */ +export interface Having { /** - * Possible signatures for `having null` clause + * A subquery callback */ - interface HavingNull extends WhereNull {} + (callback: QueryCallback): Builder + (callback: RawBuilderContract | RawQuery): Builder /** - * Possible signatures for `having exists` clause + * Key operator and value. Value can be a subquery as well */ - interface HavingExists { - /** - * A query callback or a sub query - */ - (callback: QueryCallback | ChainableContract): Builder - } + ( + key: string | RawQuery, + operator: string, + value: StrictValues | ChainableContract | RawBuilderContract | RawQuery + ): Builder +} +/** + * Possible signatures for `having in` clause. + */ +export interface HavingIn { /** - * Possible signatures for having between + * Key and an array of literal values, raw queries or + * subqueries. */ - interface HavingBetween extends WhereBetween {} + ( + key: string | RawQuery, + value: (StrictValues | ChainableContract | RawBuilderContract | RawQuery)[] + ): Builder /** - * Possible signatures of `with` CTE + * Key, along with a query callback */ - interface With { - ( - alias: string, - query: RawQuery | ChainableContract | QueryCallback, - columns?: string[] - ): Builder - } + (key: string | RawQuery, callback: QueryCallback): Builder +} + +/** + * Possible signatures for `having null` clause + */ +export interface HavingNull extends WhereNull {} +/** + * Possible signatures for `having exists` clause + */ +export interface HavingExists { /** - * Possible signatures for defining table for a select query. + * A query callback or a sub query */ - interface FromTable { - ( - table: string | Dictionary | QueryCallback | ChainableContract - ): Builder - } + (callback: QueryCallback | ChainableContract): Builder +} + +/** + * Possible signatures for having between + */ +export interface HavingBetween extends WhereBetween {} +/** + * Possible signatures of `with` CTE + */ +export interface With { + (alias: string, callback: QueryCallback, columns?: string[]): Builder + (alias: string, query: RawQuery | ChainableContract, columns?: string[]): Builder +} + +/** + * Possible signatures for defining table for a select query. + */ +export interface FromTable { + (table: string | Dictionary | QueryCallback | ChainableContract): Builder +} + +/** + * Possible signatures for the `returning` method. + */ +export interface Returning { + (column: OneOrMany): Builder +} + +/** + * Possible signatures for performing an update + */ +export interface Update { /** - * Possible signatures for the `returning` method. + * Accepts an array of object of named key/value pair and returns an array + * of Generic return columns. */ - interface Returning { - (column: OneOrMany): Builder - } + (values: Dictionary, returning?: OneOrMany): Builder /** - * Possible signatures for performing an update + * Accepts a key-value pair to update. */ - interface Update { - /** - * Accepts an array of object of named key/value pair and returns an array - * of Generic return columns. - */ - (values: Dictionary, returning?: OneOrMany): Builder + (column: string, value: any, returning?: OneOrMany): Builder +} - /** - * Accepts a key-value pair to update. - */ - (column: string, value: any, returning?: OneOrMany): Builder - } +/** + * Possible signatures for incrementing/decrementing + * values + */ +export interface Counter { + (column: string, counter?: number): Builder + (values: Dictionary): Builder +} - /** - * Possible signatures for incrementing/decrementing - * values - */ - interface Counter { - (column: string, counter?: number): Builder - (values: Dictionary): Builder - } +/** + * Possible signatures for an insert query + */ +export interface Insert { + (values: Dictionary): Builder +} + +/** + * Possible signatures for doing multiple inserts in a single query + */ +export interface MultiInsert { + (values: Dictionary[]): Builder +} + +/** + * The chainable contract has all the methods that can be chained + * to build a query. This interface will never have any + * methods to execute a query. + */ +export interface ChainableContract { + knexQuery: Knex.QueryBuilder + columns: (string | Knex.QueryBuilder | Knex.RawQueryBuilder)[] + subQueryAlias?: string + hasAggregates: boolean + hasGroupBy: boolean + hasUnion: boolean + keysResolver?: (columnName: string) => string + + from: FromTable + select: DatabaseQueryBuilderSelect + + wrapExisting(): this + + where: Where + orWhere: Where + andWhere: Where + + whereNot: Where + orWhereNot: Where + andWhereNot: Where + + whereColumn: WhereColumn + orWhereColumn: WhereColumn + andWhereColumn: WhereColumn + + whereNotColumn: WhereColumn + orWhereNotColumn: WhereColumn + andWhereNotColumn: WhereColumn + + whereIn: WhereIn + orWhereIn: WhereIn + andWhereIn: WhereIn + + whereNotIn: WhereIn + orWhereNotIn: WhereIn + andWhereNotIn: WhereIn + + whereNull: WhereNull + orWhereNull: WhereNull + andWhereNull: WhereNull + + whereNotNull: WhereNull + orWhereNotNull: WhereNull + andWhereNotNull: WhereNull + + whereExists: WhereExists + orWhereExists: WhereExists + andWhereExists: WhereExists + + whereNotExists: WhereExists + orWhereNotExists: WhereExists + andWhereNotExists: WhereExists + + whereBetween: WhereBetween + orWhereBetween: WhereBetween + andWhereBetween: WhereBetween + + whereNotBetween: WhereBetween + orWhereNotBetween: WhereBetween + andWhereNotBetween: WhereBetween + + whereRaw: RawQueryFn + orWhereRaw: RawQueryFn + andWhereRaw: RawQueryFn + + whereLike: WhereLike + orWhereLike: WhereLike + andWhereLike: WhereLike + + whereILike: WhereLike + orWhereILike: WhereLike + andWhereILike: WhereLike + + whereJson: WhereJson + orWhereJson: WhereJson + andWhereJson: WhereJson + + whereNotJson: WhereJson + orWhereNotJson: WhereJson + andWhereNotJson: WhereJson + + whereJsonSuperset: WhereJson + orWhereJsonSuperset: WhereJson + andWhereJsonSuperset: WhereJson + + whereNotJsonSuperset: WhereJson + orWhereNotJsonSuperset: WhereJson + andWhereNotJsonSuperset: WhereJson + + whereJsonSubset: WhereJson + orWhereJsonSubset: WhereJson + andWhereJsonSubset: WhereJson + + whereNotJsonSubset: WhereJson + orWhereNotJsonSubset: WhereJson + andWhereNotJsonSubset: WhereJson + + whereJsonPath: WhereJsonPath + orWhereJsonPath: WhereJsonPath + andWhereJsonPath: WhereJsonPath + + join: Join + innerJoin: Join + leftJoin: Join + leftOuterJoin: Join + rightJoin: Join + rightOuterJoin: Join + fullOuterJoin: Join + crossJoin: Join + joinRaw: RawQueryFn + + having: Having + orHaving: Having + andHaving: Having + + havingIn: HavingIn + orHavingIn: HavingIn + andHavingIn: HavingIn + + havingNotIn: HavingIn + orHavingNotIn: HavingIn + andHavingNotIn: HavingIn + + havingNull: HavingNull + orHavingNull: HavingNull + andHavingNull: HavingNull + + havingNotNull: HavingNull + orHavingNotNull: HavingNull + andHavingNotNull: HavingNull + + havingExists: HavingExists + orHavingExists: HavingExists + andHavingExists: HavingExists + + havingNotExists: HavingExists + orHavingNotExists: HavingExists + andHavingNotExists: HavingExists + + havingBetween: HavingBetween + orHavingBetween: HavingBetween + andHavingBetween: HavingBetween + + havingNotBetween: HavingBetween + orHavingNotBetween: HavingBetween + andHavingNotBetween: HavingBetween + + havingRaw: RawQueryFn + orHavingRaw: RawQueryFn + andHavingRaw: RawQueryFn + + distinct: Distinct + distinctOn: Distinct + + groupBy: GroupBy + groupByRaw: RawQueryFn + + orderBy: OrderBy + orderByRaw: RawQueryFn + + union: Union + unionAll: UnionAll + + intersect: Intersect + + with: With + withRecursive: With + withMaterialized: With + withNotMaterialized: With + + withSchema(schema: string): this + as(name: string): this + + offset(offset: number): this + limit(limit: number): this + + clearSelect(): this + clearWhere(): this + clearOrder(): this + clearHaving(): this + clearLimit(): this + clearOffset(): this + + forUpdate(...tableNames: string[]): this + forShare(...tableNames: string[]): this + + skipLocked(): this + noWait(): this /** - * Possible signatures for an insert query + * Executes the callback when condition is truthy */ - interface Insert { - (values: Dictionary): Builder - } + if( + condition: any, + matchCallback: (query: this) => any, + noMatchCallback?: (query: this) => any + ): this /** - * Possible signatures for doing multiple inserts in a single query + * Executes the callback when condition is falsy */ - interface MultiInsert { - (values: Dictionary[]): Builder - } + unless( + condition: any, + matchCallback: (query: this) => any, + noMatchCallback?: (query: this) => any + ): this /** - * The chainable contract has all the methods that can be chained - * to build a query. This interface will never have any - * methods to execute a query. + * Write blocks to match from */ - export interface ChainableContract { - knexQuery: Knex.QueryBuilder - columns: (string | Knex.QueryBuilder | Knex.RawQueryBuilder)[] - subQueryAlias?: string - hasAggregates: boolean - hasGroupBy: boolean - hasUnion: boolean - keysResolver?: (columnName: string) => string - - from: FromTable - select: DatabaseQueryBuilderSelect - - wrapExisting(): this - - where: Where - orWhere: Where - andWhere: Where - - whereNot: Where - orWhereNot: Where - andWhereNot: Where - - whereColumn: WhereColumn - orWhereColumn: WhereColumn - andWhereColumn: WhereColumn - - whereNotColumn: WhereColumn - orWhereNotColumn: WhereColumn - andWhereNotColumn: WhereColumn - - whereIn: WhereIn - orWhereIn: WhereIn - andWhereIn: WhereIn - - whereNotIn: WhereIn - orWhereNotIn: WhereIn - andWhereNotIn: WhereIn - - whereNull: WhereNull - orWhereNull: WhereNull - andWhereNull: WhereNull - - whereNotNull: WhereNull - orWhereNotNull: WhereNull - andWhereNotNull: WhereNull - - whereExists: WhereExists - orWhereExists: WhereExists - andWhereExists: WhereExists - - whereNotExists: WhereExists - orWhereNotExists: WhereExists - andWhereNotExists: WhereExists - - whereBetween: WhereBetween - orWhereBetween: WhereBetween - andWhereBetween: WhereBetween - - whereNotBetween: WhereBetween - orWhereNotBetween: WhereBetween - andWhereNotBetween: WhereBetween + match( + ...blocks: ([condition: any, callback: (query: this) => any] | ((query: this) => any))[] + ): this +} - whereRaw: RawQueryFn - orWhereRaw: RawQueryFn - andWhereRaw: RawQueryFn +/** + * Shape of the raw query that can also be passed as a value to + * other queries + */ +export interface RawQueryBuilderContract + extends ExcutableQueryBuilderContract { + knexQuery: Knex.Raw + client: QueryClientContract + wrap(before: string, after: string): this +} - whereLike: WhereLike - orWhereLike: WhereLike - andWhereLike: WhereLike +/** + * Reference builder + */ +export interface ReferenceBuilderContract { + withSchema(name: string): this + as(name: string): this + toKnex(client: Knex.Client): Knex.Ref +} - whereILike: WhereLike - orWhereILike: WhereLike - andWhereILike: WhereLike +/** + * Static raw builder + */ +export interface RawBuilderContract { + wrap(before: string, after: string): this + toKnex(client: Knex.Client): Knex.Raw +} - whereJson: WhereJson - orWhereJson: WhereJson - andWhereJson: WhereJson +/** + * The keys for the simple paginator meta + * data + */ +export type SimplePaginatorMetaKeys = { + total: string + perPage: string + currentPage: string + lastPage: string + firstPage: string + firstPageUrl: string + lastPageUrl: string + nextPageUrl: string + previousPageUrl: string +} - whereNotJson: WhereJson - orWhereNotJson: WhereJson - andWhereNotJson: WhereJson +/** + * Shape of the simple paginator that works with offset and limit + */ +export interface SimplePaginatorContract extends Array { + all(): Result[] + readonly firstPage: number + readonly perPage: number + readonly currentPage: number + readonly lastPage: number + readonly hasPages: boolean + readonly hasMorePages: boolean + readonly isEmpty: boolean + readonly total: number + readonly hasTotal: boolean + namingStrategy: { + paginationMetaKeys(): SimplePaginatorMetaKeys + } + baseUrl(url: string): this + queryString(values: { [key: string]: any }): this + getUrl(page: number): string + getMeta(): any + getNextPageUrl(): string | null + getPreviousPageUrl(): string | null + getUrlsForRange(start: number, end: number): { url: string; page: number; isActive: boolean }[] + toJSON(): { meta: any; data: Result[] } +} - whereJsonSuperset: WhereJson - orWhereJsonSuperset: WhereJson - andWhereJsonSuperset: WhereJson +/** + * Database query builder exposes the API to construct SQL query using fluent + * chainable API + */ +export interface DatabaseQueryBuilderContract> + extends ChainableContract, + ExcutableQueryBuilderContract { + client: QueryClientContract + returning: Returning - whereNotJsonSuperset: WhereJson - orWhereNotJsonSuperset: WhereJson - andWhereNotJsonSuperset: WhereJson + /** + * Clone current query + */ + clone(): DatabaseQueryBuilderContract - whereJsonSubset: WhereJson - orWhereJsonSubset: WhereJson - andWhereJsonSubset: WhereJson + /** + * Execute and get first result + */ + first(): Promise - whereNotJsonSubset: WhereJson - orWhereNotJsonSubset: WhereJson - andWhereNotJsonSubset: WhereJson - - whereJsonPath: WhereJsonPath - orWhereJsonPath: WhereJsonPath - andWhereJsonPath: WhereJsonPath - - join: Join - innerJoin: Join - leftJoin: Join - leftOuterJoin: Join - rightJoin: Join - rightOuterJoin: Join - fullOuterJoin: Join - crossJoin: Join - joinRaw: RawQueryFn - - having: Having - orHaving: Having - andHaving: Having - - havingIn: HavingIn - orHavingIn: HavingIn - andHavingIn: HavingIn - - havingNotIn: HavingIn - orHavingNotIn: HavingIn - andHavingNotIn: HavingIn - - havingNull: HavingNull - orHavingNull: HavingNull - andHavingNull: HavingNull - - havingNotNull: HavingNull - orHavingNotNull: HavingNull - andHavingNotNull: HavingNull - - havingExists: HavingExists - orHavingExists: HavingExists - andHavingExists: HavingExists - - havingNotExists: HavingExists - orHavingNotExists: HavingExists - andHavingNotExists: HavingExists - - havingBetween: HavingBetween - orHavingBetween: HavingBetween - andHavingBetween: HavingBetween - - havingNotBetween: HavingBetween - orHavingNotBetween: HavingBetween - andHavingNotBetween: HavingBetween - - havingRaw: RawQueryFn - orHavingRaw: RawQueryFn - andHavingRaw: RawQueryFn - - distinct: Distinct - distinctOn: Distinct - - groupBy: GroupBy - groupByRaw: RawQueryFn - - orderBy: OrderBy - orderByRaw: RawQueryFn - - union: Union - unionAll: UnionAll - - intersect: Intersect - - with: With - withRecursive: With - withMaterialized: With - withNotMaterialized: With - - withSchema(schema: string): this - as(name: string): this - - offset(offset: number): this - limit(limit: number): this - - clearSelect(): this - clearWhere(): this - clearOrder(): this - clearHaving(): this - clearLimit(): this - clearOffset(): this - - forUpdate(...tableNames: string[]): this - forShare(...tableNames: string[]): this - - skipLocked(): this - noWait(): this - - /** - * Executes the callback when condition is truthy - */ - if( - condition: any, - matchCallback: (query: this) => any, - noMatchCallback?: (query: this) => any - ): this - - /** - * Executes the callback when condition is falsy - */ - unless( - condition: any, - matchCallback: (query: this) => any, - noMatchCallback?: (query: this) => any - ): this - - /** - * Write blocks to match from - */ - match( - ...blocks: ([condition: any, callback: (query: this) => any] | ((query: this) => any))[] - ): this - } + /** + * Execute and get first result or fail + */ + firstOrFail(): Promise /** - * Shape of the raw query that can also be passed as a value to - * other queries + * Perform delete operation */ - export interface RawQueryBuilderContract - extends ExcutableQueryBuilderContract { - knexQuery: Knex.Raw - client: QueryClientContract - wrap(before: string, after: string): this - } + del(returning?: OneOrMany): this + delete(returning?: OneOrMany): this /** - * Reference builder + * A shorthand to define limit and offset based upon the + * current page */ - export interface ReferenceBuilderContract { - withSchema(name: string): this - as(name: string): this - toKnex(client: Knex.Client): Knex.Ref - } + forPage(page: number, perPage?: number): this /** - * Static raw builder + * Execute query with pagination */ - export interface RawBuilderContract { - wrap(before: string, after: string): this - toKnex(client: Knex.Client): Knex.Raw - } + paginate(page: number, perPage?: number): Promise> /** - * The keys for the simple paginator meta - * data + * Mutations (update and increment can be one query aswell) */ - export type SimplePaginatorMetaKeys = { - total: string - perPage: string - currentPage: string - lastPage: string - firstPage: string - firstPageUrl: string - lastPageUrl: string - nextPageUrl: string - previousPageUrl: string - } + update: Update + increment: Counter + decrement: Counter /** - * Shape of the simple paginator that works with offset and limit - */ - export interface SimplePaginatorContract extends Array { - all(): Result[] - readonly firstPage: number - readonly perPage: number - readonly currentPage: number - readonly lastPage: number - readonly hasPages: boolean - readonly hasMorePages: boolean - readonly isEmpty: boolean - readonly total: number - readonly hasTotal: boolean - namingStrategy: { - paginationMetaKeys(): SimplePaginatorMetaKeys - } - baseUrl(url: string): this - queryString(values: { [key: string]: any }): this - getUrl(page: number): string - getMeta(): any - getNextPageUrl(): string | null - getPreviousPageUrl(): string | null - getUrlsForRange(start: number, end: number): { url: string; page: number; isActive: boolean }[] - toJSON(): { meta: any; data: Result[] } - } + * Aggregates + */ + count: Aggregate + countDistinct: Aggregate + min: Aggregate + max: Aggregate + sum: Aggregate + sumDistinct: Aggregate + avg: Aggregate + avgDistinct: Aggregate /** - * Database query builder exposes the API to construct SQL query using fluent - * chainable API - */ - export interface DatabaseQueryBuilderContract> - extends ChainableContract, - ExcutableQueryBuilderContract { - client: QueryClientContract - returning: Returning - - /** - * Clone current query - */ - clone(): DatabaseQueryBuilderContract - - /** - * Execute and get first result - */ - first(): Promise - - /** - * Execute and get first result or fail - */ - firstOrFail(): Promise - - /** - * Perform delete operation - */ - del(returning?: OneOrMany): this - delete(returning?: OneOrMany): this - - /** - * A shorthand to define limit and offset based upon the - * current page - */ - forPage(page: number, perPage?: number): this - - /** - * Execute query with pagination - */ - paginate(page: number, perPage?: number): Promise> - - /** - * Mutations (update and increment can be one query aswell) - */ - update: Update - increment: Counter - decrement: Counter - - /** - * Aggregates - */ - count: Aggregate - countDistinct: Aggregate - min: Aggregate - max: Aggregate - sum: Aggregate - sumDistinct: Aggregate - avg: Aggregate - avgDistinct: Aggregate - - /** - * Executes the callback when dialect matches one of the mentioned - * dialects - */ - ifDialect( - dialect: DialectContract['name'] | DialectContract['name'][], - matchCallback: (query: this) => any, - noMatchCallback?: (query: this) => any - ): this - - /** - * Executes the callback when dialect matches doesn't all the mentioned - * dialects - */ - unlessDialect( - dialect: DialectContract['name'] | DialectContract['name'][], - matchCallback: (query: this) => any, - noMatchCallback?: (query: this) => any - ): this - } + * Executes the callback when dialect matches one of the mentioned + * dialects + */ + ifDialect( + dialect: DialectContract['name'] | DialectContract['name'][], + matchCallback: (query: this) => any, + noMatchCallback?: (query: this) => any + ): this /** - * Insert query builder to perform database inserts. + * Executes the callback when dialect matches doesn't all the mentioned + * dialects */ - export interface InsertQueryBuilderContract - extends ExcutableQueryBuilderContract { - knexQuery: Knex.QueryBuilder - client: QueryClientContract + unlessDialect( + dialect: DialectContract['name'] | DialectContract['name'][], + matchCallback: (query: this) => any, + noMatchCallback?: (query: this) => any + ): this +} - /** - * Table for the insert query - */ - table(table: string): this - withSchema(schema: string): this +/** + * Insert query builder to perform database inserts. + */ +export interface InsertQueryBuilderContract + extends ExcutableQueryBuilderContract { + knexQuery: Knex.QueryBuilder + client: QueryClientContract - /** - * Define returning columns - */ - returning: Returning + /** + * Table for the insert query + */ + table(table: string): this + withSchema(schema: string): this - /** - * Inserting a single record. - */ - insert: Insert + /** + * Define returning columns + */ + returning: Returning - /** - * Inserting multiple columns at once - */ - multiInsert: MultiInsert - } + /** + * Inserting a single record. + */ + insert: Insert /** - * A executable query builder will always have these methods on it. + * Inserting multiple columns at once */ - export interface ExcutableQueryBuilderContract extends Promise { - debug(debug: boolean): this - timeout(time: number, options?: { cancel: boolean }): this - useTransaction(trx: TransactionClientContract): this - reporterData(data: any): this - toQuery(): string - exec(): Promise - toSQL(): Knex.Sql - } + multiInsert: MultiInsert +} + +/** + * A executable query builder will always have these methods on it. + */ +export interface ExcutableQueryBuilderContract extends Promise { + debug(debug: boolean): this + timeout(time: number, options?: { cancel: boolean }): this + useTransaction(trx: TransactionClientContract): this + reporterData(data: any): this + toQuery(): string + exec(): Promise + toSQL(): Knex.Sql } diff --git a/adonis-typings/relations.ts b/adonis-typings/relations.ts index 701f7eb6..b3ee5e0a 100644 --- a/adonis-typings/relations.ts +++ b/adonis-typings/relations.ts @@ -7,1031 +7,1035 @@ * file that was distributed with this source code. */ -declare module '@ioc:Adonis/Lucid/Orm' { - import { - RawQuery, - OneOrMany, - StrictValues, - QueryCallback, - ChainableContract, - RawBuilderContract, - QueryClientContract, - TransactionClientContract, - } from '@ioc:Adonis/Lucid/Database' +import { + RawQuery, + OneOrMany, + StrictValues, + QueryCallback, + ChainableContract, + RawBuilderContract, +} from './querybuilder.js' + +import { QueryClientContract, TransactionClientContract } from './database.js' +import { + LucidModel, + LucidRow, + ModelAssignOptions, + ModelAttributes, + ModelObject, + ModelQueryBuilderContract, + TypedDecorator, +} from './model.js' + +/** + * ------------------------------------------------------ + * Helpers + * ------------------------------------------------------ + */ + +/** + * Extracts relationship attributes from the model + */ +export type ExtractModelRelations = { + [Key in keyof Model]: Model[Key] extends ModelRelations ? Key : never +}[keyof Model] + +/** + * Returns relationship model instance or array of instances based + * upon the relationship type + */ +export type GetRelationModelInstance = + Relation['__opaque_type'] extends 'hasOne' | 'belongsTo' + ? Relation['instance'] + : Relation['instance'][] + +/** + * ------------------------------------------------------ + * Options + * ------------------------------------------------------ + */ + +/** + * Options accepted when defining a new relationship. Certain + * relationships like `manyToMany` have their own options + */ +export type RelationOptions = { + localKey?: string + foreignKey?: string + serializeAs?: string | null + onQuery?(query: Related['builder'] | Related['subQuery']): void +} + +/** + * Options accepted by many to many relationship + */ +export type ManyToManyRelationOptions = { + pivotTable?: string + localKey?: string + pivotForeignKey?: string + relatedKey?: string + pivotRelatedForeignKey?: string + pivotColumns?: string[] + pivotTimestamps?: + | boolean + | { + createdAt: string | boolean + updatedAt: string | boolean + } + serializeAs?: string | null + onQuery?(query: Related['builder'] | Related['subQuery']): void +} + +/** + * Options accepted by through relationships + */ +export type ThroughRelationOptions = RelationOptions & { + throughLocalKey?: string + throughForeignKey?: string + throughModel: () => LucidModel +} + +/** + * ------------------------------------------------------ + * Decorators + * ------------------------------------------------------ + */ + +/** + * Decorator signature to define has one relationship + */ +export type HasOneDecorator = ( + model: () => RelatedModel, + options?: RelationOptions> +) => TypedDecorator> + +/** + * Decorator signature to define has many relationship + */ +export type HasManyDecorator = ( + model: () => RelatedModel, + options?: RelationOptions> +) => TypedDecorator> + +/** + * Decorator signature to define belongs to relationship + */ +export type BelongsToDecorator = ( + model: () => RelatedModel, + options?: RelationOptions> +) => TypedDecorator> + +/** + * Decorator signature to define many to many relationship + */ +export type ManyToManyDecorator = ( + model: () => RelatedModel, + column?: ManyToManyRelationOptions> +) => TypedDecorator> + +/** + * Decorator signature to define has many through relationship + */ +export type HasManyThroughDecorator = ( + model: [() => RelatedModel, () => LucidModel], + column?: Omit>, 'throughModel'> +) => TypedDecorator> + +/** + * ------------------------------------------------------ + * Opaque typed relationships + * ------------------------------------------------------ + * + * They have no runtime relevance, just a way to distinguish + * between standard model properties and relationships + * + */ +export type ModelRelationTypes = { + readonly __opaque_type: 'hasOne' | 'hasMany' | 'belongsTo' | 'manyToMany' | 'hasManyThrough' +} + +/** + * Opaque type for has one relationship + */ +export type HasOne< + RelatedModel extends LucidModel, + ParentModel extends LucidModel = LucidModel, +> = InstanceType & { + readonly __opaque_type: 'hasOne' + model: RelatedModel + instance: InstanceType + client: HasOneClientContract, RelatedModel> + builder: RelationQueryBuilderContract + subQuery: RelationSubQueryBuilderContract +} + +/** + * Opaque type for has many relationship + */ +export type HasMany< + RelatedModel extends LucidModel, + ParentModel extends LucidModel = LucidModel, +> = InstanceType[] & { + readonly __opaque_type: 'hasMany' + model: RelatedModel + instance: InstanceType + client: HasManyClientContract, RelatedModel> + builder: HasManyQueryBuilderContract + subQuery: RelationSubQueryBuilderContract +} + +/** + * Opaque type for has belongs to relationship + */ +export type BelongsTo< + RelatedModel extends LucidModel, + ParentModel extends LucidModel = LucidModel, +> = InstanceType & { + readonly __opaque_type: 'belongsTo' + model: RelatedModel + instance: InstanceType + client: BelongsToClientContract< + BelongsToRelationContract, + RelatedModel + > + builder: RelationQueryBuilderContract + subQuery: RelationSubQueryBuilderContract +} + +/** + * Opaque type for many to many relationship + */ +export type ManyToMany< + RelatedModel extends LucidModel, + ParentModel extends LucidModel = LucidModel, +> = InstanceType[] & { + readonly __opaque_type: 'manyToMany' + model: RelatedModel + instance: InstanceType + client: ManyToManyClientContract< + ManyToManyRelationContract, + RelatedModel + > + builder: ManyToManyQueryBuilderContract + subQuery: ManyToManySubQueryBuilderContract +} + +/** + * Opaque type for many to many relationship + */ +export type HasManyThrough< + RelatedModel extends LucidModel, + ParentModel extends LucidModel = LucidModel, +> = InstanceType[] & { + readonly __opaque_type: 'hasManyThrough' + model: RelatedModel + instance: InstanceType + client: HasManyThroughClientContract< + HasManyThroughRelationContract, + RelatedModel + > + builder: HasManyThroughQueryBuilderContract + subQuery: RelationSubQueryBuilderContract +} + +/** + * These exists on the models directly as a relationship. The idea + * is to distinguish relationship properties from other model + * properties. + */ +export type ModelRelations = + | HasOne + | HasMany + | BelongsTo + | ManyToMany + | HasManyThrough + +/** + * ------------------------------------------------------ + * Relationships + * ------------------------------------------------------ + */ + +/** + * Interface to be implemented by all relationship types + */ +export interface BaseRelationContract< + ParentModel extends LucidModel, + RelatedModel extends LucidModel, +> { + readonly type: ModelRelationTypes['__opaque_type'] + readonly relationName: string + readonly serializeAs: string | null + readonly booted: boolean + readonly model: ParentModel + relatedModel(): RelatedModel + boot(): void + clone(parent: LucidModel): this /** - * ------------------------------------------------------ - * Helpers - * ------------------------------------------------------ + * Get client */ + client(parent: InstanceType, client: QueryClientContract): unknown /** - * Extracts relationship attributes from the model + * Get eager query for the relationship */ - export type ExtractModelRelations = { - [Key in keyof Model]: Model[Key] extends ModelRelations ? Key : never - }[keyof Model] + eagerQuery( + parent: OneOrMany>, + client: QueryClientContract + ): RelationQueryBuilderContract> + + subQuery(client: QueryClientContract): RelationSubQueryBuilderContract +} + +/** + * Has one relationship interface + */ +export interface HasOneRelationContract< + ParentModel extends LucidModel, + RelatedModel extends LucidModel, +> extends BaseRelationContract { + readonly type: 'hasOne' + readonly localKey: string + readonly foreignKey: string /** - * Returns relationship model instance or array of instances based - * upon the relationship type + * Set related model as a relationship on the parent model. */ - export type GetRelationModelInstance = - Relation['__opaque_type'] extends 'hasOne' | 'belongsTo' - ? Relation['instance'] - : Relation['instance'][] + setRelated(parent: InstanceType, related: InstanceType | null): void /** - * ------------------------------------------------------ - * Options - * ------------------------------------------------------ + * Push related model as a relationship on the parent model */ + pushRelated(parent: InstanceType, related: InstanceType | null): void /** - * Options accepted when defining a new relationship. Certain - * relationships like `manyToMany` have their own options + * Set multiple related instances on the multiple parent models. + * This method is generally invoked during eager load. + * + * Fetch 10 users and then all profiles for all 10 users and then + * call this method to set related instances */ - export type RelationOptions = { - localKey?: string - foreignKey?: string - serializeAs?: string | null - onQuery?(query: Related['builder'] | Related['subQuery']): void - } + setRelatedForMany( + parent: InstanceType[], + related: InstanceType[] + ): void /** - * Options accepted by many to many relationship + * Returns the query client for one or many model instances. The query + * client then be used to fetch and persist relationships. */ - export type ManyToManyRelationOptions = { - pivotTable?: string - localKey?: string - pivotForeignKey?: string - relatedKey?: string - pivotRelatedForeignKey?: string - pivotColumns?: string[] - pivotTimestamps?: - | boolean - | { - createdAt: string | boolean - updatedAt: string | boolean - } - serializeAs?: string | null - onQuery?(query: Related['builder'] | Related['subQuery']): void - } + client( + parent: InstanceType, + client: QueryClientContract + ): HasOneClientContract /** - * Options accepted by through relationships + * Hydrates related model attributes for persistance */ - export type ThroughRelationOptions = RelationOptions & { - throughLocalKey?: string - throughForeignKey?: string - throughModel: () => LucidModel - } + hydrateForPersistance(parent: LucidRow, values: ModelObject | LucidRow): void +} + +/** + * Has many relationship interface + */ +export interface HasManyRelationContract< + ParentModel extends LucidModel, + RelatedModel extends LucidModel, +> extends BaseRelationContract { + readonly type: 'hasMany' + readonly localKey: string + readonly foreignKey: string /** - * ------------------------------------------------------ - * Decorators - * ------------------------------------------------------ + * Set related models as a relationship on the parent model */ + setRelated(parent: InstanceType, related: InstanceType[]): void /** - * Decorator signature to define has one relationship + * Push related model(s) as a relationship on the parent model */ - export type HasOneDecorator = ( - model: () => RelatedModel, - options?: RelationOptions> - ) => TypedDecorator> + pushRelated( + parent: InstanceType, + related: OneOrMany> + ): void /** - * Decorator signature to define has many relationship + * Set multiple related instances on the multiple parent models. + * This method is generally invoked during eager load. + * + * Fetch 10 users and then all posts for all 10 users and then + * call this method to set related instances */ - export type HasManyDecorator = ( - model: () => RelatedModel, - options?: RelationOptions> - ) => TypedDecorator> + setRelatedForMany( + parent: InstanceType[], + related: InstanceType[] + ): void /** - * Decorator signature to define belongs to relationship + * Returns the query client for one or many model instances. The query + * client then be used to fetch and persist relationships. */ - export type BelongsToDecorator = ( - model: () => RelatedModel, - options?: RelationOptions> - ) => TypedDecorator> + client( + parent: InstanceType, + client: QueryClientContract + ): HasManyClientContract /** - * Decorator signature to define many to many relationship + * Hydrates related model attributes for persistance */ - export type ManyToManyDecorator = ( - model: () => RelatedModel, - column?: ManyToManyRelationOptions> - ) => TypedDecorator> + hydrateForPersistance(parent: LucidRow, values: ModelObject | LucidRow): void +} + +/** + * Belongs to relationship interface + */ +export interface BelongsToRelationContract< + ParentModel extends LucidModel, + RelatedModel extends LucidModel, +> extends BaseRelationContract { + readonly type: 'belongsTo' + readonly localKey: string + readonly foreignKey: string /** - * Decorator signature to define has many through relationship + * Set related model as a relationship on the parent model */ - export type HasManyThroughDecorator = ( - model: [() => RelatedModel, () => LucidModel], - column?: Omit>, 'throughModel'> - ) => TypedDecorator> + setRelated(parent: InstanceType, related: InstanceType | null): void /** - * ------------------------------------------------------ - * Opaque typed relationships - * ------------------------------------------------------ - * - * They have no runtime relevance, just a way to distinguish - * between standard model properties and relationships - * + * Push related model as a relationship on the parent model */ - export type ModelRelationTypes = { - readonly __opaque_type: 'hasOne' | 'hasMany' | 'belongsTo' | 'manyToMany' | 'hasManyThrough' - } + pushRelated(parent: InstanceType, related: InstanceType | null): void /** - * Opaque type for has one relationship + * Set multiple related instances on the multiple parent models. + * This method is generally invoked during eager load. + * + * Fetch 10 profiles and then users for all 10 profiles and then + * call this method to set related instances */ - export type HasOne< - RelatedModel extends LucidModel, - ParentModel extends LucidModel = LucidModel - > = InstanceType & { - readonly __opaque_type: 'hasOne' - model: RelatedModel - instance: InstanceType - client: HasOneClientContract, RelatedModel> - builder: RelationQueryBuilderContract - subQuery: RelationSubQueryBuilderContract - } + setRelatedForMany( + parent: InstanceType[], + related: InstanceType[] + ): void /** - * Opaque type for has many relationship + * Returns the query client for a model instance */ - export type HasMany< - RelatedModel extends LucidModel, - ParentModel extends LucidModel = LucidModel - > = InstanceType[] & { - readonly __opaque_type: 'hasMany' - model: RelatedModel - instance: InstanceType - client: HasManyClientContract, RelatedModel> - builder: HasManyQueryBuilderContract - subQuery: RelationSubQueryBuilderContract - } + client( + parent: InstanceType, + client: QueryClientContract + ): BelongsToClientContract /** - * Opaque type for has belongs to relationship + * Hydrates parent model attributes for persistance */ - export type BelongsTo< - RelatedModel extends LucidModel, - ParentModel extends LucidModel = LucidModel - > = InstanceType & { - readonly __opaque_type: 'belongsTo' - model: RelatedModel - instance: InstanceType - client: BelongsToClientContract< - BelongsToRelationContract, - RelatedModel - > - builder: RelationQueryBuilderContract - subQuery: RelationSubQueryBuilderContract - } + hydrateForPersistance(parent: LucidRow, values: ModelObject | LucidRow): void +} + +/** + * Many to many relationship interface + */ +export interface ManyToManyRelationContract< + ParentModel extends LucidModel, + RelatedModel extends LucidModel, +> extends BaseRelationContract { + type: 'manyToMany' + + readonly localKey: string + readonly relatedKey: string + readonly pivotForeignKey: string + readonly pivotRelatedForeignKey: string + readonly pivotTable: string + pivotColumns: string[] /** - * Opaque type for many to many relationship + * Set related models as a relationship on the parent model */ - export type ManyToMany< - RelatedModel extends LucidModel, - ParentModel extends LucidModel = LucidModel - > = InstanceType[] & { - readonly __opaque_type: 'manyToMany' - model: RelatedModel - instance: InstanceType - client: ManyToManyClientContract< - ManyToManyRelationContract, - RelatedModel - > - builder: ManyToManyQueryBuilderContract - subQuery: ManyToManySubQueryBuilderContract - } + setRelated(parent: InstanceType, related: InstanceType[]): void /** - * Opaque type for many to many relationship + * Push related model(s) as a relationship on the parent model */ - export type HasManyThrough< - RelatedModel extends LucidModel, - ParentModel extends LucidModel = LucidModel - > = InstanceType[] & { - readonly __opaque_type: 'hasManyThrough' - model: RelatedModel - instance: InstanceType - client: HasManyThroughClientContract< - HasManyThroughRelationContract, - RelatedModel - > - builder: HasManyThroughQueryBuilderContract - subQuery: RelationSubQueryBuilderContract - } + pushRelated( + parent: InstanceType, + related: OneOrMany> + ): void /** - * These exists on the models directly as a relationship. The idea - * is to distinguish relationship properties from other model - * properties. + * Set multiple related instances on the multiple parent models. + * This method is generally invoked during eager load. */ - type ModelRelations = - | HasOne - | HasMany - | BelongsTo - | ManyToMany - | HasManyThrough + setRelatedForMany( + parent: InstanceType[], + related: InstanceType[] + ): void /** - * ------------------------------------------------------ - * Relationships - * ------------------------------------------------------ + * Returns the query client for one model instance */ + client( + parent: InstanceType, + client: QueryClientContract + ): ManyToManyClientContract /** - * Interface to be implemented by all relationship types + * Get eager query for the relationship */ - export interface BaseRelationContract< - ParentModel extends LucidModel, - RelatedModel extends LucidModel - > { - readonly type: ModelRelationTypes['__opaque_type'] - readonly relationName: string - readonly serializeAs: string | null - readonly booted: boolean - readonly model: ParentModel - relatedModel(): RelatedModel - boot(): void - clone(parent: LucidModel): this - - /** - * Get client - */ - client(parent: InstanceType, client: QueryClientContract): unknown - - /** - * Get eager query for the relationship - */ - eagerQuery( - parent: OneOrMany>, - client: QueryClientContract - ): RelationQueryBuilderContract> - - subQuery(client: QueryClientContract): RelationSubQueryBuilderContract - } + eagerQuery( + parent: OneOrMany>, + client: QueryClientContract + ): ManyToManyQueryBuilderContract> /** - * Has one relationship interface + * Get subquery for the relationships */ - export interface HasOneRelationContract< - ParentModel extends LucidModel, - RelatedModel extends LucidModel - > extends BaseRelationContract { - readonly type: 'hasOne' - readonly localKey: string - readonly foreignKey: string - - /** - * Set related model as a relationship on the parent model. - */ - setRelated(parent: InstanceType, related: InstanceType | null): void - - /** - * Push related model as a relationship on the parent model - */ - pushRelated(parent: InstanceType, related: InstanceType | null): void - - /** - * Set multiple related instances on the multiple parent models. - * This method is generally invoked during eager load. - * - * Fetch 10 users and then all profiles for all 10 users and then - * call this method to set related instances - */ - setRelatedForMany( - parent: InstanceType[], - related: InstanceType[] - ): void - - /** - * Returns the query client for one or many model instances. The query - * client then be used to fetch and persist relationships. - */ - client( - parent: InstanceType, - client: QueryClientContract - ): HasOneClientContract - - /** - * Hydrates related model attributes for persistance - */ - hydrateForPersistance(parent: LucidRow, values: ModelObject | LucidRow): void - } + subQuery(client: QueryClientContract): ManyToManySubQueryBuilderContract /** - * Has many relationship interface + * Returns key-value pair for the pivot table in relation to the parent model */ - export interface HasManyRelationContract< - ParentModel extends LucidModel, - RelatedModel extends LucidModel - > extends BaseRelationContract { - readonly type: 'hasMany' - readonly localKey: string - readonly foreignKey: string - - /** - * Set related models as a relationship on the parent model - */ - setRelated(parent: InstanceType, related: InstanceType[]): void - - /** - * Push related model(s) as a relationship on the parent model - */ - pushRelated( - parent: InstanceType, - related: OneOrMany> - ): void - - /** - * Set multiple related instances on the multiple parent models. - * This method is generally invoked during eager load. - * - * Fetch 10 users and then all posts for all 10 users and then - * call this method to set related instances - */ - setRelatedForMany( - parent: InstanceType[], - related: InstanceType[] - ): void - - /** - * Returns the query client for one or many model instances. The query - * client then be used to fetch and persist relationships. - */ - client( - parent: InstanceType, - client: QueryClientContract - ): HasManyClientContract - - /** - * Hydrates related model attributes for persistance - */ - hydrateForPersistance(parent: LucidRow, values: ModelObject | LucidRow): void - } + getPivotPair(parent: LucidRow): [string, number | string] /** - * Belongs to relationship interface + * Returns key-value pair for the pivot table in relation to the related model */ - export interface BelongsToRelationContract< - ParentModel extends LucidModel, - RelatedModel extends LucidModel - > extends BaseRelationContract { - readonly type: 'belongsTo' - readonly localKey: string - readonly foreignKey: string - - /** - * Set related model as a relationship on the parent model - */ - setRelated(parent: InstanceType, related: InstanceType | null): void - - /** - * Push related model as a relationship on the parent model - */ - pushRelated(parent: InstanceType, related: InstanceType | null): void - - /** - * Set multiple related instances on the multiple parent models. - * This method is generally invoked during eager load. - * - * Fetch 10 profiles and then users for all 10 profiles and then - * call this method to set related instances - */ - setRelatedForMany( - parent: InstanceType[], - related: InstanceType[] - ): void - - /** - * Returns the query client for a model instance - */ - client( - parent: InstanceType, - client: QueryClientContract - ): BelongsToClientContract - - /** - * Hydrates parent model attributes for persistance - */ - hydrateForPersistance(parent: LucidRow, values: ModelObject | LucidRow): void - } + getPivotRelatedPair(related: LucidRow): [string, number | string] +} + +/** + * Has many through relationship interface + */ +export interface HasManyThroughRelationContract< + ParentModel extends LucidModel, + RelatedModel extends LucidModel, +> extends BaseRelationContract { + type: 'hasManyThrough' + readonly localKey: string + readonly foreignKey: string + readonly throughLocalKey: string + readonly throughForeignKey: string /** - * Many to many relationship interface + * Set related models as a relationship on the parent model */ - export interface ManyToManyRelationContract< - ParentModel extends LucidModel, - RelatedModel extends LucidModel - > extends BaseRelationContract { - type: 'manyToMany' - - readonly localKey: string - readonly relatedKey: string - readonly pivotForeignKey: string - readonly pivotRelatedForeignKey: string - readonly pivotTable: string - pivotColumns: string[] - - /** - * Set related models as a relationship on the parent model - */ - setRelated(parent: InstanceType, related: InstanceType[]): void - - /** - * Push related model(s) as a relationship on the parent model - */ - pushRelated( - parent: InstanceType, - related: OneOrMany> - ): void - - /** - * Set multiple related instances on the multiple parent models. - * This method is generally invoked during eager load. - */ - setRelatedForMany( - parent: InstanceType[], - related: InstanceType[] - ): void - - /** - * Returns the query client for one model instance - */ - client( - parent: InstanceType, - client: QueryClientContract - ): ManyToManyClientContract - - /** - * Get eager query for the relationship - */ - eagerQuery( - parent: OneOrMany>, - client: QueryClientContract - ): ManyToManyQueryBuilderContract> - - /** - * Get subquery for the relationships - */ - subQuery(client: QueryClientContract): ManyToManySubQueryBuilderContract - - /** - * Returns key-value pair for the pivot table in relation to the parent model - */ - getPivotPair(parent: LucidRow): [string, number | string] - - /** - * Returns key-value pair for the pivot table in relation to the related model - */ - getPivotRelatedPair(related: LucidRow): [string, number | string] - } + setRelated(parent: InstanceType, related: InstanceType[]): void /** - * Has many through relationship interface + * Push related model(s) as a relationship on the parent model */ - export interface HasManyThroughRelationContract< - ParentModel extends LucidModel, - RelatedModel extends LucidModel - > extends BaseRelationContract { - type: 'hasManyThrough' - readonly localKey: string - readonly foreignKey: string - readonly throughLocalKey: string - readonly throughForeignKey: string - - /** - * Set related models as a relationship on the parent model - */ - setRelated(parent: InstanceType, related: InstanceType[]): void - - /** - * Push related model(s) as a relationship on the parent model - */ - pushRelated( - parent: InstanceType, - related: InstanceType | InstanceType[] - ): void - - /** - * Set multiple related instances on the multiple parent models. - * This method is generally invoked during eager load. - */ - setRelatedForMany( - parent: InstanceType[], - related: InstanceType[] - ): void - - /** - * Returns the query client for a model instance - */ - client( - model: InstanceType, - client: QueryClientContract - ): RelationQueryClientContract - } + pushRelated( + parent: InstanceType, + related: InstanceType | InstanceType[] + ): void /** - * A union of relationships + * Set multiple related instances on the multiple parent models. + * This method is generally invoked during eager load. */ - export type RelationshipsContract = - | HasOneRelationContract - | HasManyRelationContract - | BelongsToRelationContract - | ManyToManyRelationContract - | HasManyThroughRelationContract + setRelatedForMany( + parent: InstanceType[], + related: InstanceType[] + ): void /** - * ------------------------------------------------------ - * Relationships query client - * ------------------------------------------------------ + * Returns the query client for a model instance */ - export interface RelationQueryClientContract< - Relation extends RelationshipsContract, - RelatedModel extends LucidModel - > { - relation: Relation - - /** - * Return a query builder instance of the relationship - */ - query>(): RelationQueryBuilderContract - } + client( + model: InstanceType, + client: QueryClientContract + ): RelationQueryClientContract +} + +/** + * A union of relationships + */ +export type RelationshipsContract = + | HasOneRelationContract + | HasManyRelationContract + | BelongsToRelationContract + | ManyToManyRelationContract + | HasManyThroughRelationContract + +/** + * ------------------------------------------------------ + * Relationships query client + * ------------------------------------------------------ + */ +export interface RelationQueryClientContract< + Relation extends RelationshipsContract, + RelatedModel extends LucidModel, +> { + relation: Relation /** - * Query client for has one relationship + * Return a query builder instance of the relationship */ - export interface HasOneClientContract< - Relation extends RelationshipsContract, - RelatedModel extends LucidModel - > extends RelationQueryClientContract { - /** - * Save related instance. Sets up the FK automatically - */ - save(related: InstanceType): Promise - - /** - * Create related instance. Sets up the FK automatically - */ - create( - values: Partial>>, - options?: ModelAssignOptions - ): Promise> - - /** - * Return first or create related instance - */ - firstOrCreate( - search: Partial>>, - savePayload?: Partial>>, - options?: ModelAssignOptions - ): Promise> - - /** - * Update or create related instance - */ - updateOrCreate( - search: Partial>>, - updatePayload: Partial>>, - options?: ModelAssignOptions - ): Promise> - } + query>(): RelationQueryBuilderContract +} +/** + * Query client for has one relationship + */ +export interface HasOneClientContract< + Relation extends RelationshipsContract, + RelatedModel extends LucidModel, +> extends RelationQueryClientContract { /** - * Query client for has many relationship. Extends hasOne and - * adds support for saving many relations + * Save related instance. Sets up the FK automatically */ - export interface HasManyClientContract< - Relation extends RelationshipsContract, - RelatedModel extends LucidModel - > extends HasOneClientContract { - /** - * Save many of related instances. Sets up FK automatically - */ - saveMany(related: InstanceType[]): Promise - - /** - * Create many of related instances. Sets up FK automatically - */ - createMany( - values: Partial>>[], - options?: ModelAssignOptions - ): Promise[]> - - /** - * Fetch or create rows. Providers a great API to sync rows - */ - fetchOrCreateMany( - payload: Partial>>[], - predicate?: - | keyof ModelAttributes> - | (keyof ModelAttributes>)[], - options?: ModelAssignOptions - ): Promise[]> - - /** - * Update or create rows. Providers a great API to sync rows - */ - updateOrCreateMany( - payload: Partial>>[], - predicate?: - | keyof ModelAttributes> - | (keyof ModelAttributes>)[], - options?: ModelAssignOptions - ): Promise[]> - - /** - * Return a query builder instance of the relationship - */ - query>(): HasManyQueryBuilderContract - } + save(related: InstanceType): Promise /** - * Query client for belongs to relationship. Uses `associate` and - * `dissociate` over save. + * Create related instance. Sets up the FK automatically */ - export interface BelongsToClientContract< - Relation extends RelationshipsContract, - RelatedModel extends LucidModel - > extends RelationQueryClientContract { - /** - * Associate related instance - */ - associate(related: InstanceType): Promise - - /** - * Dissociate related instance - */ - dissociate(): Promise - } + create( + values: Partial>>, + options?: ModelAssignOptions + ): Promise> /** - * Query client for many to many relationship. + * Return first or create related instance */ - export interface ManyToManyClientContract< - Relation extends RelationshipsContract, - RelatedModel extends LucidModel - > extends RelationQueryClientContract { - /** - * Returns related model query builder instance - */ - query>(): ManyToManyQueryBuilderContract< - RelatedModel, - Result - > - - /** - * Pivot query just targets the pivot table without any joins - */ - pivotQuery(): ManyToManyQueryBuilderContract - - /** - * Save related model instance. Sets up FK automatically - */ - save( - related: InstanceType, - performSync?: boolean, // defaults to true - pivotAttributes?: ModelObject - ): Promise - - /** - * Save many of related model instance. Sets up FK automatically - */ - saveMany( - related: InstanceType[], - performSync?: boolean, // defaults to true - pivotAttributes?: (ModelObject | undefined)[] - ): Promise - - /** - * Create related model instance. Sets up FK automatically - */ - create( - values: Partial>>, - pivotAttributes?: ModelObject, - options?: ModelAssignOptions - ): Promise> - - /** - * Create many of related model instances. Sets up FK automatically - */ - createMany( - values: Partial>>[], - pivotAttributes?: (ModelObject | undefined)[], - options?: ModelAssignOptions - ): Promise[]> - - /** - * Attach new pivot rows - */ - attach( - ids: (string | number)[] | Record, - trx?: TransactionClientContract - ): Promise - - /** - * Detach existing pivot rows - */ - detach(ids?: (string | number)[], trx?: TransactionClientContract): Promise - - /** - * Sync pivot rows. - */ - sync( - ids: (string | number)[] | Record, - detach?: boolean, - trx?: TransactionClientContract - ): Promise - } + firstOrCreate( + search: Partial>>, + savePayload?: Partial>>, + options?: ModelAssignOptions + ): Promise> /** - * HasMany through client contract. HasMany through doesn't - * allow persisting relationships. Use the direct relation - * for that. + * Update or create related instance */ - export interface HasManyThroughClientContract< - Relation extends RelationshipsContract, - RelatedModel extends LucidModel - > extends RelationQueryClientContract { - /** - * Return a query builder instance of the relationship - */ - query>(): HasManyThroughQueryBuilderContract< - RelatedModel, - Result - > - } + updateOrCreate( + search: Partial>>, + updatePayload: Partial>>, + options?: ModelAssignOptions + ): Promise> +} +/** + * Query client for has many relationship. Extends hasOne and + * adds support for saving many relations + */ +export interface HasManyClientContract< + Relation extends RelationshipsContract, + RelatedModel extends LucidModel, +> extends HasOneClientContract { /** - * ------------------------------------------------------ - * Relationships query builders - * ------------------------------------------------------ + * Save many of related instances. Sets up FK automatically */ + saveMany(related: InstanceType[]): Promise /** - * Interface with query builder options for the many to many pivot - * table + * Create many of related instances. Sets up FK automatically */ - export interface PivotQueryBuilderContract { - pivotColumns(columns: string[]): this - - wherePivot: WherePivot - orWherePivot: WherePivot - andWherePivot: WherePivot - - whereNotPivot: WherePivot - orWhereNotPivot: WherePivot - andWhereNotPivot: WherePivot - - whereInPivot: WhereInPivot - orWhereInPivot: WhereInPivot - andWhereInPivot: WhereInPivot + createMany( + values: Partial>>[], + options?: ModelAssignOptions + ): Promise[]> - whereNotInPivot: WhereInPivot - orWhereNotInPivot: WhereInPivot - andWhereNotInPivot: WhereInPivot + /** + * Fetch or create rows. Providers a great API to sync rows + */ + fetchOrCreateMany( + payload: Partial>>[], + predicate?: + | keyof ModelAttributes> + | (keyof ModelAttributes>)[], + options?: ModelAssignOptions + ): Promise[]> - whereNullPivot: WhereNullPivot - orWhereNullPivot: WhereNullPivot - andWhereNullPivot: WhereNullPivot + /** + * Update or create rows. Providers a great API to sync rows + */ + updateOrCreateMany( + payload: Partial>>[], + predicate?: + | keyof ModelAttributes> + | (keyof ModelAttributes>)[], + options?: ModelAssignOptions + ): Promise[]> - whereNotNullPivot: WhereNullPivot - orWhereNotNullPivot: WhereNullPivot - andWhereNotNullPivot: WhereNullPivot - } + /** + * Return a query builder instance of the relationship + */ + query>(): HasManyQueryBuilderContract +} +/** + * Query client for belongs to relationship. Uses `associate` and + * `dissociate` over save. + */ +export interface BelongsToClientContract< + Relation extends RelationshipsContract, + RelatedModel extends LucidModel, +> extends RelationQueryClientContract { /** - * Base query builder for all relations + * Associate related instance */ - export interface RelationQueryBuilderContract - extends ModelQueryBuilderContract { - /** - * Is query a relationship query obtained using `related('relation').query()` - */ - isRelatedQuery: true - - /** - * Is query a relationship query obtained using `related('relation').subQuery()` - */ - isRelatedSubQuery: false - - /** - * Is query a relationship query obtained using one of the preload methods. - */ - isRelatedPreloadQuery: boolean - selectRelationKeys(): this - } + associate(related: InstanceType): Promise /** - * Has many query builder contract + * Dissociate related instance */ - export interface HasManyQueryBuilderContract - extends RelationQueryBuilderContract { - groupLimit(limit: number): this - groupOrderBy(column: string, direction?: 'asc' | 'desc'): this - } + dissociate(): Promise +} +/** + * Query client for many to many relationship. + */ +export interface ManyToManyClientContract< + Relation extends RelationshipsContract, + RelatedModel extends LucidModel, +> extends RelationQueryClientContract { /** - * Has many query through builder contract + * Returns related model query builder instance */ - export interface HasManyThroughQueryBuilderContract - extends RelationQueryBuilderContract { - groupLimit(limit: number): this - groupOrderBy(column: string, direction?: 'asc' | 'desc'): this - } + query>(): ManyToManyQueryBuilderContract /** - * Possible signatures for adding a where clause + * Pivot query just targets the pivot table without any joins */ - interface WherePivot { - (key: string, value: StrictValues | ChainableContract): Builder - (key: string, operator: string, value: StrictValues | ChainableContract): Builder - } + pivotQuery(): ManyToManyQueryBuilderContract /** - * Possible signatures for adding whereNull clause. + * Save related model instance. Sets up FK automatically */ - interface WhereNullPivot { - (key: string): Builder - } + save( + related: InstanceType, + performSync?: boolean, // defaults to true + pivotAttributes?: ModelObject + ): Promise /** - * Possible signatures for adding where in clause. + * Save many of related model instance. Sets up FK automatically */ - interface WhereInPivot { - (K: string, value: StrictValues[]): Builder - (K: string[], value: StrictValues[][]): Builder - ( - k: string, - subquery: ChainableContract | QueryCallback | RawBuilderContract | RawQuery - ): Builder - (k: string[], subquery: ChainableContract | RawBuilderContract | RawQuery): Builder - } + saveMany( + related: InstanceType[], + performSync?: boolean, // defaults to true + pivotAttributes?: (ModelObject | undefined)[] + ): Promise /** - * Shape of many to many query builder. It has few methods over the standard - * model query builder + * Create related model instance. Sets up FK automatically */ - export interface ManyToManyQueryBuilderContract - extends RelationQueryBuilderContract, - PivotQueryBuilderContract { - isPivotOnlyQuery: boolean - groupLimit(limit: number): this - groupOrderBy(column: string, direction?: 'asc' | 'desc'): this - } + create( + values: Partial>>, + pivotAttributes?: ModelObject, + options?: ModelAssignOptions + ): Promise> /** - * ------------------------------------------------------ - * Sub Queries - * ------------------------------------------------------ + * Create many of related model instances. Sets up FK automatically */ + createMany( + values: Partial>>[], + pivotAttributes?: (ModelObject | undefined)[], + options?: ModelAssignOptions + ): Promise[]> /** - * Not in use right now. Since after omitting these types from the - * model query builder losses "this" scope. Need to re-think + * Attach new pivot rows */ - export type UnSupportedSubQueryMethods = - | 'preload' - | 'decrement' - | 'increment' - | 'update' - | 'paginate' - | 'delete' - | 'del' - | 'firstOrFail' - | 'first' - | 'exec' - | 'withCount' + attach( + ids: (string | number)[] | Record, + trx?: TransactionClientContract + ): Promise /** - * SubQuery builder allows creating sub queries targeting a relationship. Sub queries - * cannot be executed directly, but can be used as a reference in the parent query - * builder. Use cases are: - * - * - withCount - * - whereHas + * Detach existing pivot rows */ - export interface RelationSubQueryBuilderContract - extends ModelQueryBuilderContract { - /** - * Is query a relationship query obtained using `related('relation').query()` - */ - isRelatedQuery: false - - /** - * Is query a relationship query obtained using `related('relation').subQuery()` - */ - isRelatedSubQuery: true - - /** - * Is query a relationship query obtained using one of the preload methods. - */ - isRelatedPreloadQuery: false - - selfJoinCounter: number - readonly selfJoinAlias: string - selectRelationKeys(): this - prepare(): this - } + detach(ids?: (string | number)[], trx?: TransactionClientContract): Promise /** - * SubQuery builder for many to many relationship + * Sync pivot rows. */ - export interface ManyToManySubQueryBuilderContract - extends RelationSubQueryBuilderContract, - PivotQueryBuilderContract {} + sync( + ids: (string | number)[] | Record, + detach?: boolean, + trx?: TransactionClientContract + ): Promise +} +/** + * HasMany through client contract. HasMany through doesn't + * allow persisting relationships. Use the direct relation + * for that. + */ +export interface HasManyThroughClientContract< + Relation extends RelationshipsContract, + RelatedModel extends LucidModel, +> extends RelationQueryClientContract { /** - * The withCount function + * Return a query builder instance of the relationship */ - export interface WithCount { - < - Name extends ExtractModelRelations, - RelatedBuilder = Model[Name] extends ModelRelations ? Model[Name]['subQuery'] : never - >( - relation: Name, - callback?: (builder: RelatedBuilder) => void - ): Builder - } + query>(): HasManyThroughQueryBuilderContract< + RelatedModel, + Result + > +} +/** + * ------------------------------------------------------ + * Relationships query builders + * ------------------------------------------------------ + */ + +/** + * Interface with query builder options for the many to many pivot + * table + */ +export interface PivotQueryBuilderContract { + pivotColumns(columns: string[]): this + + wherePivot: WherePivot + orWherePivot: WherePivot + andWherePivot: WherePivot + + whereNotPivot: WherePivot + orWhereNotPivot: WherePivot + andWhereNotPivot: WherePivot + + whereInPivot: WhereInPivot + orWhereInPivot: WhereInPivot + andWhereInPivot: WhereInPivot + + whereNotInPivot: WhereInPivot + orWhereNotInPivot: WhereInPivot + andWhereNotInPivot: WhereInPivot + + whereNullPivot: WhereNullPivot + orWhereNullPivot: WhereNullPivot + andWhereNullPivot: WhereNullPivot + + whereNotNullPivot: WhereNullPivot + orWhereNotNullPivot: WhereNullPivot + andWhereNotNullPivot: WhereNullPivot +} + +/** + * Base query builder for all relations + */ +export interface RelationQueryBuilderContract + extends ModelQueryBuilderContract { /** - * The with aggregate function + * Is query a relationship query obtained using `related('relation').query()` */ - export interface WithAggregate { - < - Name extends ExtractModelRelations, - RelatedBuilder = Model[Name] extends ModelRelations ? Model[Name]['subQuery'] : never - >( - relation: Name, - callback: (builder: RelatedBuilder) => void - ): Builder - } + isRelatedQuery: true /** - * The has function + * Is query a relationship query obtained using `related('relation').subQuery()` */ - export interface Has { - >( - relation: Name, - operator?: string, - value?: StrictValues | ChainableContract - ): Builder - } + isRelatedSubQuery: false /** - * The whereHas function + * Is query a relationship query obtained using one of the preload methods. */ - export interface WhereHas { - < - Name extends ExtractModelRelations, - RelatedBuilder = Model[Name] extends ModelRelations ? Model[Name]['subQuery'] : never - >( - relation: Name, - callback: (builder: RelatedBuilder) => void, - operator?: string, - value?: StrictValues | ChainableContract - ): Builder - } + isRelatedPreloadQuery: boolean + selectRelationKeys(): this +} + +/** + * Has many query builder contract + */ +export interface HasManyQueryBuilderContract + extends RelationQueryBuilderContract { + groupLimit(limit: number): this + groupOrderBy(column: string, direction?: 'asc' | 'desc'): this +} + +/** + * Has many query through builder contract + */ +export interface HasManyThroughQueryBuilderContract + extends RelationQueryBuilderContract { + groupLimit(limit: number): this + groupOrderBy(column: string, direction?: 'asc' | 'desc'): this +} + +/** + * Possible signatures for adding a where clause + */ +interface WherePivot { + (key: string, value: StrictValues | ChainableContract): Builder + (key: string, operator: string, value: StrictValues | ChainableContract): Builder +} + +/** + * Possible signatures for adding whereNull clause. + */ +interface WhereNullPivot { + (key: string): Builder +} + +/** + * Possible signatures for adding where in clause. + */ +interface WhereInPivot { + (K: string, value: StrictValues[]): Builder + (K: string[], value: StrictValues[][]): Builder + ( + k: string, + subquery: ChainableContract | QueryCallback | RawBuilderContract | RawQuery + ): Builder + (k: string[], subquery: ChainableContract | RawBuilderContract | RawQuery): Builder +} + +/** + * Shape of many to many query builder. It has few methods over the standard + * model query builder + */ +export interface ManyToManyQueryBuilderContract + extends RelationQueryBuilderContract, + PivotQueryBuilderContract { + isPivotOnlyQuery: boolean + groupLimit(limit: number): this + groupOrderBy(column: string, direction?: 'asc' | 'desc'): this +} + +/** + * ------------------------------------------------------ + * Sub Queries + * ------------------------------------------------------ + */ +/** + * Not in use right now. Since after omitting these types from the + * model query builder losses "this" scope. Need to re-think + */ +export type UnSupportedSubQueryMethods = + | 'preload' + | 'decrement' + | 'increment' + | 'update' + | 'paginate' + | 'delete' + | 'del' + | 'firstOrFail' + | 'first' + | 'exec' + | 'withCount' + +/** + * SubQuery builder allows creating sub queries targeting a relationship. Sub queries + * cannot be executed directly, but can be used as a reference in the parent query + * builder. Use cases are: + * + * - withCount + * - whereHas + */ +export interface RelationSubQueryBuilderContract + extends ModelQueryBuilderContract { /** - * ------------------------------------------------------ - * Preloader - * ------------------------------------------------------ + * Is query a relationship query obtained using `related('relation').query()` */ + isRelatedQuery: false /** - * The preload function + * Is query a relationship query obtained using `related('relation').subQuery()` */ - export interface Preload { - < - Name extends ExtractModelRelations, - RelatedBuilder = Model[Name] extends ModelRelations ? Model[Name]['builder'] : never - >( - relation: Name, - callback?: (builder: RelatedBuilder) => void - ): Builder - } + isRelatedSubQuery: true /** - * Shape of the preloader to preload relationships + * Is query a relationship query obtained using one of the preload methods. */ - export interface PreloaderContract { - processAllForOne(parent: Model, client: QueryClientContract): Promise - processAllForMany(parent: Model[], client: QueryClientContract): Promise + isRelatedPreloadQuery: false + + selfJoinCounter: number + readonly selfJoinAlias: string + selectRelationKeys(): this + prepare(): this +} + +/** + * SubQuery builder for many to many relationship + */ +export interface ManyToManySubQueryBuilderContract + extends RelationSubQueryBuilderContract, + PivotQueryBuilderContract {} + +/** + * The withCount function + */ +export interface WithCount { + < + Name extends ExtractModelRelations, + RelatedBuilder = Model[Name] extends ModelRelations ? Model[Name]['subQuery'] : never, + >( + relation: Name, + callback?: (builder: RelatedBuilder) => void + ): Builder +} + +/** + * The with aggregate function + */ +export interface WithAggregate { + < + Name extends ExtractModelRelations, + RelatedBuilder = Model[Name] extends ModelRelations ? Model[Name]['subQuery'] : never, + >( + relation: Name, + callback: (builder: RelatedBuilder) => void + ): Builder +} + +/** + * The has function + */ +export interface Has { + >( + relation: Name, + operator?: string, + value?: StrictValues | ChainableContract + ): Builder +} + +/** + * The whereHas function + */ +export interface WhereHas { + < + Name extends ExtractModelRelations, + RelatedBuilder = Model[Name] extends ModelRelations ? Model[Name]['subQuery'] : never, + >( + relation: Name, + callback: (builder: RelatedBuilder) => void, + operator?: string, + value?: StrictValues | ChainableContract + ): Builder +} + +/** + * ------------------------------------------------------ + * Preloader + * ------------------------------------------------------ + */ + +/** + * The preload function + */ +export interface Preload { + < + Name extends ExtractModelRelations, + RelatedBuilder = Model[Name] extends ModelRelations ? Model[Name]['builder'] : never, + >( + relation: Name, + callback?: (builder: RelatedBuilder) => void + ): Builder +} + +/** + * Shape of the preloader to preload relationships + */ +export interface PreloaderContract { + processAllForOne(parent: Model, client: QueryClientContract): Promise + processAllForMany(parent: Model[], client: QueryClientContract): Promise - load: Preload - preload: Preload + load: Preload + preload: Preload - debug(debug: boolean): this - sideload(values: ModelObject): this - } + debug(debug: boolean): this + sideload(values: ModelObject): this } diff --git a/adonis-typings/schema.ts b/adonis-typings/schema.ts index 89edc26f..3cbfdb34 100644 --- a/adonis-typings/schema.ts +++ b/adonis-typings/schema.ts @@ -7,42 +7,9 @@ * file that was distributed with this source code. */ -declare module '@ioc:Adonis/Lucid/Schema' { - import { Knex } from 'knex' - import { QueryClientContract, RawQueryBindings } from '@ioc:Adonis/Lucid/Database' +import { QueryClientContract } from './database.js' - /** - * Shape of callback to defer database calls - */ - export type DeferCallback = (client: QueryClientContract) => void | Promise - - /** - * Shape of schema class constructor - */ - export interface SchemaConstructorContract { - disableTransactions: boolean - new (db: QueryClientContract, file: string, dryRun: boolean): SchemaContract - } - - /** - * Shape of schema class - */ - export interface SchemaContract { - readonly file: string - dryRun: boolean - debug: boolean - db: QueryClientContract - schema: Knex.SchemaBuilder - now(precision?: number): Knex.Raw - knex(): Knex.QueryBuilder - raw(sql: string, bindings?: RawQueryBindings): Knex.Raw - defer: (cb: DeferCallback) => void - up(): Promise | void - down(): Promise | void - execUp(): Promise - execDown(): Promise - } - - const Schema: SchemaConstructorContract - export default Schema -} +/** + * Shape of callback to defer database calls + */ +export type DeferCallback = (client: QueryClientContract) => void | Promise diff --git a/adonis-typings/seeder.ts b/adonis-typings/seeder.ts index f6ccb17d..ae5eb089 100644 --- a/adonis-typings/seeder.ts +++ b/adonis-typings/seeder.ts @@ -7,33 +7,13 @@ * file that was distributed with this source code. */ -declare module '@ioc:Adonis/Lucid/Seeder' { - import { QueryClientContract, FileNode } from '@ioc:Adonis/Lucid/Database' +import { FileNode } from './database.js' - /** - * Shape of seeder class - */ - export type SeederConstructorContract = { - /** - * @deprecated - */ - developmentOnly: boolean - environment: string[] - new (client: QueryClientContract): { - client: QueryClientContract - run(): Promise - } - } - - /** - * Shape of file node returned by the run method - */ - export type SeederFileNode = { - status: 'pending' | 'completed' | 'failed' | 'ignored' - error?: any - file: FileNode - } - - const BaseSeeder: SeederConstructorContract - export default BaseSeeder +/** + * Shape of file node returned by the run method + */ +export type SeederFileNode = { + status: 'pending' | 'completed' | 'failed' | 'ignored' + error?: any + file: FileNode } diff --git a/adonis-typings/test-utils.ts b/adonis-typings/test-utils.ts deleted file mode 100644 index 51f0ea06..00000000 --- a/adonis-typings/test-utils.ts +++ /dev/null @@ -1,21 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -declare module '@ioc:Adonis/Core/TestUtils' { - type HookCleanupHandler = () => Promise - type HookCallback = () => Promise | Promise - - export interface TestUtilsContract { - db(connectionName?: string): { - seed: HookCallback - migrate: HookCallback - truncate: HookCallback - } - } -} diff --git a/adonis-typings/test_utils.ts b/adonis-typings/test_utils.ts new file mode 100644 index 00000000..8f8cccb6 --- /dev/null +++ b/adonis-typings/test_utils.ts @@ -0,0 +1,21 @@ +/* + * @adonisjs/lucid + * + * (c) Harminder Virk + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +// declare module '@ioc:Adonis/Core/TestUtils' { +// type HookCleanupHandler = () => Promise +// type HookCallback = () => Promise | Promise + +// export interface TestUtilsContract { +// db(connectionName?: string): { +// seed: HookCallback +// migrate: HookCallback +// truncate: HookCallback +// } +// } +// } diff --git a/adonis-typings/validator.ts b/adonis-typings/validator.ts index 5bf93ac2..c32d7cca 100644 --- a/adonis-typings/validator.ts +++ b/adonis-typings/validator.ts @@ -7,22 +7,22 @@ * file that was distributed with this source code. */ -declare module '@ioc:Adonis/Core/Validator' { - import { Rule } from '@ioc:Adonis/Core/Validator' +// declare module '@ioc:Adonis/Core/Validator' { +// import { Rule } from '@ioc:Adonis/Core/Validator' - export type DbRowCheckOptions = { - table: string - column: string - dateFormat?: string - connection?: string - caseInsensitive?: boolean - constraints?: { [key: string]: any } - where?: { [key: string]: any } - whereNot?: { [key: string]: any } - } +// export type DbRowCheckOptions = { +// table: string +// column: string +// dateFormat?: string +// connection?: string +// caseInsensitive?: boolean +// constraints?: { [key: string]: any } +// where?: { [key: string]: any } +// whereNot?: { [key: string]: any } +// } - export interface Rules { - exists(options: DbRowCheckOptions): Rule - unique(options: DbRowCheckOptions): Rule - } -} +// export interface Rules { +// exists(options: DbRowCheckOptions): Rule +// unique(options: DbRowCheckOptions): Rule +// } +// } diff --git a/bin/japaTypes.ts b/bin/japaTypes.ts deleted file mode 100644 index 7ee34011..00000000 --- a/bin/japaTypes.ts +++ /dev/null @@ -1,2 +0,0 @@ -import '@japa/assert' -declare module '@japa/runner' {} diff --git a/bin/test.ts b/bin/test.ts index 4f30a926..55c5501d 100644 --- a/bin/test.ts +++ b/bin/test.ts @@ -1,9 +1,6 @@ import { assert } from '@japa/assert' -import { specReporter } from '@japa/spec-reporter' -import { runFailedTests } from '@japa/run-failed-tests' -import { processCliArgs, configure, run } from '@japa/runner' -import { remove } from 'fs-extra' -import { join } from 'path' +import { fileSystem } from '@japa/file-system' +import { processCLIArgs, configure, run } from '@japa/runner' /* |-------------------------------------------------------------------------- @@ -18,19 +15,10 @@ import { join } from 'path' | | Please consult japa.dev/runner-config for the config docs. */ +processCLIArgs(process.argv.slice(2)) configure({ - ...processCliArgs(process.argv.slice(2)), - ...{ - files: ['test/**/*.spec.ts'], - plugins: [assert(), runFailedTests()], - reporters: [specReporter()], - importer: (filePath: string) => import(filePath), - teardown: [ - async () => { - await remove(join(__dirname, 'test-helpers', 'tmp')) - }, - ], - }, + files: ['test/**/*.spec.ts'], + plugins: [assert(), fileSystem()], }) /* diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 00000000..ecfee9ca --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,99 @@ +version: '3.8' + +services: + legacy_mysql: + platform: linux/x86_64 + image: mysql:5.7 + container_name: legacy_mysql + env_file: ./.env + environment: + - MYSQL_USER=$LEGACY_MYSQL_USER + - MYSQL_PASSWORD=$LEGACY_MYSQL_PASSWORD + - MYSQL_DATABASE=$LEGACY_MYSQL_DATABASE + - MYSQL_ROOT_PASSWORD=$LEGACY_MYSQL_PASSWORD + ports: + - $LEGACY_MYSQL_PORT:3306 + expose: + - $LEGACY_MYSQL_PORT + + mysql: + platform: linux/x86_64 + image: mysql:8.0 + command: --default-authentication-plugin=mysql_native_password --sync_binlog=0 --innodb_doublewrite=OFF --innodb-flush-log-at-trx-commit=0 --innodb-flush-method=nosync + container_name: mysql + env_file: ./.env + environment: + - MYSQL_USER=$MYSQL_USER + - MYSQL_PASSWORD=$MYSQL_PASSWORD + - MYSQL_DATABASE=$MYSQL_DATABASE + - MYSQL_ROOT_PASSWORD=$MYSQL_PASSWORD + ports: + - $MYSQL_PORT:3306 + expose: + - $MYSQL_PORT + + legacy_mysql_read_replica: + platform: linux/x86_64 + image: mysql:5.7 + container_name: legacy_mysql_read_replica + env_file: ./.env + environment: + - MYSQL_USER=$LEGACY_MYSQL_READ_REPLICA_USER + - MYSQL_PASSWORD=$LEGACY_MYSQL_READ_REPLICA_PASSWORD + - MYSQL_DATABASE=$LEGACY_MYSQL_READ_REPLICA_DATABASE + - MYSQL_ROOT_PASSWORD=$LEGACY_MYSQL_READ_REPLICA_PASSWORD + ports: + - $LEGACY_MYSQL_READ_REPLICA_PORT:3306 + expose: + - $LEGACY_MYSQL_READ_REPLICA_PORT + + pg: + image: postgres:11 + container_name: pg + env_file: ./.env + environment: + - POSTGRES_DB=$PG_DATABASE + - POSTGRES_USER=$PG_USER + - POSTGRES_PASSWORD=$PG_PASSWORD + ports: + - $PG_PORT:5432 + expose: + - $PG_PORT + + pg_read_replica: + image: postgres:11 + container_name: pg_read_replica + env_file: ./.env + environment: + - POSTGRES_DB=$PG_READ_REPLICA_DATABASE + - POSTGRES_USER=$PG_READ_REPLICA_USER + - POSTGRES_PASSWORD=$PG_READ_REPLICA_PASSWORD + ports: + - $PG_READ_REPLICA_PORT:5432 + expose: + - $PG_READ_REPLICA_PORT + + mssql: + platform: linux/x86_64 + image: mcr.microsoft.com/mssql/server:2019-latest + container_name: mssql + env_file: ./.env + environment: + - SA_PASSWORD=$MSSQL_PASSWORD + - ACCEPT_EULA='Y' + ports: + - $MSSQL_PORT:1433 + expose: + - $MSSQL_PORT + + mssql_read_replica: + image: mcr.microsoft.com/mssql/server:2019-latest + container_name: mssql_read_replica + env_file: ./.env + environment: + - SA_PASSWORD=$MSSQL_READ_REPLICA_PASSWORD + - ACCEPT_EULA='Y' + ports: + - $MSSQL_READ_REPLICA_PORT:1433 + expose: + - $MSSQL_READ_REPLICA_PORT diff --git a/package.json b/package.json index 4992ade3..3cde9e64 100644 --- a/package.json +++ b/package.json @@ -2,192 +2,121 @@ "name": "@adonisjs/lucid", "version": "18.4.0", "description": "SQL ORM built on top of Active Record pattern", - "main": "build/providers/DatabaseProvider.js", - "files": [ - "build/adonis-typings", - "build/commands", - "build/providers", - "build/src", - "build/instructions.js", - "build/templates", - "build/instructions.md" - ], - "typings": "./build/adonis-typings/index.d.ts", + "engines": { + "node": ">=18.16.0" + }, + "type": "module", "scripts": { - "mrm": "mrm --preset=@adonisjs/mrm-preset", "pretest": "npm run lint", - "test:better_sqlite": "sh ./scripts/run-tests.sh better_sqlite", - "test:sqlite": "sh ./scripts/run-tests.sh sqlite", - "test:mysql": "sh ./scripts/run-tests.sh mysql", - "test:mysql_legacy": "sh ./scripts/run-tests.sh mysql_legacy", - "test:mssql": "sh ./scripts/run-tests.sh mssql", - "test:pg": "sh ./scripts/run-tests.sh pg", + "test:better_sqlite": "DB=better_sqlite node --enable-source-maps --loader=ts-node/esm ./bin/test.js", + "test:sqlite": "DB=sqlite node --enable-source-maps --loader=ts-node/esm ./bin/test.js", + "test:mysql": "DB=mysql node --enable-source-maps --loader=ts-node/esm ./bin/test.js", + "test:mysql_legacy": "DB=mysql_legacy node --enable-source-maps --loader=ts-node/esm ./bin/test.js", + "test:mssql": "DB=mssql node --enable-source-maps --loader=ts-node/esm ./bin/test.js", + "test:pg": "DB=pg node --enable-source-maps --loader=ts-node/esm ./bin/test.js", "test:docker": "npm run test:mysql && npm run test:mysql_legacy && npm run test:pg && npm run test:mssql", "lint": "eslint . --ext=.ts", "clean": "del-cli build", "compile": "npm run lint && npm run clean && tsc && npm run copyfiles", "copyfiles": "copyfiles \"templates/**/*.txt\" \"instructions.md\" build", "build": "npm run compile", - "commit": "git-cz", - "release": "np --message=\"chore(release): %s\"", + "release": "np", "version": "npm run build", + "typecheck": "tsc --noEmit", "sync-labels": "github-label-sync --labels ./node_modules/@adonisjs/mrm-preset/gh-labels.json adonisjs/lucid", "format": "prettier --write .", - "prepublishOnly": "npm run build" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/adonisjs/lucid.git" - }, - "author": "virk,adonisjs", - "license": "MIT", - "bugs": { - "url": "https://github.com/adonisjs/lucid/issues" + "prepublishOnly": "npm run build", + "test": "c8 npm run test:docker" }, - "homepage": "https://github.com/adonisjs/lucid#readme", "dependencies": { "@faker-js/faker": "^8.0.1", - "@poppinss/hooks": "^5.0.3", - "@poppinss/utils": "^5.0.0", + "@poppinss/hooks": "^7.1.1-4", + "@poppinss/macroable": "^1.0.0-0", + "@poppinss/utils": "^6.5.0-6", "fast-deep-equal": "^3.1.3", "igniculus": "^1.5.0", "knex": "^2.4.2", - "knex-dynamic-connection": "^3.0.1", + "knex-dynamic-connection": "^3.1.0", "luxon": "^3.3.0", - "macroable": "^7.0.2", "pretty-hrtime": "^1.0.3", "qs": "^6.11.2", - "slash": "^3.0.0", + "slash": "^5.1.0", "tarn": "^3.0.2" }, - "peerDependencies": { - "@adonisjs/core": "^5.1.0" - }, "devDependencies": { - "@adonisjs/ace": "^11.3.1", - "@adonisjs/core": "^5.9.0", - "@adonisjs/mrm-preset": "^5.0.3", - "@adonisjs/repl": "^3.1.11", - "@adonisjs/require-ts": "^2.0.13", - "@adonisjs/sink": "^5.4.3", - "@adonisjs/validator": "^12.4.2", - "@japa/assert": "^1.4.1", - "@japa/run-failed-tests": "^1.1.1", - "@japa/runner": "^2.5.1", - "@japa/spec-reporter": "^1.3.3", - "@poppinss/dev-utils": "^2.0.3", + "@adonisjs/core": "^6.1.5-26", + "@adonisjs/eslint-config": "^1.1.8", + "@adonisjs/prettier-config": "^1.1.8", + "@adonisjs/tsconfig": "^1.1.8", + "@commitlint/cli": "^17.7.1", + "@commitlint/config-conventional": "^17.7.0", + "@japa/assert": "^2.0.0-1", + "@japa/file-system": "^2.0.0-1", + "@japa/runner": "^3.0.0-7", + "@swc/core": "1.3.82", + "@types/chance": "^1.1.4", "@types/luxon": "^3.3.0", - "@types/node": "^20.2.3", - "@types/pluralize": "0.0.29", + "@types/node": "^20.6.2", + "@types/pluralize": "^0.0.30", + "@types/pretty-hrtime": "^1.0.1", "@types/qs": "^6.9.7", "better-sqlite3": "^8.4.0", + "c8": "^8.0.1", "chance": "^1.1.11", - "commitizen": "^4.3.0", "copyfiles": "^2.4.1", "cross-env": "^7.0.3", - "cz-conventional-changelog": "^3.3.0", "del-cli": "^5.0.0", "dotenv": "^16.0.3", "eslint": "^8.41.0", - "eslint-config-prettier": "^8.8.0", - "eslint-plugin-adonis": "^2.1.1", - "eslint-plugin-prettier": "^4.2.1", "fs-extra": "^11.1.1", "github-label-sync": "^2.3.1", "husky": "^8.0.3", - "mrm": "^4.1.14", "mysql2": "^3.3.1", - "np": "^7.7.0", + "np": "^8.0.4", "pg": "^8.11.0", - "prettier": "^2.8.8", + "prettier": "^3.0.3", "reflect-metadata": "^0.1.13", "sqlite3": "^5.1.6", "tedious": "^16.1.0", - "typescript": "4.8.4" + "ts-node": "^10.9.1", + "typescript": "^5.2.2" }, - "publishConfig": { - "tag": "latest", - "access": "public" - }, - "nyc": { - "exclude": [ - "test" - ], - "extension": [ - ".ts" - ] + "license": "MIT", + "author": "virk,adonisjs", + "homepage": "https://github.com/adonisjs/lucid#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/adonisjs/lucid.git" }, - "config": { - "commitizen": { - "path": "cz-conventional-changelog" - } + "bugs": { + "url": "https://github.com/adonisjs/lucid/issues" }, - "directories": { - "test": "test" + "eslintConfig": { + "extends": "@adonisjs/eslint-config/package" }, - "keywords": [], - "adonisjs": { - "instructions": "./build/instructions.js", - "instructionsMd": "./build/instructions.md", - "types": "@adonisjs/lucid", - "providers": [ - "@adonisjs/lucid" - ], - "commands": [ - "@adonisjs/lucid/build/commands" - ], - "templates": { - "database": [ - "factories/index.txt" - ] - } + "prettier": "@adonisjs/prettier-config", + "publishConfig": { + "access": "public", + "tag": "next" }, "np": { - "contents": ".", - "anyBranch": false, - "yolo": true + "message": "chore(release): %s", + "tag": "next", + "branch": "main", + "anyBranch": false }, - "mrmConfig": { - "core": true, - "license": "MIT", - "services": [ - "github-actions" - ], - "minNodeVersion": "14.15.4", - "probotApps": [ - "stale", - "lock" - ], - "runGhActionsOnWindows": false - }, - "eslintConfig": { + "commitlint": { "extends": [ - "plugin:adonis/typescriptPackage", - "prettier" - ], - "plugins": [ - "prettier" - ], - "rules": { - "prettier/prettier": [ - "error", - { - "endOfLine": "auto" - } - ] - } + "@commitlint/config-conventional" + ] }, - "eslintIgnore": [ - "build" - ], - "prettier": { - "trailingComma": "es5", - "semi": false, - "singleQuote": true, - "useTabs": false, - "quoteProps": "consistent", - "bracketSpacing": true, - "arrowParens": "always", - "printWidth": 100 + "c8": { + "reporter": [ + "text", + "html" + ], + "exclude": [ + "tests/**" + ] } } diff --git a/scripts/Dockerfile b/scripts/Dockerfile deleted file mode 100644 index 957652fe..00000000 --- a/scripts/Dockerfile +++ /dev/null @@ -1,20 +0,0 @@ -FROM node:16.14.0-alpine as build-deps - -RUN apk update && apk upgrade && \ - apk add --update git && \ - apk add --update openssh && \ - apk add --update bash && \ - apk add --update wget && \ - apk add --update g++ make python3 - -WORKDIR /usr/src/app - -COPY package*.json ./ -RUN HUSKY_SKIP_INSTALL=1 npm install --build-from-source --python=/usr/bin/python3 - -RUN wget https://raw.githubusercontent.com/vishnubob/wait-for-it/master/wait-for-it.sh -O /wait-for-it.sh -RUN chmod +x /wait-for-it.sh - -COPY . . - -RUN npm run build diff --git a/scripts/docker-compose.yml b/scripts/docker-compose.yml deleted file mode 100644 index 4075e961..00000000 --- a/scripts/docker-compose.yml +++ /dev/null @@ -1,75 +0,0 @@ -version: '3.4' -services: - mysql_legacy: - platform: linux/x86_64 - image: mysql:5.7 - environment: - MYSQL_DATABASE: lucid - MYSQL_USER: virk - MYSQL_PASSWORD: password - MYSQL_ROOT_PASSWORD: password - ports: - - '3306:3306' - expose: - - '3306' - - mysql_replica_1: - platform: linux/x86_64 - image: mysql:5.7 - environment: - MYSQL_DATABASE: lucid - MYSQL_USER: virk - MYSQL_PASSWORD: password - MYSQL_ROOT_PASSWORD: password - ports: - - '3304:3306' - expose: - - '3306' - - mysql_replica_2: - platform: linux/x86_64 - image: mysql:5.7 - environment: - MYSQL_DATABASE: lucid - MYSQL_USER: virk - MYSQL_PASSWORD: password - MYSQL_ROOT_PASSWORD: password - ports: - - '3303:3306' - expose: - - '3306' - - mysql: - platform: linux/x86_64 - image: mysql:8.0 - command: --default-authentication-plugin=mysql_native_password --sync_binlog=0 --innodb_doublewrite=OFF --innodb-flush-log-at-trx-commit=0 --innodb-flush-method=nosync - environment: - MYSQL_DATABASE: lucid - MYSQL_USER: virk - MYSQL_PASSWORD: password - MYSQL_ROOT_PASSWORD: password - ports: - - '3306:3306' - expose: - - '3306' - - pg: - image: postgres:11 - environment: - POSTGRES_DB: lucid - POSTGRES_USER: virk - POSTGRES_PASSWORD: password - ports: - - 5432:5432 - expose: - - '5432' - - mssql: - image: mcr.microsoft.com/mssql/server:2019-latest - ports: - - 1433:1433 - expose: - - '1433' - environment: - SA_PASSWORD: 'arandom&233password' - ACCEPT_EULA: 'Y' diff --git a/scripts/run-tests.sh b/scripts/run-tests.sh deleted file mode 100644 index 9c1fb49c..00000000 --- a/scripts/run-tests.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/bash - -docker-compose -f ./scripts/docker-compose.yml down - -if [ $1 != "better_sqlite" ] && [ $1 != "sqlite" ]; then - docker-compose -f ./scripts/docker-compose.yml up -d $1 -fi - -DB=$1 FORCE_COLOR=true node -r @adonisjs/require-ts/build/register ./bin/test.ts diff --git a/src/Factory/FactoryContext.ts b/src/Factory/FactoryContext.ts index 6702cd07..744ffdd5 100644 --- a/src/Factory/FactoryContext.ts +++ b/src/Factory/FactoryContext.ts @@ -14,5 +14,8 @@ import { TransactionClientContract } from '@ioc:Adonis/Lucid/Database' export class FactoryContext implements FactoryContextContract { public faker = faker - constructor(public isStubbed: boolean, public $trx: TransactionClientContract | undefined) {} + constructor( + public isStubbed: boolean, + public $trx: TransactionClientContract | undefined + ) {} } diff --git a/src/Migrator/MigrationSource.ts b/src/Migrator/MigrationSource.ts index 621d3c87..d622e0d3 100644 --- a/src/Migrator/MigrationSource.ts +++ b/src/Migrator/MigrationSource.ts @@ -18,7 +18,10 @@ import { sourceFiles } from '../utils' * from disk for a given connection. */ export class MigrationSource { - constructor(private config: ConnectionConfig, private app: ApplicationContract) {} + constructor( + private config: ConnectionConfig, + private app: ApplicationContract + ) {} /** * Returns an array of files inside a given directory. Relative diff --git a/src/Orm/Relations/HasMany/SubQueryBuilder.ts b/src/Orm/Relations/HasMany/SubQueryBuilder.ts index 85d8bde3..8888e0c8 100644 --- a/src/Orm/Relations/HasMany/SubQueryBuilder.ts +++ b/src/Orm/Relations/HasMany/SubQueryBuilder.ts @@ -20,7 +20,11 @@ export class HasManySubQueryBuilder { protected appliedConstraints: boolean = false - constructor(builder: Knex.QueryBuilder, client: QueryClientContract, private relation: HasMany) { + constructor( + builder: Knex.QueryBuilder, + client: QueryClientContract, + private relation: HasMany + ) { super(builder, client, relation, (userFn) => { return ($builder) => { const subQuery = new HasManySubQueryBuilder($builder, this.client, this.relation) diff --git a/src/Orm/Relations/HasOne/SubQueryBuilder.ts b/src/Orm/Relations/HasOne/SubQueryBuilder.ts index 40c3efed..4593a9f4 100644 --- a/src/Orm/Relations/HasOne/SubQueryBuilder.ts +++ b/src/Orm/Relations/HasOne/SubQueryBuilder.ts @@ -20,7 +20,11 @@ export class HasOneSubQueryBuilder { protected appliedConstraints: boolean = false - constructor(builder: Knex.QueryBuilder, client: QueryClientContract, private relation: HasOne) { + constructor( + builder: Knex.QueryBuilder, + client: QueryClientContract, + private relation: HasOne + ) { super(builder, client, relation, (userFn) => { return ($builder) => { const subQuery = new HasOneSubQueryBuilder($builder, this.client, this.relation) diff --git a/src/Orm/Relations/KeysExtractor.ts b/src/Orm/Relations/KeysExtractor.ts index bdb2ac8c..70e7fbaa 100644 --- a/src/Orm/Relations/KeysExtractor.ts +++ b/src/Orm/Relations/KeysExtractor.ts @@ -15,7 +15,11 @@ import { LucidModel } from '@ioc:Adonis/Lucid/Orm' * and the relation model. */ export class KeysExtractor { - constructor(private model: LucidModel, private relationName: string, private keys: Keys) {} + constructor( + private model: LucidModel, + private relationName: string, + private keys: Keys + ) {} /** * Extract the defined keys from the models @@ -23,24 +27,27 @@ export class KeysExtractor { - const { key, model } = this.keys[extractKey] - const attribute = model.$getColumn(key) + return Object.keys(this.keys).reduce( + (result, extractKey: keyof Keys) => { + const { key, model } = this.keys[extractKey] + const attribute = model.$getColumn(key) - if (!attribute) { - throw new Exception( - `"${relationRef}" expects "${key}" to exist on "${model.name}" model, but is missing`, - 500, - 'E_MISSING_MODEL_ATTRIBUTE' - ) - } + if (!attribute) { + throw new Exception( + `"${relationRef}" expects "${key}" to exist on "${model.name}" model, but is missing`, + 500, + 'E_MISSING_MODEL_ATTRIBUTE' + ) + } - result[extractKey] = { - attributeName: key, - columnName: attribute.columnName, - } + result[extractKey] = { + attributeName: key, + columnName: attribute.columnName, + } - return result - }, {} as { [P in keyof Keys]: { attributeName: string; columnName: string } }) + return result + }, + {} as { [P in keyof Keys]: { attributeName: string; columnName: string } } + ) } } diff --git a/src/Orm/Relations/ManyToMany/QueryClient.ts b/src/Orm/Relations/ManyToMany/QueryClient.ts index 1e751479..f29468dc 100644 --- a/src/Orm/Relations/ManyToMany/QueryClient.ts +++ b/src/Orm/Relations/ManyToMany/QueryClient.ts @@ -388,10 +388,13 @@ export class ManyToManyQueryClient implements ManyToManyClientContract { - result[id] = {} - return result - }, {} as Record) + ? (ids as (string | number)[]).reduce( + (result, id) => { + result[id] = {} + return result + }, + {} as Record + ) : (ids as Record) const query = this.pivotQuery().useTransaction(transaction) diff --git a/src/Orm/NamingStrategies/SnakeCase.ts b/src/Orm/naming_strategies/snake_case.ts similarity index 79% rename from src/Orm/NamingStrategies/SnakeCase.ts rename to src/Orm/naming_strategies/snake_case.ts index bcda2252..4f671d6a 100644 --- a/src/Orm/NamingStrategies/SnakeCase.ts +++ b/src/Orm/naming_strategies/snake_case.ts @@ -7,8 +7,9 @@ * file that was distributed with this source code. */ -import { string } from '@poppinss/utils/build/helpers' -import { NamingStrategyContract, LucidModel, ModelRelations } from '@ioc:Adonis/Lucid/Orm' +import string from '@poppinss/utils/string' +import { ModelRelations } from '../../../adonis-typings/relations.js' +import { NamingStrategyContract, LucidModel } from '../../../adonis-typings/model.js' /** * Uses snake case as the naming strategy for different model properties @@ -17,28 +18,28 @@ export class SnakeCaseNamingStrategy implements NamingStrategyContract { /** * The default table name for the given model */ - public tableName(model: LucidModel): string { + tableName(model: LucidModel): string { return string.pluralize(string.snakeCase(model.name)) } /** * The database column name for a given model attribute */ - public columnName(_: LucidModel, attributeName: string): string { + columnName(_: LucidModel, attributeName: string): string { return string.snakeCase(attributeName) } /** * The post serialization name for a given model attribute */ - public serializedName(_: LucidModel, attributeName: string): string { + serializedName(_: LucidModel, attributeName: string): string { return string.snakeCase(attributeName) } /** * The local key for a given model relationship */ - public relationLocalKey( + relationLocalKey( relation: ModelRelations['__opaque_type'], model: LucidModel, relatedModel: LucidModel @@ -53,7 +54,7 @@ export class SnakeCaseNamingStrategy implements NamingStrategyContract { /** * The foreign key for a given model relationship */ - public relationForeignKey( + relationForeignKey( relation: ModelRelations['__opaque_type'], model: LucidModel, relatedModel: LucidModel @@ -68,21 +69,21 @@ export class SnakeCaseNamingStrategy implements NamingStrategyContract { /** * Pivot table name for many to many relationship */ - public relationPivotTable(_: 'manyToMany', model: LucidModel, relatedModel: LucidModel): string { + relationPivotTable(_: 'manyToMany', model: LucidModel, relatedModel: LucidModel): string { return string.snakeCase([relatedModel.name, model.name].sort().join('_')) } /** * Pivot foreign key for many to many relationship */ - public relationPivotForeignKey(_: 'manyToMany', model: LucidModel): string { + relationPivotForeignKey(_: 'manyToMany', model: LucidModel): string { return string.snakeCase(`${model.name}_${model.primaryKey}`) } /** * Keys for the pagination meta */ - public paginationMetaKeys(): { + paginationMetaKeys(): { total: string perPage: string currentPage: string diff --git a/src/SeedsRunner/SeedersSource.ts b/src/SeedsRunner/SeedersSource.ts index b44bd4c4..46aadbea 100644 --- a/src/SeedsRunner/SeedersSource.ts +++ b/src/SeedsRunner/SeedersSource.ts @@ -17,7 +17,10 @@ import { sourceFiles } from '../utils' * Seeders source exposes the API to read the seeders from disk for a given connection. */ export class SeedersSource { - constructor(private config: ConnectionConfig, private app: ApplicationContract) {} + constructor( + private config: ConnectionConfig, + private app: ApplicationContract + ) {} /** * Returns an array of files inside a given directory. Relative diff --git a/src/TestUtils/Migration.ts b/src/TestUtils/Migration.ts index 29b4fd81..3621d8e6 100644 --- a/src/TestUtils/Migration.ts +++ b/src/TestUtils/Migration.ts @@ -13,7 +13,10 @@ import type Ace from '@ioc:Adonis/Core/Ace' * Migrator class to be used for testing. */ export class TestsMigrator { - constructor(private ace: typeof Ace, private connectionName?: string) {} + constructor( + private ace: typeof Ace, + private connectionName?: string + ) {} private async runCommand(commandName: string) { const args: string[] = ['--compact-output'] diff --git a/src/TestUtils/Seeder.ts b/src/TestUtils/Seeder.ts index 229e0b5d..08fea7f3 100644 --- a/src/TestUtils/Seeder.ts +++ b/src/TestUtils/Seeder.ts @@ -13,7 +13,10 @@ import type Ace from '@ioc:Adonis/Core/Ace' * Seeder class to be used for testing */ export class TestsSeeder { - constructor(private ace: typeof Ace, private connectionName?: string) {} + constructor( + private ace: typeof Ace, + private connectionName?: string + ) {} private async runCommand(commandName: string) { const args: string[] = ['--compact-output'] diff --git a/src/TestUtils/Truncator.ts b/src/TestUtils/Truncator.ts index 6b3295d5..fe48bfc1 100644 --- a/src/TestUtils/Truncator.ts +++ b/src/TestUtils/Truncator.ts @@ -13,7 +13,10 @@ import type Ace from '@ioc:Adonis/Core/Ace' * Migrator class to be used for testing. */ export class TestsTruncator { - constructor(private ace: typeof Ace, private connectionName?: string) {} + constructor( + private ace: typeof Ace, + private connectionName?: string + ) {} private async runCommand(commandName: string, args: string[] = []) { if (this.connectionName) { diff --git a/src/Connection/index.ts b/src/connection/index.ts similarity index 85% rename from src/Connection/index.ts rename to src/connection/index.ts index 7d0ba2a7..b3fa9e68 100644 --- a/src/Connection/index.ts +++ b/src/connection/index.ts @@ -7,18 +7,17 @@ * file that was distributed with this source code. */ -/// - import { Pool } from 'tarn' import knex, { Knex } from 'knex' -import { EventEmitter } from 'events' +import { EventEmitter } from 'node:events' import { Exception } from '@poppinss/utils' import { patchKnex } from 'knex-dynamic-connection' -import { LoggerContract } from '@ioc:Adonis/Core/Logger' -import { resolveClientNameWithAliases } from 'knex/lib/util/helpers' -import { ConnectionConfig, ConnectionContract, ReportNode } from '@ioc:Adonis/Lucid/Database' +import type { Logger } from '@adonisjs/core/logger' +// @ts-expect-error +import { resolveClientNameWithAliases } from 'knex/lib/util/helpers.js' +import { ConnectionConfig, ConnectionContract, ReportNode } from '../../adonis-typings/database.js' -import { Logger } from './Logger' +import { Logger as ConnectionLogger } from './logger.js' /** * Connection class manages a given database connection. Internally it uses @@ -30,30 +29,24 @@ export class Connection extends EventEmitter implements ConnectionContract { * Reference to knex. The instance is created once the `open` * method is invoked */ - public client?: Knex + client?: Knex /** * Read client when read/write replicas are defined in the config, otherwise * it is a reference to the `client`. */ - public readClient?: Knex + readClient?: Knex /** * Connection dialect name */ - public dialectName: ConnectionContract['dialectName'] = resolveClientNameWithAliases( - this.config.client - ) + dialectName: ConnectionContract['dialectName'] /** * A boolean to know if connection operates on read/write * replicas */ - public hasReadWriteReplicas: boolean = !!( - this.config.replicas && - this.config.replicas.read && - this.config.replicas.write - ) + hasReadWriteReplicas: boolean /** * Config for one or more read replicas. Only exists, when replicas are @@ -67,12 +60,18 @@ export class Connection extends EventEmitter implements ConnectionContract { private roundRobinCounter = 0 constructor( - public readonly name: string, + public name: string, public config: ConnectionConfig, - private logger: LoggerContract + private logger: Logger ) { super() this.validateConfig() + this.dialectName = resolveClientNameWithAliases(this.config.client) + this.hasReadWriteReplicas = !!( + this.config.replicas && + this.config.replicas.read && + this.config.replicas.write + ) } /** @@ -82,19 +81,17 @@ export class Connection extends EventEmitter implements ConnectionContract { private validateConfig(): void { if (this.config.replicas) { if (!this.config.replicas.read || !this.config.replicas.write) { - throw new Exception( - 'Make sure to define read/write replicas or use connection property', - 500, - 'E_INCOMPLETE_REPLICAS_CONFIG' - ) + throw new Exception('Make sure to define read/write replicas or use connection property', { + code: 'E_INCOMPLETE_REPLICAS_CONFIG', + status: 500, + }) } if (!this.config.replicas.read.connection || !this.config.replicas.read.connection) { - throw new Exception( - 'Make sure to define connection property inside read/write replicas', - 500, - 'E_INVALID_REPLICAS_CONFIG' - ) + throw new Exception('Make sure to define connection property inside read/write replicas', { + status: 500, + code: 'E_INVALID_REPLICAS_CONFIG', + }) } } } @@ -233,11 +230,13 @@ export class Connection extends EventEmitter implements ConnectionContract { * Creates the write connection. */ private setupWriteConnection() { - this.client = knex( - Object.assign({ log: new Logger(this.name, this.logger) }, this.getWriteConfig(), { + this.client = knex.knex( + Object.assign({ log: new ConnectionLogger(this.name, this.logger) }, this.getWriteConfig(), { debug: false, }) ) + + // @ts-ignore patchKnex(this.client, this.writeConfigResolver.bind(this)) } @@ -252,11 +251,13 @@ export class Connection extends EventEmitter implements ConnectionContract { } this.logger.trace({ connection: this.name }, 'setting up read/write replicas') - this.readClient = knex( - Object.assign({ log: new Logger(this.name, this.logger) }, this.getReadConfig(), { + this.readClient = knex.knex( + Object.assign({ log: new ConnectionLogger(this.name, this.logger) }, this.getReadConfig(), { debug: false, }) ) + + // @ts-ignore patchKnex(this.readClient, this.readConfigResolver.bind(this)) } @@ -265,16 +266,20 @@ export class Connection extends EventEmitter implements ConnectionContract { * after first error. */ private async checkReadHosts() { - const configCopy = Object.assign({ log: new Logger(this.name, this.logger) }, this.config, { - debug: false, - }) + const configCopy = Object.assign( + { log: new ConnectionLogger(this.name, this.logger) }, + this.config, + { + debug: false, + } + ) let error: any = null // eslint-disable-next-line @typescript-eslint/naming-convention for (let _ of this.readReplicas) { configCopy.connection = this.readConfigResolver(this.config) this.logger.trace({ connection: this.name }, 'spawing health check read connection') - const client = knex(configCopy) + const client = knex.knex(configCopy) try { if (this.dialectName === 'oracledb') { @@ -321,7 +326,7 @@ export class Connection extends EventEmitter implements ConnectionContract { /** * Returns the pool instance for the given connection */ - public get pool(): null | Pool { + get pool(): null | Pool { return this.client ? this.client.client.pool : null } @@ -329,7 +334,7 @@ export class Connection extends EventEmitter implements ConnectionContract { * Returns the pool instance for the read connection. When replicas are * not in use, then read/write pools are same. */ - public get readPool(): null | Pool { + get readPool(): null | Pool { return this.readClient ? this.readClient.client.pool : null } @@ -337,14 +342,14 @@ export class Connection extends EventEmitter implements ConnectionContract { * Returns a boolean indicating if the connection is ready for making * database queries. If not, one must call `connect`. */ - public get ready(): boolean { + get ready(): boolean { return !!(this.client || this.readClient) } /** * Opens the connection by creating knex instance */ - public connect() { + connect() { try { this.setupWriteConnection() this.setupReadConnection() @@ -363,7 +368,7 @@ export class Connection extends EventEmitter implements ConnectionContract { * In case of error this method will emit `close:error` event followed * by the `close` event. */ - public async disconnect(): Promise { + async disconnect(): Promise { this.logger.trace({ connection: this.name }, 'destroying connection') /** @@ -393,7 +398,7 @@ export class Connection extends EventEmitter implements ConnectionContract { /** * Returns the healthcheck report for the connection */ - public async getReport(): Promise { + async getReport(): Promise { const error = await this.checkWriteHost() let readError: Error | undefined diff --git a/src/Connection/Logger.ts b/src/connection/logger.ts similarity index 64% rename from src/Connection/Logger.ts rename to src/connection/logger.ts index f5f94eb9..6622d360 100644 --- a/src/Connection/Logger.ts +++ b/src/connection/logger.ts @@ -7,31 +7,34 @@ * file that was distributed with this source code. */ -import { LoggerContract } from '@ioc:Adonis/Core/Logger' +import type { Logger as PinoLogger } from '@adonisjs/core/logger' /** * Custom knex logger that uses adonisjs logger under the * hood. */ export class Logger { - public warn = function (message: any) { + warn = function (this: Logger, message: any) { this.adonisLogger.warn(message) }.bind(this) - public error = function (message: any) { + error = function (this: Logger, message: any) { this.adonisLogger.error(message) }.bind(this) - public deprecate = function (message: any) { + deprecate = function (this: Logger, message: any) { this.adonisLogger.info(message) }.bind(this) - public debug = function (message: any) { + debug = function (this: Logger, message: any) { this.warn( '"debug" property inside config is depreciated. We recommend using "db:query" event for enrich logging' ) this.adonisLogger.debug(message) }.bind(this) - constructor(public name: string, public adonisLogger: LoggerContract) {} + constructor( + public name: string, + public adonisLogger: PinoLogger + ) {} } diff --git a/src/Connection/Manager.ts b/src/connection/manager.ts similarity index 84% rename from src/Connection/Manager.ts rename to src/connection/manager.ts index 738cac1d..88bde2f8 100644 --- a/src/Connection/Manager.ts +++ b/src/connection/manager.ts @@ -7,12 +7,9 @@ * file that was distributed with this source code. */ -/// - import { Exception } from '@poppinss/utils' -import { EmitterContract } from '@ioc:Adonis/Core/Event' -import { LoggerContract } from '@ioc:Adonis/Core/Logger' -import { HealthReportEntry } from '@ioc:Adonis/Core/HealthCheck' +import type { Emitter } from '@adonisjs/core/events' +import type { Logger } from '@adonisjs/core/logger' import { ReportNode, @@ -20,9 +17,9 @@ import { ConnectionConfig, ConnectionContract, ConnectionManagerContract, -} from '@ioc:Adonis/Lucid/Database' +} from '../../adonis-typings/database.js' -import { Connection } from './index' +import { Connection } from './index.js' /** * Connection manager job is to manage multiple named connections. You can add any number @@ -33,7 +30,7 @@ export class ConnectionManager implements ConnectionManagerContract { /** * List of managed connections */ - public connections: ConnectionManagerContract['connections'] = new Map() + connections: ConnectionManagerContract['connections'] = new Map() /** * Connections for which the config was patched. They must get removed @@ -41,7 +38,10 @@ export class ConnectionManager implements ConnectionManagerContract { */ private orphanConnections: Set = new Set() - constructor(private logger: LoggerContract, private emitter: EmitterContract) {} + constructor( + private logger: Logger, + private emitter: Emitter + ) {} /** * Handles disconnection of a connection @@ -103,7 +103,7 @@ export class ConnectionManager implements ConnectionManagerContract { * Add a named connection with it's configuration. Make sure to call `connect` * before using the connection to make database queries. */ - public add(connectionName: string, config: ConnectionConfig): void { + add(connectionName: string, config: ConnectionConfig): void { /** * Noop when connection already exists. If one wants to change the config, they * must release the old connection and add a new one @@ -123,14 +123,13 @@ export class ConnectionManager implements ConnectionManagerContract { /** * Connect to the database using config for a given named connection */ - public connect(connectionName: string): void { + connect(connectionName: string): void { const connection = this.connections.get(connectionName) if (!connection) { - throw new Exception( - `Cannot connect to unregistered connection ${connectionName}`, - 500, - 'E_UNMANAGED_DB_CONNECTION' - ) + throw new Exception(`Cannot connect to unregistered connection ${connectionName}`, { + code: 'E_UNMANAGED_DB_CONNECTION', + status: 500, + }) } /** @@ -151,7 +150,7 @@ export class ConnectionManager implements ConnectionManagerContract { /** * Patching the config */ - public patch(connectionName: string, config: ConnectionConfig): void { + patch(connectionName: string, config: ConnectionConfig): void { const connection = this.get(connectionName) /** @@ -188,7 +187,7 @@ export class ConnectionManager implements ConnectionManagerContract { /** * Returns the connection node for a given named connection */ - public get(connectionName: string): ConnectionNode | undefined { + get(connectionName: string): ConnectionNode | undefined { return this.connections.get(connectionName) } @@ -197,7 +196,7 @@ export class ConnectionManager implements ConnectionManagerContract { * a given named connection. This method doesn't tell if * connection is connected or not. */ - public has(connectionName: string): boolean { + has(connectionName: string): boolean { return this.connections.has(connectionName) } @@ -205,7 +204,7 @@ export class ConnectionManager implements ConnectionManagerContract { * Returns a boolean telling if connection has been established * with the database or not */ - public isConnected(connectionName: string): boolean { + isConnected(connectionName: string): boolean { if (!this.has(connectionName)) { return false } @@ -218,7 +217,7 @@ export class ConnectionManager implements ConnectionManagerContract { * Closes a given connection and can optionally release it from the * tracking list */ - public async close(connectionName: string, release: boolean = false): Promise { + async close(connectionName: string, release: boolean = false): Promise { if (this.isConnected(connectionName)) { const connection = this.get(connectionName)! await connection.connection!.disconnect() @@ -233,7 +232,7 @@ export class ConnectionManager implements ConnectionManagerContract { /** * Close all tracked connections */ - public async closeAll(release: boolean = false): Promise { + async closeAll(release: boolean = false): Promise { await Promise.all(Array.from(this.connections.keys()).map((name) => this.close(name, release))) } @@ -241,7 +240,7 @@ export class ConnectionManager implements ConnectionManagerContract { * Release a connection. This will disconnect the connection * and will delete it from internal list */ - public async release(connectionName: string): Promise { + async release(connectionName: string): Promise { if (this.isConnected(connectionName)) { await this.close(connectionName, true) } else { @@ -252,7 +251,7 @@ export class ConnectionManager implements ConnectionManagerContract { /** * Returns the report for all the connections marked for healthChecks. */ - public async report(): Promise { + async report(): Promise { const reports = await Promise.all( Array.from(this.connections.keys()) .filter((one) => this.get(one)!.config.healthCheck) diff --git a/src/Database/index.ts b/src/database/index.ts similarity index 72% rename from src/Database/index.ts rename to src/database/index.ts index 2a2c42b7..612d1be1 100644 --- a/src/Database/index.ts +++ b/src/database/index.ts @@ -7,86 +7,77 @@ * file that was distributed with this source code. */ -/// - -import { Macroable } from 'macroable' -import { EmitterContract } from '@ioc:Adonis/Core/Event' -import { LoggerContract } from '@ioc:Adonis/Core/Logger' -import { ProfilerContract } from '@ioc:Adonis/Core/Profiler' -import { Exception, ManagerConfigValidator } from '@poppinss/utils' +import { Exception } from '@poppinss/utils' +import Macroable from '@poppinss/macroable' +import type { Emitter } from '@adonisjs/core/events' +import type { Logger } from '@adonisjs/core/logger' import { DatabaseConfig, IsolationLevels, - DatabaseContract, QueryClientContract, DatabaseClientOptions, TransactionClientContract, ConnectionManagerContract, -} from '@ioc:Adonis/Lucid/Database' - -import { QueryClient } from '../QueryClient' -import { RawBuilder } from './StaticBuilder/Raw' -import { prettyPrint } from '../Helpers/prettyPrint' -import { ModelQueryBuilder } from '../Orm/QueryBuilder' -import { ConnectionManager } from '../Connection/Manager' -import { InsertQueryBuilder } from './QueryBuilder/Insert' -import { ReferenceBuilder } from './StaticBuilder/Reference' -import { SimplePaginator } from './Paginator/SimplePaginator' -import { DatabaseQueryBuilder } from './QueryBuilder/Database' +} from '../../adonis-typings/database.js' + +import { QueryClient } from '../query_client/index.js' +import { RawBuilder } from './static_builder/raw.js' +import { prettyPrint } from '../helpers/pretty_print.js' +import { ConnectionManager } from '../connection/manager.js' +import { InsertQueryBuilder } from './query_builder/insert.js' +import { ReferenceBuilder } from './static_builder/reference.js' +import { SimplePaginator } from './paginator/simple_paginator.js' +import { DatabaseQueryBuilder } from './query_builder/database.js' +// import { ModelQueryBuilder } from '../Orm/QueryBuilder/index.js' /** * Database class exposes the API to manage multiple connections and obtain an instance * of query/transaction clients. */ -export class Database extends Macroable implements DatabaseContract { - /** - * Required by macroable - */ - protected static macros = {} - protected static getters = {} - +export class Database extends Macroable { /** * Reference to self constructor. TypeScript sucks with "this.constructor" * https://github.com/microsoft/TypeScript/issues/4586 */ - public Database = Database + Database = Database /** * Reference to connections manager */ - public manager: ConnectionManagerContract + manager: ConnectionManagerContract /** * Primary connection name */ - public primaryConnectionName = this.config.connection + primaryConnectionName: string /** * Reference to query builders. We expose them, so that they can be * extended from outside using macros. */ - public DatabaseQueryBuilder = DatabaseQueryBuilder - public InsertQueryBuilder = InsertQueryBuilder - public ModelQueryBuilder = ModelQueryBuilder - public SimplePaginator = SimplePaginator + DatabaseQueryBuilder = DatabaseQueryBuilder + InsertQueryBuilder = InsertQueryBuilder + // ModelQueryBuilder = ModelQueryBuilder + SimplePaginator = SimplePaginator /** * A store of global transactions */ - public connectionGlobalTransactions: Map = new Map() - public hasHealthChecksEnabled = false - public prettyPrint = prettyPrint + connectionGlobalTransactions: Map = new Map() + hasHealthChecksEnabled = false + prettyPrint = prettyPrint constructor( private config: DatabaseConfig, - private logger: LoggerContract, - private profiler: ProfilerContract, - private emitter: EmitterContract + private logger: Logger, + private emitter: Emitter ) { super() - this.validateConfig() this.manager = new ConnectionManager(this.logger, this.emitter) + this.primaryConnectionName = this.config.connection + + this.validateConfig() this.registerConnections() this.findIfHealthChecksAreEnabled() } @@ -95,9 +86,9 @@ export class Database extends Macroable implements DatabaseContract { * Validate config at runtime */ private validateConfig() { - const validator = new ManagerConfigValidator(this.config, 'database', 'config/database') - validator.validateDefault('connection') - validator.validateList('connections', 'connection') + // const validator = new ManagerConfigValidator(this.config, 'database', 'config/database') + // validator.validateDefault('connection') + // validator.validateList('connections', 'connection') } /** @@ -129,27 +120,19 @@ export class Database extends Macroable implements DatabaseContract { /** * Returns the connection node from the connection manager */ - public getRawConnection(name: string) { + getRawConnection(name: string) { return this.manager.get(name) } /** * Returns the query client for a given connection */ - public connection( + connection( connection: string = this.primaryConnectionName, options?: DatabaseClientOptions ): QueryClientContract | TransactionClientContract { options = options || {} - /** - * Use default profiler, when no profiler is defined when obtaining - * the query client for a given connection. - */ - if (!options.profiler) { - options.profiler = this.profiler - } - /** * Connect is noop when already connected */ @@ -185,31 +168,27 @@ export class Database extends Macroable implements DatabaseContract { ? new QueryClient(options.mode, rawConnection, this.emitter) : new QueryClient('dual', rawConnection, this.emitter) - /** - * Passing profiler to the query client for profiling queries - */ - queryClient.profiler = options.profiler return queryClient } /** * Returns the knex query builder */ - public knexQuery() { + knexQuery() { return this.connection(this.primaryConnectionName).knexQuery() } /** * Returns the knex raw query builder */ - public knexRawQuery(sql: string, bindings?: any[]) { + knexRawQuery(sql: string, bindings?: any[]) { return this.connection(this.primaryConnectionName).knexRawQuery(sql, bindings) } /** * Returns query builder. Optionally one can define the mode as well */ - public query(options?: DatabaseClientOptions) { + query(options?: DatabaseClientOptions) { return this.connection(this.primaryConnectionName, options).query() } @@ -218,14 +197,14 @@ export class Database extends Macroable implements DatabaseContract { * hence it doesn't matter, since in both `dual` and `write` mode, * the `write` connection is always used. */ - public insertQuery(options?: DatabaseClientOptions) { + insertQuery(options?: DatabaseClientOptions) { return this.connection(this.primaryConnectionName, options).insertQuery() } /** * Returns a query builder instance for a given model. */ - public modelQuery(model: any, options?: DatabaseClientOptions) { + modelQuery(model: any, options?: DatabaseClientOptions) { return this.connection(this.primaryConnectionName, options).modelQuery(model) } @@ -234,7 +213,7 @@ export class Database extends Macroable implements DatabaseContract { * defined the `read/write` mode in which to execute the * query */ - public rawQuery(sql: string, bindings?: any, options?: DatabaseClientOptions) { + rawQuery(sql: string, bindings?: any, options?: DatabaseClientOptions) { return this.connection(this.primaryConnectionName, options).rawQuery(sql, bindings) } @@ -243,28 +222,28 @@ export class Database extends Macroable implements DatabaseContract { * cannot be executed. Use `rawQuery`, if you want to execute * queries raw queries. */ - public raw(sql: string, bindings?: any) { + raw(sql: string, bindings?: any) { return new RawBuilder(sql, bindings) } /** * Returns reference builder. */ - public ref(reference: string) { + ref(reference: string) { return new ReferenceBuilder(reference, this.connection().getReadClient().client) } /** * Returns instance of a query builder and selects the table */ - public from(table: any) { + from(table: any) { return this.connection().from(table) } /** * Returns insert query builder and selects the table */ - public table(table: any) { + table(table: any) { return this.connection().table(table) } @@ -272,7 +251,7 @@ export class Database extends Macroable implements DatabaseContract { * Returns a transaction instance on the default * connection */ - public transaction( + transaction( callback?: | { isolationLevel?: IsolationLevels } | ((trx: TransactionClientContract) => Promise), @@ -287,14 +266,14 @@ export class Database extends Macroable implements DatabaseContract { /** * Invokes `manager.report` */ - public report() { + report() { return this.manager.report() } /** * Begin a new global transaction */ - public async beginGlobalTransaction( + async beginGlobalTransaction( connectionName?: string, options?: Omit ) { @@ -332,7 +311,7 @@ export class Database extends Macroable implements DatabaseContract { /** * Commit an existing global transaction */ - public async commitGlobalTransaction(connectionName?: string) { + async commitGlobalTransaction(connectionName?: string) { connectionName = connectionName || this.primaryConnectionName const trx = this.connectionGlobalTransactions.get(connectionName) @@ -351,7 +330,7 @@ export class Database extends Macroable implements DatabaseContract { /** * Rollback an existing global transaction */ - public async rollbackGlobalTransaction(connectionName?: string) { + async rollbackGlobalTransaction(connectionName?: string) { connectionName = connectionName || this.primaryConnectionName const trx = this.connectionGlobalTransactions.get(connectionName) diff --git a/src/Database/Paginator/SimplePaginator.ts b/src/database/paginator/simple_paginator.ts similarity index 75% rename from src/Database/Paginator/SimplePaginator.ts rename to src/database/paginator/simple_paginator.ts index ce1f8f96..e313aaae 100644 --- a/src/Database/Paginator/SimplePaginator.ts +++ b/src/database/paginator/simple_paginator.ts @@ -8,9 +8,11 @@ */ import { stringify } from 'qs' -import { SimplePaginatorContract, SimplePaginatorMetaKeys } from '@ioc:Adonis/Lucid/Database' - -import { SnakeCaseNamingStrategy } from '../../Orm/NamingStrategies/SnakeCase' +import { + SimplePaginatorContract, + SimplePaginatorMetaKeys, +} from '../../../adonis-typings/querybuilder.js' +import { SnakeCaseNamingStrategy } from '../../Orm/naming_strategies/snake_case.js' /** * Simple paginator works with the data set provided by the standard @@ -24,30 +26,30 @@ export class SimplePaginator extends Array implements SimplePaginatorContract 0 + readonly hasTotal: boolean /** * The Last page number */ - public readonly lastPage: number = Math.max(Math.ceil(this.total / this.perPage), 1) + readonly lastPage: number /** * Find if there are more pages to come */ - public readonly hasMorePages: boolean = this.lastPage > this.currentPage + readonly hasMorePages: boolean /** * Find if there are enough results to be paginated or not */ - public readonly hasPages: boolean = this.lastPage !== 1 + readonly hasPages: boolean constructor( private totalNumber: number, - public readonly perPage: number, - public readonly currentPage: number, + public perPage: number, + public currentPage: number, ...rows: any[] ) { super(...rows) this.rows = rows this.isEmpty = this.rows.length === 0 + + this.total = Number(this.totalNumber) + this.hasTotal = this.total > 0 + this.lastPage = Math.max(Math.ceil(this.total / this.perPage), 1) + this.hasPages = this.lastPage !== 1 + this.hasMorePages = this.lastPage > this.currentPage } /** * A reference to the result rows */ - public all() { + all() { return this.rows } /** * Returns JSON meta data */ - public getMeta(): any { + getMeta(): any { const metaKeys = this.namingStrategy.paginationMetaKeys() return { @@ -114,7 +122,7 @@ export class SimplePaginator extends Array implements SimplePaginatorContract 1) { return this.getUrl(this.currentPage - 1) } @@ -170,7 +178,7 @@ export class SimplePaginator extends Array implements SimplePaginatorContract - import { Knex } from 'knex' -import { Macroable } from 'macroable' +import Macroable from '@poppinss/macroable' import { Exception } from '@poppinss/utils' -import { ChainableContract, DBQueryCallback } from '@ioc:Adonis/Lucid/Database' +import { ChainableContract, DBQueryCallback } from '../../../adonis-typings/querybuilder.js' -import { isObject } from '../../utils' -import { RawQueryBuilder } from './Raw' -import { RawBuilder } from '../StaticBuilder/Raw' -import { ReferenceBuilder } from '../StaticBuilder/Reference' +import { isObject } from '../../utils/index.js' +import { RawQueryBuilder } from './raw.js' +import { RawBuilder } from '../static_builder/raw.js' +import { ReferenceBuilder } from '../static_builder/reference.js' const WRAPPING_METHODS = ['where', 'orWhere', 'whereNot', 'orWhereNot'] @@ -29,9 +27,9 @@ const WRAPPING_METHODS = ['where', 'orWhere', 'whereNot', 'orWhereNot'] * different API. */ export abstract class Chainable extends Macroable implements ChainableContract { - public hasAggregates: boolean = false - public hasGroupBy: boolean = false - public hasUnion: boolean = false + hasAggregates: boolean = false + hasGroupBy: boolean = false + hasUnion: boolean = false /** * Collection where clauses in a 2nd array. Calling `wrapExisting` @@ -78,7 +76,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { if (this.whereStack.length === 1) { this.whereStack[0].forEach(({ method, args }) => { - this.knexQuery[method](...args) + ;(this.knexQuery as any)[method](...args) }) return } @@ -86,7 +84,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { this.whereStack.forEach((collection) => { const firstItem = collection.shift() const wrapper = this.getWrappingMethod(firstItem.method) - this.knexQuery[wrapper.wrappingMethod]((subquery) => { + ;(this.knexQuery as any)[wrapper.wrappingMethod]((subquery: any) => { subquery[wrapper.method](...firstItem.args) collection.forEach(({ method, args }) => subquery[method](...args)) }) @@ -96,10 +94,10 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * An array of selected columns */ - public get columns(): ChainableContract['columns'] { - return this.knexQuery['_statements'] - .filter(({ grouping }) => grouping === 'columns') - .reduce((result: ChainableContract['columns'], { value }) => { + get columns(): ChainableContract['columns'] { + return (this.knexQuery as any)['_statements'] + .filter(({ grouping }: any) => grouping === 'columns') + .reduce((result: ChainableContract['columns'], { value }: any) => { result = result.concat(value) return result }, []) @@ -109,7 +107,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * Custom alias for the query results. Ignored if it not a * subquery */ - public subQueryAlias?: string + subQueryAlias?: string constructor( public knexQuery: Knex.QueryBuilder, @@ -147,7 +145,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ private normalizeAggregateColumns(columns: any, alias?: any): any { if (columns.constructor === Object) { - return Object.keys(columns).reduce((result, key) => { + return Object.keys(columns).reduce((result: any, key) => { const value = columns[key] result[key] = typeof value === 'string' ? this.resolveKey(value) : this.transformValue(value) @@ -203,7 +201,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * If check for objects is enabled, then resolve object keys */ if (checkForObject && isObject(columns)) { - return Object.keys(columns).reduce((result, column) => { + return Object.keys(columns).reduce((result: any, column) => { result[this.keysResolver!(column)] = columns[column] return result }, {}) @@ -286,7 +284,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Define columns for selection */ - public select(...args: any[]): this { + select(...args: any[]): this { let columns = args if (Array.isArray(args[0])) { columns = args[0] @@ -307,7 +305,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * Select table for the query. Re-calling this method multiple times will * use the last selected table */ - public from(table: any): this { + from(table: any): this { this.knexQuery.from(this.transformValue(table)) return this } @@ -315,7 +313,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Wrap existing where clauses to its own group */ - public wrapExisting(): this { + wrapExisting(): this { if (this.getRecentStackItem().length) { this.whereStack.push([]) } @@ -325,7 +323,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Add a `where` clause */ - public where(key: any, operator?: any, value?: any): this { + where(key: any, operator?: any, value?: any): this { const whereClauses = this.getRecentStackItem() if (value !== undefined) { @@ -356,7 +354,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Add a `or where` clause */ - public orWhere(key: any, operator?: any, value?: any): this { + orWhere(key: any, operator?: any, value?: any): this { const whereClauses = this.getRecentStackItem() if (value !== undefined) { @@ -383,14 +381,14 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Alias for `where` */ - public andWhere(key: any, operator?: any, value?: any): this { + andWhere(key: any, operator?: any, value?: any): this { return this.where(key, operator, value) } /** * Adding `where not` clause */ - public whereNot(key: any, operator?: any, value?: any): this { + whereNot(key: any, operator?: any, value?: any): this { const whereClauses = this.getRecentStackItem() if (value !== undefined) { @@ -417,7 +415,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Adding `or where not` clause */ - public orWhereNot(key: any, operator?: any, value?: any): this { + orWhereNot(key: any, operator?: any, value?: any): this { const whereClauses = this.getRecentStackItem() if (value !== undefined) { @@ -444,14 +442,14 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Alias for [[whereNot]] */ - public andWhereNot(key: any, operator?: any, value?: any): this { + andWhereNot(key: any, operator?: any, value?: any): this { return this.whereNot(key, operator, value) } /** * Add a where clause on a given column */ - public whereColumn(column: any, operator: any, comparisonColumn?: any): this { + whereColumn(column: any, operator: any, comparisonColumn?: any): this { if (comparisonColumn !== undefined) { this.where(column, operator, new ReferenceBuilder(comparisonColumn, this.knexQuery.client)) } else { @@ -463,7 +461,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Add a orWhere clause on a given column */ - public orWhereColumn(column: any, operator: any, comparisonColumn?: any): this { + orWhereColumn(column: any, operator: any, comparisonColumn?: any): this { if (comparisonColumn !== undefined) { this.orWhere(column, operator, new ReferenceBuilder(comparisonColumn, this.knexQuery.client)) } else { @@ -475,14 +473,14 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Alias for whereColumn */ - public andWhereColumn(column: any, operator: any, comparisonColumn?: any): this { + andWhereColumn(column: any, operator: any, comparisonColumn?: any): this { return this.whereColumn(column, operator, comparisonColumn) } /** * Add a whereNot clause on a given column */ - public whereNotColumn(column: any, operator: any, comparisonColumn?: any): this { + whereNotColumn(column: any, operator: any, comparisonColumn?: any): this { if (comparisonColumn !== undefined) { this.whereNot(column, operator, new ReferenceBuilder(comparisonColumn, this.knexQuery.client)) } else { @@ -494,7 +492,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Add a orWhereNotColumn clause on a given column */ - public orWhereNotColumn(column: any, operator: any, comparisonColumn?: any): this { + orWhereNotColumn(column: any, operator: any, comparisonColumn?: any): this { if (comparisonColumn !== undefined) { this.orWhereNot( column, @@ -510,14 +508,14 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Alias for whereNotColumn */ - public andWhereNotColumn(column: any, operator: any, comparisonColumn?: any): this { + andWhereNotColumn(column: any, operator: any, comparisonColumn?: any): this { return this.whereNotColumn(column, operator, comparisonColumn) } /** * Adding a `where in` clause */ - public whereIn(columns: any, value: any): this { + whereIn(columns: any, value: any): this { value = Array.isArray(value) ? value.map((one) => this.transformValue(one)) : this.transformValue(value) @@ -537,7 +535,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Adding a `or where in` clause */ - public orWhereIn(columns: any, value: any): this { + orWhereIn(columns: any, value: any): this { value = Array.isArray(value) ? value.map((one) => this.transformValue(one)) : this.transformValue(value) @@ -557,14 +555,14 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Alias for [[whereIn]] */ - public andWhereIn(key: any, value: any): this { + andWhereIn(key: any, value: any): this { return this.whereIn(key, value) } /** * Adding a `where not in` clause */ - public whereNotIn(columns: any, value: any): this { + whereNotIn(columns: any, value: any): this { value = Array.isArray(value) ? value.map((one) => this.transformValue(one)) : this.transformValue(value) @@ -584,7 +582,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Adding a `or where not in` clause */ - public orWhereNotIn(columns: any, value: any): this { + orWhereNotIn(columns: any, value: any): this { value = Array.isArray(value) ? value.map((one) => this.transformValue(one)) : this.transformValue(value) @@ -604,14 +602,14 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Alias for [[whereNotIn]] */ - public andWhereNotIn(key: any, value: any): this { + andWhereNotIn(key: any, value: any): this { return this.whereNotIn(key, value) } /** * Adding `where not null` clause */ - public whereNull(key: any): this { + whereNull(key: any): this { const whereClauses = this.getRecentStackItem() whereClauses.push({ method: 'whereNull', @@ -623,7 +621,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Adding `or where not null` clause */ - public orWhereNull(key: any): this { + orWhereNull(key: any): this { const whereClauses = this.getRecentStackItem() whereClauses.push({ method: 'orWhereNull', @@ -635,14 +633,14 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Alias for [[whereNull]] */ - public andWhereNull(key: any): this { + andWhereNull(key: any): this { return this.whereNull(key) } /** * Adding `where not null` clause */ - public whereNotNull(key: any): this { + whereNotNull(key: any): this { const whereClauses = this.getRecentStackItem() whereClauses.push({ method: 'whereNotNull', @@ -654,7 +652,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Adding `or where not null` clause */ - public orWhereNotNull(key: any): this { + orWhereNotNull(key: any): this { const whereClauses = this.getRecentStackItem() whereClauses.push({ method: 'orWhereNotNull', @@ -666,14 +664,14 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Alias for [[whereNotNull]] */ - public andWhereNotNull(key: any): this { + andWhereNotNull(key: any): this { return this.whereNotNull(key) } /** * Add a `where exists` clause */ - public whereExists(value: any) { + whereExists(value: any) { const whereClauses = this.getRecentStackItem() whereClauses.push({ method: 'whereExists', @@ -685,7 +683,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Add a `or where exists` clause */ - public orWhereExists(value: any) { + orWhereExists(value: any) { const whereClauses = this.getRecentStackItem() whereClauses.push({ method: 'orWhereExists', @@ -697,14 +695,14 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Alias for [[whereExists]] */ - public andWhereExists(value: any) { + andWhereExists(value: any) { return this.whereExists(value) } /** * Add a `where not exists` clause */ - public whereNotExists(value: any) { + whereNotExists(value: any) { const whereClauses = this.getRecentStackItem() whereClauses.push({ method: 'whereNotExists', @@ -716,7 +714,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Add a `or where not exists` clause */ - public orWhereNotExists(value: any) { + orWhereNotExists(value: any) { const whereClauses = this.getRecentStackItem() whereClauses.push({ method: 'orWhereNotExists', @@ -728,14 +726,14 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Alias for [[whereNotExists]] */ - public andWhereNotExists(value: any) { + andWhereNotExists(value: any) { return this.whereNotExists(value) } /** * Add where between clause */ - public whereBetween(key: any, value: [any, any]): this { + whereBetween(key: any, value: [any, any]): this { const whereClauses = this.getRecentStackItem() whereClauses.push({ method: 'whereBetween', @@ -747,7 +745,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Add where between clause */ - public orWhereBetween(key: any, value: any): this { + orWhereBetween(key: any, value: any): this { const whereClauses = this.getRecentStackItem() whereClauses.push({ method: 'orWhereBetween', @@ -759,14 +757,14 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Alias for [[whereBetween]] */ - public andWhereBetween(key: any, value: any): this { + andWhereBetween(key: any, value: any): this { return this.whereBetween(key, value) } /** * Add where between clause */ - public whereNotBetween(key: any, value: any): this { + whereNotBetween(key: any, value: any): this { const whereClauses = this.getRecentStackItem() whereClauses.push({ method: 'whereNotBetween', @@ -778,7 +776,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Add where between clause */ - public orWhereNotBetween(key: any, value: any): this { + orWhereNotBetween(key: any, value: any): this { const whereClauses = this.getRecentStackItem() whereClauses.push({ method: 'orWhereNotBetween', @@ -790,14 +788,14 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Alias for [[whereNotBetween]] */ - public andWhereNotBetween(key: any, value: any): this { + andWhereNotBetween(key: any, value: any): this { return this.whereNotBetween(key, value) } /** * Adding a where clause using raw sql */ - public whereRaw(sql: any, bindings?: any): this { + whereRaw(sql: any, bindings?: any): this { const whereClauses = this.getRecentStackItem() if (bindings) { @@ -822,7 +820,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Adding a or where clause using raw sql */ - public orWhereRaw(sql: any, bindings?: any): this { + orWhereRaw(sql: any, bindings?: any): this { const whereClauses = this.getRecentStackItem() if (bindings) { @@ -846,14 +844,14 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Alias for [[whereRaw]] */ - public andWhereRaw(sql: any, bindings?: any): this { + andWhereRaw(sql: any, bindings?: any): this { return this.whereRaw(sql, bindings) } /** * Add a `where like` clause */ - public whereLike(key: any, value: any): this { + whereLike(key: any, value: any): this { const whereClauses = this.getRecentStackItem() whereClauses.push({ @@ -867,7 +865,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Add a `where like` clause */ - public orWhereLike(key: any, value?: any): this { + orWhereLike(key: any, value?: any): this { const whereClauses = this.getRecentStackItem() whereClauses.push({ @@ -881,14 +879,14 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Add a `where like` clause */ - public andWhereLike(key: any, value?: any): this { + andWhereLike(key: any, value?: any): this { return this.whereLike(key, value) } /** * Add a `where like` clause */ - public whereILike(key: any, value?: any): this { + whereILike(key: any, value?: any): this { const whereClauses = this.getRecentStackItem() whereClauses.push({ @@ -902,7 +900,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Add a `where like` clause */ - public orWhereILike(key: any, value?: any): this { + orWhereILike(key: any, value?: any): this { const whereClauses = this.getRecentStackItem() whereClauses.push({ @@ -916,14 +914,14 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Add a `where like` clause */ - public andWhereILike(key: any, value?: any): this { + andWhereILike(key: any, value?: any): this { return this.whereILike(key, value) } /** * Define a where clause with value that matches for JSON */ - public whereJson(column: string, value: any) { + whereJson(column: string, value: any) { const whereClauses = this.getRecentStackItem() whereClauses.push({ @@ -937,7 +935,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Define a or where clause with value that matches for JSON */ - public orWhereJson(column: string, value: any) { + orWhereJson(column: string, value: any) { const whereClauses = this.getRecentStackItem() whereClauses.push({ @@ -953,14 +951,14 @@ export abstract class Chainable extends Macroable implements ChainableContract { * * @alias whereJson */ - public andWhereJson(column: string, value: any) { + andWhereJson(column: string, value: any) { return this.whereJson(column, value) } /** * Define a where clause with value that matches for JSON */ - public whereNotJson(column: string, value: any) { + whereNotJson(column: string, value: any) { const whereClauses = this.getRecentStackItem() whereClauses.push({ @@ -974,7 +972,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Define a or where clause with value that matches for JSON */ - public orWhereNotJson(column: string, value: any) { + orWhereNotJson(column: string, value: any) { const whereClauses = this.getRecentStackItem() whereClauses.push({ @@ -990,7 +988,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * * @alias whereNotJson */ - public andWhereNotJson(column: string, value: any) { + andWhereNotJson(column: string, value: any) { return this.whereNotJson(column, value) } @@ -998,7 +996,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * Define a where clause with value that matches for a superset of * JSON */ - public whereJsonSuperset(column: string, value: any) { + whereJsonSuperset(column: string, value: any) { const whereClauses = this.getRecentStackItem() whereClauses.push({ @@ -1013,7 +1011,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * Define a or where clause with value that matches for a superset of * JSON */ - public orWhereJsonSuperset(column: string, value: any) { + orWhereJsonSuperset(column: string, value: any) { const whereClauses = this.getRecentStackItem() whereClauses.push({ @@ -1030,7 +1028,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * * @alias whereJsonSuperset */ - public andWhereJsonSuperset(column: string, value: any) { + andWhereJsonSuperset(column: string, value: any) { return this.whereJsonSuperset(column, value) } @@ -1038,7 +1036,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * Define a where clause with value that matches for a superset of * JSON */ - public whereNotJsonSuperset(column: string, value: any) { + whereNotJsonSuperset(column: string, value: any) { const whereClauses = this.getRecentStackItem() whereClauses.push({ @@ -1053,7 +1051,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * Define a or where clause with value that matches for a superset of * JSON */ - public orWhereNotJsonSuperset(column: string, value: any) { + orWhereNotJsonSuperset(column: string, value: any) { const whereClauses = this.getRecentStackItem() whereClauses.push({ @@ -1070,7 +1068,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * * @alias whereNotJsonSuperset */ - public andWhereNotJsonSuperset(column: string, value: any) { + andWhereNotJsonSuperset(column: string, value: any) { return this.whereNotJsonSuperset(column, value) } @@ -1078,7 +1076,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * Define a where clause with value that matches for a subset of * JSON */ - public whereJsonSubset(column: string, value: any) { + whereJsonSubset(column: string, value: any) { const whereClauses = this.getRecentStackItem() whereClauses.push({ @@ -1093,7 +1091,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * Define a or where clause with value that matches for a subset of * JSON */ - public orWhereJsonSubset(column: string, value: any) { + orWhereJsonSubset(column: string, value: any) { const whereClauses = this.getRecentStackItem() whereClauses.push({ @@ -1110,7 +1108,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * * @alias whereJsonSubset */ - public andWhereJsonSubset(column: string, value: any) { + andWhereJsonSubset(column: string, value: any) { return this.whereJsonSubset(column, value) } @@ -1118,7 +1116,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * Define a where clause with value that matches for a subset of * JSON */ - public whereNotJsonSubset(column: string, value: any) { + whereNotJsonSubset(column: string, value: any) { const whereClauses = this.getRecentStackItem() whereClauses.push({ @@ -1133,7 +1131,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * Define a or where clause with value that matches for a subset of * JSON */ - public orWhereNotJsonSubset(column: string, value: any) { + orWhereNotJsonSubset(column: string, value: any) { const whereClauses = this.getRecentStackItem() whereClauses.push({ @@ -1150,7 +1148,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * * @alias whereNotJsonSubset */ - public andWhereNotJsonSubset(column: string, value: any) { + andWhereNotJsonSubset(column: string, value: any) { return this.whereNotJsonSubset(column, value) } @@ -1158,7 +1156,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * Adds a where clause with comparison of a value returned * by a JsonPath given an operator and a value. */ - public whereJsonPath(column: string, jsonPath: string, operator: any, value?: any): this { + whereJsonPath(column: string, jsonPath: string, operator: any, value?: any): this { const whereClauses = this.getRecentStackItem() if (!value) { value = operator @@ -1177,7 +1175,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * Adds a or where clause with comparison of a value returned * by a JsonPath given an operator and a value. */ - public orWhereJsonPath(column: string, jsonPath: string, operator: any, value?: any): this { + orWhereJsonPath(column: string, jsonPath: string, operator: any, value?: any): this { const whereClauses = this.getRecentStackItem() if (!value) { value = operator @@ -1198,14 +1196,14 @@ export abstract class Chainable extends Macroable implements ChainableContract { * * @alias whereJsonPath */ - public andWhereJsonPath(column: string, jsonPath: string, operator: any, value?: any): this { + andWhereJsonPath(column: string, jsonPath: string, operator: any, value?: any): this { return this.whereJsonPath(column, jsonPath, operator, value) } /** * Add a join clause */ - public join(table: any, first: any, operator?: any, second?: any): this { + join(table: any, first: any, operator?: any, second?: any): this { if (second !== undefined) { this.knexQuery.join(table, first, operator, this.transformRaw(second)) } else if (operator !== undefined) { @@ -1220,7 +1218,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Add an inner join clause */ - public innerJoin(table: any, first: any, operator?: any, second?: any): this { + innerJoin(table: any, first: any, operator?: any, second?: any): this { if (second !== undefined) { this.knexQuery.innerJoin(table, first, operator, this.transformRaw(second)) } else if (operator !== undefined) { @@ -1235,7 +1233,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Add a left join clause */ - public leftJoin(table: any, first: any, operator?: any, second?: any): this { + leftJoin(table: any, first: any, operator?: any, second?: any): this { if (second !== undefined) { this.knexQuery.leftJoin(table, first, operator, this.transformRaw(second)) } else if (operator !== undefined) { @@ -1250,7 +1248,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Add a left outer join clause */ - public leftOuterJoin(table: any, first: any, operator?: any, second?: any): this { + leftOuterJoin(table: any, first: any, operator?: any, second?: any): this { if (second !== undefined) { this.knexQuery.leftOuterJoin(table, first, operator, this.transformRaw(second)) } else if (operator !== undefined) { @@ -1265,7 +1263,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Add a right join clause */ - public rightJoin(table: any, first: any, operator?: any, second?: any): this { + rightJoin(table: any, first: any, operator?: any, second?: any): this { if (second !== undefined) { this.knexQuery.rightJoin(table, first, operator, this.transformRaw(second)) } else if (operator !== undefined) { @@ -1280,7 +1278,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Add a right outer join clause */ - public rightOuterJoin(table: any, first: any, operator?: any, second?: any): this { + rightOuterJoin(table: any, first: any, operator?: any, second?: any): this { if (second !== undefined) { this.knexQuery.rightOuterJoin(table, first, operator, this.transformRaw(second)) } else if (operator !== undefined) { @@ -1295,7 +1293,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Add a full outer join clause */ - public fullOuterJoin(table: any, first: any, operator?: any, second?: any): this { + fullOuterJoin(table: any, first: any, operator?: any, second?: any): this { if (second !== undefined) { this.knexQuery.fullOuterJoin(table, first, operator, this.transformRaw(second)) } else if (operator !== undefined) { @@ -1310,7 +1308,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Add a cross join clause */ - public crossJoin(table: any, first: any, operator?: any, second?: any): this { + crossJoin(table: any, first: any, operator?: any, second?: any): this { if (second !== undefined) { this.knexQuery.crossJoin(table, first, operator, this.transformRaw(second)) } else if (operator !== undefined) { @@ -1325,7 +1323,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Add join clause as a raw query */ - public joinRaw(sql: any, bindings?: any) { + joinRaw(sql: any, bindings?: any) { if (bindings) { this.knexQuery.joinRaw(sql, bindings) } else { @@ -1341,7 +1339,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * being referred within `having` clause. The end user has to * use raw queries in this case. */ - public having(key: any, operator?: any, value?: any): this { + having(key: any, operator?: any, value?: any): this { if (value !== undefined) { this.knexQuery.having(this.resolveColumn(key), operator, this.transformValue(value)) return this @@ -1363,7 +1361,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * being referred within `having` clause. The end user has to * use raw queries in this case. */ - public orHaving(key: any, operator?: any, value?: any): this { + orHaving(key: any, operator?: any, value?: any): this { if (value !== undefined) { this.knexQuery.orHaving(this.resolveColumn(key), operator, this.transformValue(value)) return this @@ -1382,14 +1380,14 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Alias for [[having]] */ - public andHaving(key: any, operator?: any, value?: any): this { + andHaving(key: any, operator?: any, value?: any): this { return this.having(key, operator, value) } /** * Adding having in clause to the query */ - public havingIn(key: any, value: any): this { + havingIn(key: any, value: any): this { value = Array.isArray(value) ? value.map((one) => this.transformValue(one)) : this.transformValue(value) @@ -1401,26 +1399,25 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Adding or having in clause to the query */ - public orHavingIn(key: any, value: any): this { + orHavingIn(key: any, value: any): this { value = Array.isArray(value) ? value.map((one) => this.transformValue(one)) : this.transformValue(value) - - this.knexQuery['orHavingIn'](this.resolveColumn(key), value) + ;(this.knexQuery as any)['orHavingIn'](this.resolveColumn(key), value) return this } /** * Alias for [[havingIn]] */ - public andHavingIn(key: any, value: any) { + andHavingIn(key: any, value: any) { return this.havingIn(key, value) } /** * Adding having not in clause to the query */ - public havingNotIn(key: any, value: any): this { + havingNotIn(key: any, value: any): this { value = Array.isArray(value) ? value.map((one) => this.transformValue(one)) : this.transformValue(value) @@ -1432,7 +1429,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Adding or having not in clause to the query */ - public orHavingNotIn(key: any, value: any): this { + orHavingNotIn(key: any, value: any): this { value = Array.isArray(value) ? value.map((one) => this.transformValue(one)) : this.transformValue(value) @@ -1444,14 +1441,14 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Alias for [[havingNotIn]] */ - public andHavingNotIn(key: any, value: any) { + andHavingNotIn(key: any, value: any) { return this.havingNotIn(key, value) } /** * Adding having null clause */ - public havingNull(key: any): this { + havingNull(key: any): this { this.knexQuery['havingNull'](this.resolveColumn(key)) return this } @@ -1459,22 +1456,22 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Adding or having null clause */ - public orHavingNull(key: any): this { - this.knexQuery['orHavingNull'](this.resolveColumn(key)) + orHavingNull(key: any): this { + ;(this.knexQuery as any)['orHavingNull'](this.resolveColumn(key)) return this } /** * Alias for [[havingNull]] clause */ - public andHavingNull(key: any): this { + andHavingNull(key: any): this { return this.havingNull(key) } /** * Adding having not null clause */ - public havingNotNull(key: any): this { + havingNotNull(key: any): this { this.knexQuery['havingNotNull'](this.resolveColumn(key)) return this } @@ -1482,68 +1479,68 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Adding or having not null clause */ - public orHavingNotNull(key: any): this { - this.knexQuery['orHavingNotNull'](this.resolveColumn(key)) + orHavingNotNull(key: any): this { + ;(this.knexQuery as any)['orHavingNotNull'](this.resolveColumn(key)) return this } /** * Alias for [[havingNotNull]] clause */ - public andHavingNotNull(key: any): this { + andHavingNotNull(key: any): this { return this.havingNotNull(key) } /** * Adding `having exists` clause */ - public havingExists(value: any): this { - this.knexQuery['havingExists'](this.transformValue(value)) + havingExists(value: any): this { + ;(this.knexQuery as any)['havingExists'](this.transformValue(value)) return this } /** * Adding `or having exists` clause */ - public orHavingExists(value: any): this { - this.knexQuery['orHavingExists'](this.transformValue(value)) + orHavingExists(value: any): this { + ;(this.knexQuery as any)['orHavingExists'](this.transformValue(value)) return this } /** * Alias for [[havingExists]] */ - public andHavingExists(value: any): this { + andHavingExists(value: any): this { return this.havingExists(value) } /** * Adding `having not exists` clause */ - public havingNotExists(value: any): this { - this.knexQuery['havingNotExists'](this.transformValue(value)) + havingNotExists(value: any): this { + ;(this.knexQuery as any)['havingNotExists'](this.transformValue(value)) return this } /** * Adding `or having not exists` clause */ - public orHavingNotExists(value: any): this { - this.knexQuery['orHavingNotExists'](this.transformValue(value)) + orHavingNotExists(value: any): this { + ;(this.knexQuery as any)['orHavingNotExists'](this.transformValue(value)) return this } /** * Alias for [[havingNotExists]] */ - public andHavingNotExists(value: any): this { + andHavingNotExists(value: any): this { return this.havingNotExists(value) } /** * Adding `having between` clause */ - public havingBetween(key: any, value: any): this { + havingBetween(key: any, value: any): this { this.knexQuery.havingBetween(this.resolveColumn(key), this.getBetweenPair(value)) return this } @@ -1551,7 +1548,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Adding `or having between` clause */ - public orHavingBetween(key: any, value: any): this { + orHavingBetween(key: any, value: any): this { this.knexQuery.orHavingBetween(this.resolveColumn(key), this.getBetweenPair(value)) return this } @@ -1559,14 +1556,14 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Alias for [[havingBetween]] */ - public andHavingBetween(key: any, value: any): this { + andHavingBetween(key: any, value: any): this { return this.havingBetween(this.resolveColumn(key), value) } /** * Adding `having not between` clause */ - public havingNotBetween(key: any, value: any): this { + havingNotBetween(key: any, value: any): this { this.knexQuery.havingNotBetween(this.resolveColumn(key), this.getBetweenPair(value)) return this } @@ -1574,7 +1571,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Adding `or having not between` clause */ - public orHavingNotBetween(key: any, value: any): this { + orHavingNotBetween(key: any, value: any): this { this.knexQuery.orHavingNotBetween(this.resolveColumn(key), this.getBetweenPair(value)) return this } @@ -1582,14 +1579,14 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Alias for [[havingNotBetween]] */ - public andHavingNotBetween(key: any, value: any): this { + andHavingNotBetween(key: any, value: any): this { return this.havingNotBetween(key, value) } /** * Adding a where clause using raw sql */ - public havingRaw(sql: any, bindings?: any): this { + havingRaw(sql: any, bindings?: any): this { if (bindings) { this.knexQuery.havingRaw(sql, bindings) } else { @@ -1602,7 +1599,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Adding a where clause using raw sql */ - public orHavingRaw(sql: any, bindings?: any): this { + orHavingRaw(sql: any, bindings?: any): this { if (bindings) { this.knexQuery.orHavingRaw(sql, bindings) } else { @@ -1615,14 +1612,14 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Alias for [[havingRaw]] */ - public andHavingRaw(sql: any, bindings?: any): this { + andHavingRaw(sql: any, bindings?: any): this { return this.havingRaw(sql, bindings) } /** * Add distinct clause */ - public distinct(...columns: any[]): this { + distinct(...columns: any[]): this { this.knexQuery.distinct(...columns.map((column) => this.resolveKey(column))) return this } @@ -1630,7 +1627,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Add distinctOn clause */ - public distinctOn(...columns: any[]): this { + distinctOn(...columns: any[]): this { this.knexQuery.distinctOn(...columns.map((column) => this.resolveKey(column))) return this } @@ -1638,7 +1635,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Add group by clause */ - public groupBy(...columns: any[]): this { + groupBy(...columns: any[]): this { this.hasGroupBy = true this.knexQuery.groupBy(...columns.map((column) => this.resolveKey(column))) return this @@ -1647,7 +1644,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Add group by clause as a raw query */ - public groupByRaw(sql: any, bindings?: any): this { + groupByRaw(sql: any, bindings?: any): this { this.hasGroupBy = true if (bindings) { this.knexQuery.groupByRaw(sql, bindings) @@ -1661,7 +1658,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Add order by clause */ - public orderBy(column: any, direction?: any): this { + orderBy(column: any, direction?: any): this { if (typeof column === 'string') { this.knexQuery.orderBy(this.resolveKey(column), direction) return this @@ -1702,7 +1699,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Add order by clause as a raw query */ - public orderByRaw(sql: any, bindings?: any): this { + orderByRaw(sql: any, bindings?: any): this { if (bindings) { this.knexQuery.orderByRaw(sql, bindings) } else { @@ -1715,7 +1712,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Define select offset */ - public offset(value: number): this { + offset(value: number): this { this.knexQuery.offset(value) return this } @@ -1723,7 +1720,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Define results limit */ - public limit(value: number): this { + limit(value: number): this { this.knexQuery.limit(value) return this } @@ -1731,7 +1728,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Define union queries */ - public union(queries: any, wrap?: boolean): this { + union(queries: any, wrap?: boolean): this { this.hasUnion = true queries = Array.isArray(queries) @@ -1745,7 +1742,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Define union all queries */ - public unionAll(queries: any, wrap?: boolean): this { + unionAll(queries: any, wrap?: boolean): this { this.hasUnion = true queries = Array.isArray(queries) @@ -1759,7 +1756,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Define intersect queries */ - public intersect(queries: any, wrap?: boolean): this { + intersect(queries: any, wrap?: boolean): this { queries = Array.isArray(queries) ? queries.map((one) => this.transformValue(one)) : this.transformValue(queries) @@ -1771,7 +1768,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Clear select columns */ - public clearSelect(): this { + clearSelect(): this { this.knexQuery.clearSelect() return this } @@ -1779,7 +1776,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Clear where clauses */ - public clearWhere(): this { + clearWhere(): this { this.whereStack = [[]] this.knexQuery.clearWhere() return this @@ -1788,7 +1785,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Clear order by */ - public clearOrder(): this { + clearOrder(): this { this.knexQuery.clearOrder() return this } @@ -1796,7 +1793,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Clear having */ - public clearHaving(): this { + clearHaving(): this { this.knexQuery.clearHaving() return this } @@ -1804,16 +1801,16 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Clear limit */ - public clearLimit(): this { - this.knexQuery['_single'].limit = null + clearLimit(): this { + ;(this.knexQuery as any)['_single'].limit = null return this } /** * Clear offset */ - public clearOffset(): this { - this.knexQuery['_single'].offset = null + clearOffset(): this { + ;(this.knexQuery as any)['_single'].offset = null return this } @@ -1821,7 +1818,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * Specify `FOR UPDATE` lock mode for a given * query */ - public forUpdate(...tableNames: string[]): this { + forUpdate(...tableNames: string[]): this { this.knexQuery.forUpdate(...tableNames) return this @@ -1831,7 +1828,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * Specify `FOR SHARE` lock mode for a given * query */ - public forShare(...tableNames: string[]): this { + forShare(...tableNames: string[]): this { this.knexQuery.forShare(...tableNames) return this @@ -1840,7 +1837,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Skip locked rows */ - public skipLocked(): this { + skipLocked(): this { this.knexQuery.skipLocked() return this } @@ -1848,7 +1845,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Fail when query wants a locked row */ - public noWait(): this { + noWait(): this { this.knexQuery.noWait() return this } @@ -1856,7 +1853,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Define `with` CTE */ - public with(alias: any, query: any, columns: string[] = []): this { + with(alias: any, query: any, columns: string[] = []): this { if (columns.length > 0) { this.knexQuery.with(alias, columns, this.transformValue(query)) } else { @@ -1869,7 +1866,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Define `with` CTE with recursive keyword */ - public withRecursive(alias: any, query: any, columns: string[] = []): this { + withRecursive(alias: any, query: any, columns: string[] = []): this { if (columns.length > 0) { this.knexQuery.withRecursive(alias, columns, this.transformValue(query)) } else { @@ -1882,7 +1879,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Define `with materialized` CTE */ - public withMaterialized(alias: any, query: any, columns: string[] = []): this { + withMaterialized(alias: any, query: any, columns: string[] = []): this { if (columns.length > 0) { this.knexQuery.withMaterialized(alias, columns, this.transformValue(query)) } else { @@ -1895,7 +1892,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Define not `with materialized` CTE */ - public withNotMaterialized(alias: any, query: any, columns: string[] = []): this { + withNotMaterialized(alias: any, query: any, columns: string[] = []): this { if (columns.length > 0) { this.knexQuery.withNotMaterialized(alias, columns, this.transformValue(query)) } else { @@ -1908,7 +1905,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Define schema for the table */ - public withSchema(schema: any): this { + withSchema(schema: any): this { this.knexQuery.withSchema(schema) return this } @@ -1916,7 +1913,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Define table alias */ - public as(alias: any): this { + as(alias: any): this { this.subQueryAlias = alias this.knexQuery.as(alias) return this @@ -1925,7 +1922,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Count rows for the current query */ - public count(columns: any, alias?: any): this { + count(columns: any, alias?: any): this { this.hasAggregates = true this.knexQuery.count(this.normalizeAggregateColumns(columns, alias)) return this @@ -1934,7 +1931,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Count distinct rows for the current query */ - public countDistinct(columns: any, alias?: any): this { + countDistinct(columns: any, alias?: any): this { this.hasAggregates = true this.knexQuery.countDistinct(this.normalizeAggregateColumns(columns, alias)) return this @@ -1943,7 +1940,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Make use of `min` aggregate function */ - public min(columns: any, alias?: any): this { + min(columns: any, alias?: any): this { this.hasAggregates = true this.knexQuery.min(this.normalizeAggregateColumns(columns, alias)) return this @@ -1952,7 +1949,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Make use of `max` aggregate function */ - public max(columns: any, alias?: any): this { + max(columns: any, alias?: any): this { this.hasAggregates = true this.knexQuery.max(this.normalizeAggregateColumns(columns, alias)) return this @@ -1961,7 +1958,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Make use of `avg` aggregate function */ - public avg(columns: any, alias?: any): this { + avg(columns: any, alias?: any): this { this.hasAggregates = true this.knexQuery.avg(this.normalizeAggregateColumns(columns, alias)) return this @@ -1970,7 +1967,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Make use of distinct `avg` aggregate function */ - public avgDistinct(columns: any, alias?: any): this { + avgDistinct(columns: any, alias?: any): this { this.hasAggregates = true this.knexQuery.avgDistinct(this.normalizeAggregateColumns(columns, alias)) return this @@ -1979,7 +1976,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Make use of `sum` aggregate function */ - public sum(columns: any, alias?: any): this { + sum(columns: any, alias?: any): this { this.hasAggregates = true this.knexQuery.sum(this.normalizeAggregateColumns(columns, alias)) return this @@ -1988,7 +1985,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Make use of distinct `sum` aggregate function */ - public sumDistinct(columns: any, alias?: any): this { + sumDistinct(columns: any, alias?: any): this { this.hasAggregates = true this.knexQuery.sumDistinct(this.normalizeAggregateColumns(columns, alias)) return this @@ -1998,7 +1995,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * A shorthand for applying offset and limit based upon * the current page */ - public forPage(page: number, perPage: number): this { + forPage(page: number, perPage: number): this { /** * Calculate offset from current page and per page values */ @@ -2011,7 +2008,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Define a query to constraint to be defined when condition is truthy */ - public if( + if( condition: any, matchCallback: (query: this) => any, noMatchCallback?: (query: this) => any @@ -2033,7 +2030,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Define a query to constraint to be defined when condition is falsy */ - public unless( + unless( condition: any, matchCallback: (query: this) => any, noMatchCallback?: (query: this) => any @@ -2055,7 +2052,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { /** * Define matching blocks just like `if/else if and else`. */ - public match( + match( ...blocks: ([condition: any, callback: (query: this) => any] | ((query: this) => any))[] ): this { const matchingBlock = blocks.find((block) => { diff --git a/src/Database/QueryBuilder/Database.ts b/src/database/query_builder/database.ts similarity index 84% rename from src/Database/QueryBuilder/Database.ts rename to src/database/query_builder/database.ts index c209d809..7276871c 100644 --- a/src/Database/QueryBuilder/Database.ts +++ b/src/database/query_builder/database.ts @@ -7,21 +7,21 @@ * file that was distributed with this source code. */ -/// - import { Knex } from 'knex' import { Exception } from '@poppinss/utils' import { DialectContract, - DBQueryCallback, QueryClientContract, TransactionClientContract, +} from '../../../adonis-typings/database.js' +import { + DBQueryCallback, DatabaseQueryBuilderContract, -} from '@ioc:Adonis/Lucid/Database' +} from '../../../adonis-typings/querybuilder.js' -import { Chainable } from './Chainable' -import { QueryRunner } from '../../QueryRunner' -import { SimplePaginator } from '../Paginator/SimplePaginator' +import { Chainable } from './chainable.js' +import { QueryRunner } from '../../query_runner/index.js' +import { SimplePaginator } from '../paginator/simple_paginator.js' /** * Wrapping the user function for a query callback and give them @@ -59,7 +59,7 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil * Control whether to debug the query or not. The initial * value is inherited from the query client */ - private debugQueries: boolean = this.client.debug + private debugQueries: boolean /** * Required by macroable @@ -73,6 +73,7 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil public keysResolver?: (columnName: string) => string ) { super(builder, queryCallback, keysResolver) + this.debugQueries = this.client.debug } /** @@ -100,7 +101,7 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil * Define custom reporter data. It will be merged with * the existing data */ - public reporterData(data: any) { + reporterData(data: any) { this.customReporterData = data return this } @@ -108,7 +109,7 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil /** * Delete rows under the current query */ - public del(returning?: string | string[]): this { + del(returning?: string | string[]): this { this.ensureCanPerformWrites() returning ? this.knexQuery.del(returning) : this.knexQuery.del() return this @@ -117,14 +118,14 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil /** * Alias for [[del]] */ - public delete(returning?: string | string[]): this { + delete(returning?: string | string[]): this { return this.del(returning) } /** * Clone the current query builder */ - public clone(): DatabaseQueryBuilder { + clone(): DatabaseQueryBuilder { const clonedQuery = new DatabaseQueryBuilder(this.knexQuery.clone(), this.client) this.applyQueryFlags(clonedQuery) clonedQuery.debug(this.debugQueries) @@ -135,7 +136,7 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil /** * Define returning columns */ - public returning(columns: any): this { + returning(columns: any): this { if (this.client.dialect.supportsReturningStatement) { columns = Array.isArray(columns) ? columns.map((column) => this.resolveKey(column)) @@ -151,7 +152,7 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil * Perform update by incrementing value for a given column. Increments * can be clubbed with `update` as well */ - public increment(column: any, counter?: any): this { + increment(column: any, counter?: any): this { this.ensureCanPerformWrites() this.knexQuery.increment(this.resolveKey(column, true), counter) return this @@ -161,7 +162,7 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil * Perform update by decrementing value for a given column. Decrements * can be clubbed with `update` as well */ - public decrement(column: any, counter?: any): this { + decrement(column: any, counter?: any): this { this.ensureCanPerformWrites() this.knexQuery.decrement(this.resolveKey(column, true), counter) return this @@ -170,7 +171,7 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil /** * Perform update */ - public update(column: any, value?: any, returning?: string | string[]): this { + update(column: any, value?: any, returning?: string | string[]): this { this.ensureCanPerformWrites() if (value === undefined && returning === undefined) { @@ -188,7 +189,7 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil * Fetch and return first results from the results set. This method * will implicitly set a `limit` on the query */ - public async first(): Promise { + async first(): Promise { const result = await this.limit(1)['exec']() return result[0] || null } @@ -197,10 +198,10 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil * Fetch and return first results from the results set. This method * will implicitly set a `limit` on the query */ - public async firstOrFail(): Promise { + async firstOrFail(): Promise { const row = await this.first() if (!row) { - throw new Exception('Row not found', 404, 'E_ROW_NOT_FOUND') + throw new Exception('Row not found', { status: 404, code: 'E_ROW_NOT_FOUND' }) } return row @@ -209,7 +210,7 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil /** * Define a query to constraint to be defined when condition is truthy */ - public ifDialect( + ifDialect( dialects: DialectContract['name'] | DialectContract['name'][], matchCallback: (query: this) => any, noMatchCallback?: (query: this) => any @@ -228,7 +229,7 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil /** * Define a query to constraint to be defined when condition is falsy */ - public unlessDialect( + unlessDialect( dialects: DialectContract['name'] | DialectContract['name'][], matchCallback: (query: this) => any, noMatchCallback?: (query: this) => any @@ -247,7 +248,7 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil /** * Turn on/off debugging for this query */ - public debug(debug: boolean): this { + debug(debug: boolean): this { this.debugQueries = debug return this } @@ -255,7 +256,7 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil /** * Define query timeout */ - public timeout(time: number, options?: { cancel: boolean }): this { + timeout(time: number, options?: { cancel: boolean }): this { this.knexQuery['timeout'](time, options) return this } @@ -263,7 +264,7 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil /** * Returns SQL query as a string */ - public toQuery(): string { + toQuery(): string { this.applyWhere() return this.knexQuery.toQuery() } @@ -271,7 +272,7 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil /** * Run query inside the given transaction */ - public useTransaction(transaction: TransactionClientContract): this { + useTransaction(transaction: TransactionClientContract): this { this.knexQuery.transacting(transaction.knexClient) return this } @@ -279,7 +280,7 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil /** * Executes the query */ - public async exec(): Promise { + async exec(): Promise { this.applyWhere() return new QueryRunner(this.client, this.debugQueries, this.getQueryData()).run(this.knexQuery) } @@ -287,7 +288,7 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil /** * Paginate through rows inside a given table */ - public async paginate(page: number, perPage: number = 20) { + async paginate(page: number, perPage: number = 20) { /** * Cast to number */ @@ -310,7 +311,7 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil /** * Get sql representation of the query */ - public toSQL(): Knex.Sql { + toSQL(): Knex.Sql { this.applyWhere() return this.knexQuery.toSQL() } @@ -318,28 +319,28 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil /** * Implementation of `then` for the promise API */ - public then(resolve: any, reject?: any): any { + then(resolve: any, reject?: any): any { return this.exec().then(resolve, reject) } /** * Implementation of `catch` for the promise API */ - public catch(reject: any): any { + catch(reject: any): any { return this.exec().catch(reject) } /** * Implementation of `finally` for the promise API */ - public finally(fullfilled: any) { + finally(fullfilled: any) { return this.exec().finally(fullfilled) } /** * Required when Promises are extended */ - public get [Symbol.toStringTag]() { + get [Symbol.toStringTag]() { return this.constructor.name } } diff --git a/src/Database/QueryBuilder/Insert.ts b/src/database/query_builder/insert.ts similarity index 74% rename from src/Database/QueryBuilder/Insert.ts rename to src/database/query_builder/insert.ts index b4a9040d..f9b28750 100644 --- a/src/Database/QueryBuilder/Insert.ts +++ b/src/database/query_builder/insert.ts @@ -7,21 +7,16 @@ * file that was distributed with this source code. */ -/// - import { Knex } from 'knex' -import { Macroable } from 'macroable' +import Macroable from '@poppinss/macroable' -import { - QueryClientContract, - TransactionClientContract, - InsertQueryBuilderContract, -} from '@ioc:Adonis/Lucid/Database' +import { InsertQueryBuilderContract } from '../../../adonis-typings/querybuilder.js' +import { QueryClientContract, TransactionClientContract } from '../../../adonis-typings/database.js' -import { RawQueryBuilder } from './Raw' -import { QueryRunner } from '../../QueryRunner' -import { RawBuilder } from '../StaticBuilder/Raw' -import { ReferenceBuilder } from '../StaticBuilder/Reference' +import { RawQueryBuilder } from './raw.js' +import { RawBuilder } from '../static_builder/raw.js' +import { QueryRunner } from '../../query_runner/index.js' +import { ReferenceBuilder } from '../static_builder/reference.js' /** * Exposes the API for performing SQL inserts @@ -37,7 +32,7 @@ export class InsertQueryBuilder extends Macroable implements InsertQueryBuilderC * Control whether to debug the query or not. The initial * value is inherited from the query client */ - private debugQueries: boolean = this.client.debug + private debugQueries: boolean /** * Required by macroable @@ -45,8 +40,12 @@ export class InsertQueryBuilder extends Macroable implements InsertQueryBuilderC protected static macros = {} protected static getters = {} - constructor(public knexQuery: Knex.QueryBuilder, public client: QueryClientContract) { + constructor( + public knexQuery: Knex.QueryBuilder, + public client: QueryClientContract + ) { super() + this.debugQueries = this.client.debug } /** @@ -95,7 +94,7 @@ export class InsertQueryBuilder extends Macroable implements InsertQueryBuilderC * Define custom reporter data. It will be merged with * the existing data */ - public reporterData(data: any) { + reporterData(data: any) { this.customReporterData = data return this } @@ -103,7 +102,7 @@ export class InsertQueryBuilder extends Macroable implements InsertQueryBuilderC /** * Define table for performing the insert query */ - public table(table: any): this { + table(table: any): this { this.knexQuery.table(table) return this } @@ -111,7 +110,7 @@ export class InsertQueryBuilder extends Macroable implements InsertQueryBuilderC /** * Define schema for the table */ - public withSchema(schema: any): this { + withSchema(schema: any): this { this.knexQuery.withSchema(schema) return this } @@ -119,7 +118,7 @@ export class InsertQueryBuilder extends Macroable implements InsertQueryBuilderC /** * Define returning columns for the insert query */ - public returning(column: any): any { + returning(column: any): any { if (this.client.dialect.supportsReturningStatement) { this.knexQuery.returning(column) } @@ -129,18 +128,18 @@ export class InsertQueryBuilder extends Macroable implements InsertQueryBuilderC /** * Perform insert query */ - public insert(columns: any): this { + insert(columns: any): this { if (columns && Array.isArray(columns)) { columns = columns.map((column) => { return column && typeof column === 'object' - ? Object.keys(column).reduce((result, key) => { + ? Object.keys(column).reduce((result: any, key) => { result[key] = this.transformValue(column[key]) return result }, {}) : column }) } else if (columns && typeof columns === 'object') { - columns = Object.keys(columns).reduce((result, key) => { + columns = Object.keys(columns).reduce((result: any, key) => { result[key] = this.transformValue(columns[key]) return result }, {}) @@ -153,14 +152,14 @@ export class InsertQueryBuilder extends Macroable implements InsertQueryBuilderC /** * Insert multiple rows in a single query */ - public multiInsert(columns: any): this { + multiInsert(columns: any): this { return this.insert(columns) } /** * Turn on/off debugging for this query */ - public debug(debug: boolean): this { + debug(debug: boolean): this { this.debugQueries = debug return this } @@ -168,7 +167,7 @@ export class InsertQueryBuilder extends Macroable implements InsertQueryBuilderC /** * Define query timeout */ - public timeout(time: number, options?: { cancel: boolean }): this { + timeout(time: number, options?: { cancel: boolean }): this { this.knexQuery['timeout'](time, options) return this } @@ -176,14 +175,14 @@ export class InsertQueryBuilder extends Macroable implements InsertQueryBuilderC /** * Returns SQL query as a string */ - public toQuery(): string { + toQuery(): string { return this.knexQuery.toQuery() } /** * Run query inside the given transaction */ - public useTransaction(transaction: TransactionClientContract) { + useTransaction(transaction: TransactionClientContract) { this.knexQuery.transacting(transaction.knexClient) return this } @@ -191,42 +190,42 @@ export class InsertQueryBuilder extends Macroable implements InsertQueryBuilderC /** * Executes the query */ - public async exec(): Promise { + async exec(): Promise { return new QueryRunner(this.client, this.debugQueries, this.getQueryData()).run(this.knexQuery) } /** * Get sql representation of the query */ - public toSQL(): Knex.Sql { + toSQL(): Knex.Sql { return this.knexQuery.toSQL() } /** * Implementation of `then` for the promise API */ - public then(resolve: any, reject?: any): any { + then(resolve: any, reject?: any): any { return this.exec().then(resolve, reject) } /** * Implementation of `catch` for the promise API */ - public catch(reject: any): any { + catch(reject: any): any { return this.exec().catch(reject) } /** * Implementation of `finally` for the promise API */ - public finally(fullfilled: any) { + finally(fullfilled: any) { return this.exec().finally(fullfilled) } /** * Required when Promises are extended */ - public get [Symbol.toStringTag]() { + get [Symbol.toStringTag]() { return this.constructor.name } } diff --git a/src/Database/QueryBuilder/Raw.ts b/src/database/query_builder/raw.ts similarity index 71% rename from src/Database/QueryBuilder/Raw.ts rename to src/database/query_builder/raw.ts index 20aff26a..026d4aab 100644 --- a/src/Database/QueryBuilder/Raw.ts +++ b/src/database/query_builder/raw.ts @@ -7,16 +7,11 @@ * file that was distributed with this source code. */ -/// - import { Knex } from 'knex' -import { - QueryClientContract, - RawQueryBuilderContract, - TransactionClientContract, -} from '@ioc:Adonis/Lucid/Database' -import { QueryRunner } from '../../QueryRunner' +import { QueryRunner } from '../../query_runner/index.js' +import { RawQueryBuilderContract } from '../../../adonis-typings/querybuilder.js' +import { QueryClientContract, TransactionClientContract } from '../../../adonis-typings/database.js' /** * Exposes the API to execute raw queries @@ -32,9 +27,14 @@ export class RawQueryBuilder implements RawQueryBuilderContract { * Control whether to debug the query or not. The initial * value is inherited from the query client */ - private debugQueries: boolean = this.client.debug + private debugQueries: boolean - constructor(public knexQuery: Knex.Raw, public client: QueryClientContract) {} + constructor( + public knexQuery: Knex.Raw, + public client: QueryClientContract + ) { + this.debugQueries = this.client.debug + } /** * Returns the log data @@ -51,7 +51,7 @@ export class RawQueryBuilder implements RawQueryBuilderContract { * Define custom reporter data. It will be merged with * the existing data */ - public reporterData(data: any) { + reporterData(data: any) { this.customReporterData = data return this } @@ -59,7 +59,7 @@ export class RawQueryBuilder implements RawQueryBuilderContract { /** * Wrap the query with before/after strings. */ - public wrap(before: string, after: string): this { + wrap(before: string, after: string): this { this.knexQuery.wrap(before, after) return this } @@ -67,7 +67,7 @@ export class RawQueryBuilder implements RawQueryBuilderContract { /** * Turn on/off debugging for this query */ - public debug(debug: boolean): this { + debug(debug: boolean): this { this.debugQueries = debug return this } @@ -75,7 +75,7 @@ export class RawQueryBuilder implements RawQueryBuilderContract { /** * Define query timeout */ - public timeout(time: number, options?: { cancel: boolean }): this { + timeout(time: number, options?: { cancel: boolean }): this { this.knexQuery['timeout'](time, options) return this } @@ -83,14 +83,14 @@ export class RawQueryBuilder implements RawQueryBuilderContract { /** * Returns SQL query as a string */ - public toQuery(): string { + toQuery(): string { return this.knexQuery.toQuery() } /** * Run query inside the given transaction */ - public useTransaction(transaction: TransactionClientContract) { + useTransaction(transaction: TransactionClientContract) { this.knexQuery.transacting(transaction.knexClient) return this } @@ -98,42 +98,42 @@ export class RawQueryBuilder implements RawQueryBuilderContract { /** * Executes the query */ - public async exec(): Promise { + async exec(): Promise { return new QueryRunner(this.client, this.debugQueries, this.getQueryData()).run(this.knexQuery) } /** * Get sql representation of the query */ - public toSQL(): Knex.Sql { + toSQL(): Knex.Sql { return this.knexQuery.toSQL() } /** * Implementation of `then` for the promise API */ - public then(resolve: any, reject?: any): any { + then(resolve: any, reject?: any): any { return this.exec().then(resolve, reject) } /** * Implementation of `catch` for the promise API */ - public catch(reject: any): any { + catch(reject: any): any { return this.exec().catch(reject) } /** * Implementation of `finally` for the promise API */ - public finally(fullfilled: any) { + finally(fullfilled: any) { return this.exec().finally(fullfilled) } /** * Required when Promises are extended */ - public get [Symbol.toStringTag]() { + get [Symbol.toStringTag]() { return this.constructor.name } } diff --git a/src/Database/StaticBuilder/Raw.ts b/src/database/static_builder/raw.ts similarity index 70% rename from src/Database/StaticBuilder/Raw.ts rename to src/database/static_builder/raw.ts index f56cca55..fcde0fbb 100644 --- a/src/Database/StaticBuilder/Raw.ts +++ b/src/database/static_builder/raw.ts @@ -7,25 +7,26 @@ * file that was distributed with this source code. */ -/// - import { Knex } from 'knex' -import { RawBuilderContract } from '@ioc:Adonis/Lucid/Database' +import { RawBuilderContract } from '../../../adonis-typings/querybuilder.js' /** * Exposes the API to construct raw queries. If you want to execute * raw queries, you can use the RawQueryBuilder */ export class RawBuilder implements RawBuilderContract { - private wrapBefore: string - private wrapAfter: string + private wrapBefore?: string + private wrapAfter?: string - constructor(private sql: string, private bindings?: any) {} + constructor( + private sql: string, + private bindings?: any + ) {} /** * Wrap the query with before/after strings. */ - public wrap(before: string, after: string): this { + wrap(before: string, after: string): this { this.wrapAfter = after this.wrapBefore = before return this @@ -34,7 +35,7 @@ export class RawBuilder implements RawBuilderContract { /** * Converts the raw query to knex raw query instance */ - public toKnex(client: Knex.Client): Knex.Raw { + toKnex(client: Knex.Client): Knex.Raw { const rawQuery = client.raw(this.sql, this.bindings) if (this.wrapBefore && this.wrapAfter) { diff --git a/src/Database/StaticBuilder/Reference.ts b/src/database/static_builder/reference.ts similarity index 66% rename from src/Database/StaticBuilder/Reference.ts rename to src/database/static_builder/reference.ts index 40476b2e..52e875ca 100644 --- a/src/Database/StaticBuilder/Reference.ts +++ b/src/database/static_builder/reference.ts @@ -7,24 +7,25 @@ * file that was distributed with this source code. */ -/// - import { Knex } from 'knex' -import { ReferenceBuilderContract } from '@ioc:Adonis/Lucid/Database' +import { ReferenceBuilderContract } from '../../../adonis-typings/querybuilder.js' /** * Reference builder to create SQL reference values */ export class ReferenceBuilder implements ReferenceBuilderContract { - private schema: string - private alias: string + private schema?: string + private alias?: string - constructor(private ref: string, private client: Knex.Client) {} + constructor( + private ref: string, + private client: Knex.Client + ) {} /** * Define schema */ - public withSchema(schema: string): this { + withSchema(schema: string): this { this.schema = schema return this } @@ -32,7 +33,7 @@ export class ReferenceBuilder implements ReferenceBuilderContract { /** * Define alias */ - public as(alias: string): this { + as(alias: string): this { this.alias = alias return this } @@ -40,7 +41,7 @@ export class ReferenceBuilder implements ReferenceBuilderContract { /** * Converts reference to knex */ - public toKnex(client?: Knex.Client) { + toKnex(client?: Knex.Client) { const ref = (client || this.client).ref(this.ref) this.schema && ref.withSchema(this.schema) this.alias && ref.as(this.alias) diff --git a/src/Dialects/SqliteBase.ts b/src/dialects/base_sqlite.ts similarity index 71% rename from src/Dialects/SqliteBase.ts rename to src/dialects/base_sqlite.ts index 128ec017..5a6d806d 100644 --- a/src/Dialects/SqliteBase.ts +++ b/src/dialects/base_sqlite.ts @@ -7,35 +7,42 @@ * file that was distributed with this source code. */ -/// - -import { DialectContract, QueryClientContract, SqliteConfig } from '@ioc:Adonis/Lucid/Database' +import type { + DialectContract, + QueryClientContract, + SharedConfigNode, +} from '../../adonis-typings/database.js' export abstract class BaseSqliteDialect implements DialectContract { - public abstract readonly name: 'sqlite3' | 'better-sqlite3' - public readonly supportsAdvisoryLocks = false - public readonly supportsViews = true - public readonly supportsTypes = false - public readonly supportsReturningStatement = false + abstract readonly name: 'sqlite3' | 'better-sqlite3' + readonly supportsAdvisoryLocks = false + readonly supportsViews = true + readonly supportsTypes = false + readonly supportsReturningStatement = false /** * Reference to the database version. Knex.js fetches the version after * the first database query, so it will be set to undefined initially */ - public readonly version = this.client.getReadClient()['context']['client'].version + readonly version: string /** * The default format for datetime column. The date formats is * valid for luxon date parsing library */ - public readonly dateTimeFormat = 'yyyy-MM-dd HH:mm:ss' + readonly dateTimeFormat = 'yyyy-MM-dd HH:mm:ss' - constructor(private client: QueryClientContract, private config: SqliteConfig) {} + constructor( + private client: QueryClientContract, + private config: SharedConfigNode + ) { + this.version = (this.client.getReadClient() as any).context['client'].version + } /** * Returns an array of table names */ - public async getAllTables() { + async getAllTables() { const tables = await this.client .query() .from('sqlite_master') @@ -50,7 +57,7 @@ export abstract class BaseSqliteDialect implements DialectContract { /** * Returns an array of all views names */ - public async getAllViews(): Promise { + async getAllViews(): Promise { const tables = await this.client .query() .from('sqlite_master') @@ -65,21 +72,21 @@ export abstract class BaseSqliteDialect implements DialectContract { /** * Returns an array of all types names */ - public async getAllTypes(): Promise { + async getAllTypes(): Promise { throw new Error("Sqlite doesn't support types") } /** * Truncate SQLITE tables */ - public async truncate(table: string) { + async truncate(table: string) { return this.client.knexQuery().table(table).truncate() } /** * Drop all tables inside the database */ - public async dropAllTables() { + async dropAllTables() { await this.client.rawQuery('PRAGMA writable_schema = 1;') await this.client .knexQuery() @@ -95,7 +102,7 @@ export abstract class BaseSqliteDialect implements DialectContract { /** * Drop all views inside the database */ - public async dropAllViews(): Promise { + async dropAllViews(): Promise { await this.client.rawQuery('PRAGMA writable_schema = 1;') await this.client.rawQuery(`delete from sqlite_schema where type = 'view';`) await this.client.rawQuery('PRAGMA writable_schema = 0;') @@ -105,7 +112,7 @@ export abstract class BaseSqliteDialect implements DialectContract { /** * Drop all custom types inside the database */ - public async dropAllTypes(): Promise { + async dropAllTypes(): Promise { throw new Error("Sqlite doesn't support types") } @@ -113,14 +120,14 @@ export abstract class BaseSqliteDialect implements DialectContract { * Attempts to add advisory lock to the database and * returns it's status. */ - public getAdvisoryLock(): Promise { + getAdvisoryLock(): Promise { throw new Error("Sqlite doesn't support advisory locks") } /** * Releases the advisory lock */ - public releaseAdvisoryLock(): Promise { + releaseAdvisoryLock(): Promise { throw new Error("Sqlite doesn't support advisory locks") } } diff --git a/src/Dialects/BetterSqlite.ts b/src/dialects/better_sqlite.ts similarity index 58% rename from src/Dialects/BetterSqlite.ts rename to src/dialects/better_sqlite.ts index 50948a41..6525886b 100644 --- a/src/Dialects/BetterSqlite.ts +++ b/src/dialects/better_sqlite.ts @@ -7,11 +7,9 @@ * file that was distributed with this source code. */ -/// - -import { DialectContract } from '@ioc:Adonis/Lucid/Database' -import { BaseSqliteDialect } from './SqliteBase' +import { DialectContract } from '../../adonis-typings/database.js' +import { BaseSqliteDialect } from './base_sqlite.js' export class BetterSqliteDialect extends BaseSqliteDialect implements DialectContract { - public readonly name = 'better-sqlite3' + readonly name = 'better-sqlite3' } diff --git a/src/Dialects/index.ts b/src/dialects/index.ts similarity index 56% rename from src/Dialects/index.ts rename to src/dialects/index.ts index b93fad1b..e30fc5cb 100644 --- a/src/Dialects/index.ts +++ b/src/dialects/index.ts @@ -7,16 +7,24 @@ * file that was distributed with this source code. */ -import { PgDialect } from './Pg' -import { MysqlDialect } from './Mysql' -import { MssqlDialect } from './Mssql' -import { SqliteDialect } from './Sqlite' -import { OracleDialect } from './Oracle' -import { RedshiftDialect } from './Redshift' -import { BetterSqliteDialect } from './BetterSqlite' -import { DialectContract, QueryClientContract, SharedConfigNode } from '@ioc:Adonis/Lucid/Database' +import { PgDialect } from './pg.js' +import { MysqlDialect } from './mysql.js' +import { MssqlDialect } from './mssql.js' +import { SqliteDialect } from './sqlite.js' +import { OracleDialect } from './oracle.js' +import { RedshiftDialect } from './red_shift.js' +import { BetterSqliteDialect } from './better_sqlite.js' +import { + DialectContract, + QueryClientContract, + SharedConfigNode, +} from '../../adonis-typings/database.js' -export const dialects = { +export const dialects: { + [key: string]: { + new (client: QueryClientContract, config: SharedConfigNode): DialectContract + } +} = { 'mssql': MssqlDialect, 'mysql': MysqlDialect, 'mysql2': MysqlDialect, @@ -25,8 +33,4 @@ export const dialects = { 'redshift': RedshiftDialect, 'sqlite3': SqliteDialect, 'better-sqlite3': BetterSqliteDialect, -} as { - [key: string]: { - new (client: QueryClientContract, config: SharedConfigNode): DialectContract - } } diff --git a/src/Dialects/Mssql.ts b/src/dialects/mssql.ts similarity index 72% rename from src/Dialects/Mssql.ts rename to src/dialects/mssql.ts index bc92ee91..3cbd90d2 100644 --- a/src/Dialects/Mssql.ts +++ b/src/dialects/mssql.ts @@ -7,36 +7,43 @@ * file that was distributed with this source code. */ -/// - -import { RawBuilder } from '../Database/StaticBuilder/Raw' -import { DialectContract, MssqlConfig, QueryClientContract } from '@ioc:Adonis/Lucid/Database' +import { RawBuilder } from '../database/static_builder/raw.js' +import { + DialectContract, + SharedConfigNode, + QueryClientContract, +} from '../../adonis-typings/database.js' export class MssqlDialect implements DialectContract { - public readonly name = 'mssql' - public readonly supportsAdvisoryLocks = false - public readonly supportsViews = false - public readonly supportsTypes = false - public readonly supportsReturningStatement = true + readonly name = 'mssql' + readonly supportsAdvisoryLocks = false + readonly supportsViews = false + readonly supportsTypes = false + readonly supportsReturningStatement = true /** * Reference to the database version. Knex.js fetches the version after * the first database query, so it will be set to undefined initially */ - public readonly version = this.client.getReadClient()['context']['client'].version + readonly version: string /** * The default format for datetime column. The date formats is * valid for luxon date parsing library */ - public readonly dateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZ" + readonly dateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZ" - constructor(private client: QueryClientContract, private config: MssqlConfig) {} + constructor( + private client: QueryClientContract, + private config: SharedConfigNode + ) { + this.version = (this.client.getReadClient() as any)['context']['client'].version + } /** * Returns an array of table names */ - public async getAllTables() { + async getAllTables() { const tables = await this.client .query() .from('information_schema.tables') @@ -57,14 +64,14 @@ export class MssqlDialect implements DialectContract { * One has to drop all FK constraints and then re-create them, and * this all is too much work */ - public async truncate(table: string, _: boolean) { + async truncate(table: string, _: boolean) { return this.client.knexQuery().table(table).truncate() } /** * Drop all tables inside the database */ - public async dropAllTables() { + async dropAllTables() { await this.client.rawQuery(` DECLARE @sql NVARCHAR(MAX) = N''; SELECT @sql += 'ALTER TABLE ' @@ -84,37 +91,37 @@ export class MssqlDialect implements DialectContract { `) } - public async getAllViews(): Promise { + async getAllViews(): Promise { throw new Error( '"getAllViews" method not implemented is not implemented for mssql. Create a PR to add the feature' ) } - public async getAllTypes(): Promise { + async getAllTypes(): Promise { throw new Error( '"getAllTypes" method not implemented is not implemented for mssql. Create a PR to add the feature' ) } - public async dropAllViews(): Promise { + async dropAllViews(): Promise { throw new Error( '"dropAllViews" method not implemented is not implemented for mssql. Create a PR to add the feature' ) } - public async dropAllTypes(): Promise { + async dropAllTypes(): Promise { throw new Error( '"dropAllTypes" method not implemented is not implemented for mssql. Create a PR to add the feature' ) } - public getAdvisoryLock(): Promise { + getAdvisoryLock(): Promise { throw new Error( 'Support for advisory locks is not implemented for mssql. Create a PR to add the feature' ) } - public releaseAdvisoryLock(): Promise { + releaseAdvisoryLock(): Promise { throw new Error( 'Support for advisory locks is not implemented for mssql. Create a PR to add the feature' ) diff --git a/src/Dialects/Mysql.ts b/src/dialects/mysql.ts similarity index 76% rename from src/Dialects/Mysql.ts rename to src/dialects/mysql.ts index 122897d6..0e4daf63 100644 --- a/src/Dialects/Mysql.ts +++ b/src/dialects/mysql.ts @@ -7,36 +7,43 @@ * file that was distributed with this source code. */ -/// - -import { RawBuilder } from '../Database/StaticBuilder/Raw' -import { DialectContract, MysqlConfig, QueryClientContract } from '@ioc:Adonis/Lucid/Database' +import { RawBuilder } from '../database/static_builder/raw.js' +import { + DialectContract, + SharedConfigNode, + QueryClientContract, +} from '../../adonis-typings/database.js' export class MysqlDialect implements DialectContract { - public readonly name = 'mysql' - public readonly supportsAdvisoryLocks = true - public readonly supportsViews = true - public readonly supportsTypes = false - public readonly supportsReturningStatement = false + readonly name = 'mysql' + readonly supportsAdvisoryLocks = true + readonly supportsViews = true + readonly supportsTypes = false + readonly supportsReturningStatement = false /** * Reference to the database version. Knex.js fetches the version after * the first database query, so it will be set to undefined initially */ - public readonly version = this.client.getReadClient()['context']['client'].version + readonly version: string /** * The default format for datetime column. The date formats is * valid for luxon date parsing library */ - public readonly dateTimeFormat = 'yyyy-MM-dd HH:mm:ss' + readonly dateTimeFormat = 'yyyy-MM-dd HH:mm:ss' - constructor(private client: QueryClientContract, private config: MysqlConfig) {} + constructor( + private client: QueryClientContract, + private config: SharedConfigNode + ) { + this.version = (this.client.getReadClient() as any)['context']['client'].version + } /** * Truncate mysql table with option to cascade */ - public async truncate(table: string, cascade: boolean = false) { + async truncate(table: string, cascade: boolean = false) { if (!cascade) { return this.client.knexQuery().table(table).truncate() } @@ -59,7 +66,7 @@ export class MysqlDialect implements DialectContract { /** * Returns an array of table names */ - public async getAllTables(): Promise { + async getAllTables(): Promise { const tables = await this.client .query() .from('information_schema.tables') @@ -74,7 +81,7 @@ export class MysqlDialect implements DialectContract { /** * Returns an array of all views names */ - public async getAllViews(): Promise { + async getAllViews(): Promise { const tables = await this.client .query() .from('information_schema.tables') @@ -89,14 +96,14 @@ export class MysqlDialect implements DialectContract { /** * Returns an array of all types names */ - public async getAllTypes(): Promise { + async getAllTypes(): Promise { throw new Error("MySQL doesn't support types") } /** * Drop all tables inside the database */ - public async dropAllTables() { + async dropAllTables() { let tables = await this.getAllTables() /** @@ -133,7 +140,7 @@ export class MysqlDialect implements DialectContract { /** * Drop all views inside the database */ - public async dropAllViews(): Promise { + async dropAllViews(): Promise { const views = await this.getAllViews() return this.client.rawQuery(`DROP VIEW ${views.join(',')};`) @@ -142,7 +149,7 @@ export class MysqlDialect implements DialectContract { /** * Drop all custom types inside the database */ - public async dropAllTypes(): Promise { + async dropAllTypes(): Promise { throw new Error("MySQL doesn't support types") } @@ -150,7 +157,7 @@ export class MysqlDialect implements DialectContract { * Attempts to add advisory lock to the database and * returns it's status. */ - public async getAdvisoryLock(key: string, timeout: number = 0): Promise { + async getAdvisoryLock(key: string, timeout: number = 0): Promise { const response = await this.client.rawQuery( `SELECT GET_LOCK('${key}', ${timeout}) as lock_status;` ) @@ -160,7 +167,7 @@ export class MysqlDialect implements DialectContract { /** * Releases the advisory lock */ - public async releaseAdvisoryLock(key: string): Promise { + async releaseAdvisoryLock(key: string): Promise { const response = await this.client.rawQuery(`SELECT RELEASE_LOCK('${key}') as lock_status;`) return response[0] && response[0][0] && response[0][0].lock_status === 1 } diff --git a/src/Dialects/Oracle.ts b/src/dialects/oracle.ts similarity index 65% rename from src/Dialects/Oracle.ts rename to src/dialects/oracle.ts index ac4297ed..ee3d1213 100644 --- a/src/Dialects/Oracle.ts +++ b/src/dialects/oracle.ts @@ -7,35 +7,35 @@ * file that was distributed with this source code. */ -/// - -import { DialectContract, QueryClientContract } from '@ioc:Adonis/Lucid/Database' +import { DialectContract, QueryClientContract } from '../../adonis-typings/database.js' export class OracleDialect implements DialectContract { - public readonly name = 'oracledb' - public readonly supportsAdvisoryLocks = false - public readonly supportsViews = false - public readonly supportsTypes = false - public readonly supportsReturningStatement = true + readonly name = 'oracledb' + readonly supportsAdvisoryLocks = false + readonly supportsViews = false + readonly supportsTypes = false + readonly supportsReturningStatement = true /** * Reference to the database version. Knex.js fetches the version after * the first database query, so it will be set to undefined initially */ - public readonly version = this.client.getReadClient()['context']['client'].version + readonly version: string /** * The default format for datetime column. The date formats is * valid for luxon date parsing library */ - public readonly dateTimeFormat = 'yyyy-MM-dd HH:mm:ss' + readonly dateTimeFormat = 'yyyy-MM-dd HH:mm:ss' - constructor(private client: QueryClientContract) {} + constructor(private client: QueryClientContract) { + this.version = (this.client.getReadClient() as any)['context']['client'].version + } /** * Not implemented yet */ - public async getAllTables(): Promise { + async getAllTables(): Promise { throw new Error( '"getAllTables" method is not implemented for oracledb. Create a PR to add the feature' ) @@ -44,7 +44,7 @@ export class OracleDialect implements DialectContract { /** * Truncate pg table with option to cascade and restart identity */ - public async truncate(table: string, cascade: boolean = false) { + async truncate(table: string, cascade: boolean = false) { return cascade ? this.client.rawQuery(`TRUNCATE ${table} CASCADE;`) : this.client.rawQuery(`TRUNCATE ${table};`) @@ -53,43 +53,43 @@ export class OracleDialect implements DialectContract { /** * Not implemented yet */ - public async dropAllTables() { + async dropAllTables() { throw new Error( '"dropAllTables" method is not implemented for oracledb. Create a PR to add the feature' ) } - public async getAllViews(): Promise { + async getAllViews(): Promise { throw new Error( '"getAllViews" method is not implemented for oracledb. Create a PR to add the feature.' ) } - public async getAllTypes(): Promise { + async getAllTypes(): Promise { throw new Error( '"getAllTypes" method is not implemented for oracledb. Create a PR to add the feature.' ) } - public async dropAllViews(): Promise { + async dropAllViews(): Promise { throw new Error( '"dropAllViews" method is not implemented for oracledb. Create a PR to add the feature.' ) } - public async dropAllTypes(): Promise { + async dropAllTypes(): Promise { throw new Error( '"dropAllTypes" method is not implemented for oracledb. Create a PR to add the feature.' ) } - public getAdvisoryLock(): Promise { + getAdvisoryLock(): Promise { throw new Error( 'Support for advisory locks is not implemented for oracledb. Create a PR to add the feature' ) } - public releaseAdvisoryLock(): Promise { + releaseAdvisoryLock(): Promise { throw new Error( 'Support for advisory locks is not implemented for oracledb. Create a PR to add the feature' ) diff --git a/src/Dialects/Pg.ts b/src/dialects/pg.ts similarity index 74% rename from src/Dialects/Pg.ts rename to src/dialects/pg.ts index 0355e6c9..4505484c 100644 --- a/src/Dialects/Pg.ts +++ b/src/dialects/pg.ts @@ -7,35 +7,42 @@ * file that was distributed with this source code. */ -/// - -import { DialectContract, PostgreConfig, QueryClientContract } from '@ioc:Adonis/Lucid/Database' +import { + DialectContract, + SharedConfigNode, + QueryClientContract, +} from '../../adonis-typings/database.js' export class PgDialect implements DialectContract { - public readonly name = 'postgres' - public readonly supportsAdvisoryLocks = true - public readonly supportsViews = true - public readonly supportsTypes = true - public readonly supportsReturningStatement = true + readonly name = 'postgres' + readonly supportsAdvisoryLocks = true + readonly supportsViews = true + readonly supportsTypes = true + readonly supportsReturningStatement = true /** * Reference to the database version. Knex.js fetches the version after * the first database query, so it will be set to undefined initially */ - public readonly version = this.client.getReadClient()['context']['client'].version + readonly version: string /** * The default format for datetime column. The date formats is * valid for luxon date parsing library */ - public readonly dateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZ" + readonly dateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZ" - constructor(private client: QueryClientContract, private config: PostgreConfig) {} + constructor( + private client: QueryClientContract, + private config: SharedConfigNode + ) { + this.version = (this.client.getReadClient() as any)['context']['client'].version + } /** * Returns an array of table names for one or many schemas. */ - public async getAllTables(schemas: string[]) { + async getAllTables(schemas: string[]) { const tables = await this.client .query() .from('pg_catalog.pg_tables') @@ -49,7 +56,7 @@ export class PgDialect implements DialectContract { /** * Returns an array of all views names for one or many schemas */ - public async getAllViews(schemas: string[]) { + async getAllViews(schemas: string[]) { const views = await this.client .query() .from('pg_catalog.pg_views') @@ -63,7 +70,7 @@ export class PgDialect implements DialectContract { /** * Returns an array of all types names */ - public async getAllTypes(_schemas: string[]) { + async getAllTypes(_schemas: string[]) { const types = await this.client .query() .select('pg_type.typname') @@ -77,7 +84,7 @@ export class PgDialect implements DialectContract { /** * Truncate pg table with option to cascade and restart identity */ - public async truncate(table: string, cascade: boolean = false) { + async truncate(table: string, cascade: boolean = false) { return cascade ? this.client.rawQuery(`TRUNCATE "${table}" RESTART IDENTITY CASCADE;`) : this.client.rawQuery(`TRUNCATE "${table}";`) @@ -86,7 +93,7 @@ export class PgDialect implements DialectContract { /** * Drop all tables inside the database */ - public async dropAllTables(schemas: string[]) { + async dropAllTables(schemas: string[]) { let tables = await this.getAllTables(schemas) /** @@ -106,7 +113,7 @@ export class PgDialect implements DialectContract { /** * Drop all views inside the database */ - public async dropAllViews(schemas: string[]) { + async dropAllViews(schemas: string[]) { const views = await this.getAllViews(schemas) if (!views.length) return @@ -116,7 +123,7 @@ export class PgDialect implements DialectContract { /** * Drop all types inside the database */ - public async dropAllTypes(schemas: string[]) { + async dropAllTypes(schemas: string[]) { const types = await this.getAllTypes(schemas) if (!types.length) return @@ -127,7 +134,7 @@ export class PgDialect implements DialectContract { * Attempts to add advisory lock to the database and * returns it's status. */ - public async getAdvisoryLock(key: string): Promise { + async getAdvisoryLock(key: string): Promise { const response = await this.client.rawQuery( `SELECT PG_TRY_ADVISORY_LOCK('${key}') as lock_status;` ) @@ -137,7 +144,7 @@ export class PgDialect implements DialectContract { /** * Releases the advisory lock */ - public async releaseAdvisoryLock(key: string): Promise { + async releaseAdvisoryLock(key: string): Promise { const response = await this.client.rawQuery( `SELECT PG_ADVISORY_UNLOCK('${key}') as lock_status;` ) diff --git a/src/Dialects/Redshift.ts b/src/dialects/red_shift.ts similarity index 77% rename from src/Dialects/Redshift.ts rename to src/dialects/red_shift.ts index 4fc0b4bd..59c0d425 100644 --- a/src/Dialects/Redshift.ts +++ b/src/dialects/red_shift.ts @@ -7,37 +7,44 @@ * file that was distributed with this source code. */ -/// - -import { DialectContract, PostgreConfig, QueryClientContract } from '@ioc:Adonis/Lucid/Database' +import { + DialectContract, + SharedConfigNode, + QueryClientContract, +} from '../../adonis-typings/database.js' export class RedshiftDialect implements DialectContract { - public readonly name = 'redshift' - public readonly supportsAdvisoryLocks = false - public readonly supportsViews = true - public readonly supportsTypes = true - public readonly supportsReturningStatement = true + readonly name = 'redshift' + readonly supportsAdvisoryLocks = false + readonly supportsViews = true + readonly supportsTypes = true + readonly supportsReturningStatement = true /** * Reference to the database version. Knex.js fetches the version after * the first database query, so it will be set to undefined initially */ - public readonly version = this.client.getReadClient()['context']['client'].version + readonly version: string /** * The default format for datetime column. The date formats is * valid for luxon date parsing library */ - public readonly dateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZ" + readonly dateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZ" - constructor(private client: QueryClientContract, private config: PostgreConfig) {} + constructor( + private client: QueryClientContract, + private config: SharedConfigNode + ) { + this.version = (this.client.getReadClient() as any)['context']['client'].version + } /** * Returns an array of table names for one or many schemas. * * NOTE: ASSUMING FEATURE PARITY WITH POSTGRESQL HERE (NOT TESTED) */ - public async getAllTables(schemas: string[]) { + async getAllTables(schemas: string[]) { const tables = await this.client .query() .from('pg_catalog.pg_tables') @@ -53,7 +60,7 @@ export class RedshiftDialect implements DialectContract { * * NOTE: ASSUMING FEATURE PARITY WITH POSTGRESQL HERE (NOT TESTED) */ - public async getAllViews(schemas: string[]) { + async getAllViews(schemas: string[]) { const views = await this.client .query() .from('pg_catalog.pg_views') @@ -69,7 +76,7 @@ export class RedshiftDialect implements DialectContract { * * NOTE: ASSUMING FEATURE PARITY WITH POSTGRESQL HERE (NOT TESTED) */ - public async getAllTypes(_schemas: string[]) { + async getAllTypes(_schemas: string[]) { const types = await this.client .query() .select('pg_type.typname') @@ -85,7 +92,7 @@ export class RedshiftDialect implements DialectContract { * * NOTE: ASSUMING FEATURE PARITY WITH POSTGRESQL HERE (NOT TESTED) */ - public async truncate(table: string, cascade: boolean = false) { + async truncate(table: string, cascade: boolean = false) { return cascade ? this.client.rawQuery(`TRUNCATE "${table}" RESTART IDENTITY CASCADE;`) : this.client.rawQuery(`TRUNCATE "${table}";`) @@ -94,7 +101,7 @@ export class RedshiftDialect implements DialectContract { /** * Drop all tables inside the database */ - public async dropAllTables(schemas: string[]) { + async dropAllTables(schemas: string[]) { let tables = await this.getAllTables(schemas) /** @@ -116,7 +123,7 @@ export class RedshiftDialect implements DialectContract { * * NOTE: ASSUMING FEATURE PARITY WITH POSTGRESQL HERE (NOT TESTED) */ - public async dropAllViews(schemas: string[]) { + async dropAllViews(schemas: string[]) { const views = await this.getAllViews(schemas) if (!views.length) return @@ -128,7 +135,7 @@ export class RedshiftDialect implements DialectContract { * * NOTE: ASSUMING FEATURE PARITY WITH POSTGRESQL HERE (NOT TESTED) */ - public async dropAllTypes(schemas: string[]) { + async dropAllTypes(schemas: string[]) { const types = await this.getAllTypes(schemas) if (!types.length) return @@ -139,7 +146,7 @@ export class RedshiftDialect implements DialectContract { * Redshift doesn't support advisory locks. Learn more: * https://tableplus.com/blog/2018/10/redshift-vs-postgres-database-comparison.html */ - public getAdvisoryLock(): Promise { + getAdvisoryLock(): Promise { throw new Error("Redshift doesn't support advisory locks") } @@ -147,7 +154,7 @@ export class RedshiftDialect implements DialectContract { * Redshift doesn't support advisory locks. Learn more: * https://tableplus.com/blog/2018/10/redshift-vs-postgres-database-comparison.html */ - public releaseAdvisoryLock(): Promise { + releaseAdvisoryLock(): Promise { throw new Error("Redshift doesn't support advisory locks") } } diff --git a/src/Dialects/Sqlite.ts b/src/dialects/sqlite.ts similarity index 58% rename from src/Dialects/Sqlite.ts rename to src/dialects/sqlite.ts index 827915ae..367ea372 100644 --- a/src/Dialects/Sqlite.ts +++ b/src/dialects/sqlite.ts @@ -7,11 +7,9 @@ * file that was distributed with this source code. */ -/// - -import { DialectContract } from '@ioc:Adonis/Lucid/Database' -import { BaseSqliteDialect } from './SqliteBase' +import { DialectContract } from '../../adonis-typings/database.js' +import { BaseSqliteDialect } from './base_sqlite.js' export class SqliteDialect extends BaseSqliteDialect implements DialectContract { - public readonly name = 'sqlite3' + readonly name = 'sqlite3' } diff --git a/src/Helpers/prettyPrint.ts b/src/helpers/pretty_print.ts similarity index 75% rename from src/Helpers/prettyPrint.ts rename to src/helpers/pretty_print.ts index d86ce28e..7afb9540 100644 --- a/src/Helpers/prettyPrint.ts +++ b/src/helpers/pretty_print.ts @@ -7,9 +7,12 @@ * file that was distributed with this source code. */ -import { inspect } from 'util' +// @ts-expect-error import igniculus from 'igniculus' -import { DbQueryEventNode } from '@ioc:Adonis/Lucid/Database' +import kleur from 'kleur' +import { inspect } from 'node:util' +import hrTime from 'pretty-hrtime' +import { DbQueryEventNode } from '../../adonis-typings/database.js' const illuminate = igniculus({ comments: { fg: 'gray' }, @@ -34,16 +37,10 @@ function colorizeQuery(sql: string) { * Pretty print queries */ export function prettyPrint(queryLog: DbQueryEventNode) { - /** - * Lazy loading pretty printed dependencies - */ - const color = require('kleur') - const prettyHrtime = require('pretty-hrtime') - let output: string = '' if (!queryLog.ddl) { - output += color.gray(`"${queryLog.connection}" `) + output += kleur.gray(`"${queryLog.connection}" `) } /** @@ -57,7 +54,7 @@ export function prettyPrint(queryLog: DbQueryEventNode) { * Concatenate the duration */ if (queryLog.duration) { - output += `(${prettyHrtime(queryLog.duration)}) ` + output += `(${hrTime(queryLog.duration)}) ` } /** @@ -66,7 +63,7 @@ export function prettyPrint(queryLog: DbQueryEventNode) { output += colorizeQuery(queryLog.sql) if (!queryLog.ddl) { - output += color.gray(` ${inspect(queryLog.bindings)}`) + output += kleur.gray(` ${inspect(queryLog.bindings)}`) } /** diff --git a/src/Helpers/scope.ts b/src/helpers/scope.ts similarity index 68% rename from src/Helpers/scope.ts rename to src/helpers/scope.ts index 1c32c5d9..eb160b1e 100644 --- a/src/Helpers/scope.ts +++ b/src/helpers/scope.ts @@ -7,13 +7,13 @@ * file that was distributed with this source code. */ -import { LucidModel, QueryScope, QueryScopeCallback } from '@ioc:Adonis/Lucid/Orm' +import { LucidModel, QueryScope, QueryScopeCallback } from '../../adonis-typings/model.js' /** * Helper to mark a function as query scope */ export function scope>( callback: Callback -): QueryScope { - return callback as QueryScope +): QueryScope { + return callback as QueryScope } diff --git a/src/QueryClient/index.ts b/src/query_client/index.ts similarity index 62% rename from src/QueryClient/index.ts rename to src/query_client/index.ts index a93d5771..57c112c0 100644 --- a/src/QueryClient/index.ts +++ b/src/query_client/index.ts @@ -7,12 +7,9 @@ * file that was distributed with this source code. */ -/// - import { Knex } from 'knex' import { Exception } from '@poppinss/utils' -import { EmitterContract } from '@ioc:Adonis/Core/Event' -import { ProfilerRowContract, ProfilerContract } from '@ioc:Adonis/Core/Profiler' +import type { Emitter } from '@adonisjs/core/events' import { IsolationLevels, @@ -20,16 +17,21 @@ import { ConnectionContract, QueryClientContract, TransactionClientContract, -} from '@ioc:Adonis/Lucid/Database' - -import { dialects } from '../Dialects' -import { ModelQueryBuilder } from '../Orm/QueryBuilder' -import { TransactionClient } from '../TransactionClient' -import { RawBuilder } from '../Database/StaticBuilder/Raw' -import { RawQueryBuilder } from '../Database/QueryBuilder/Raw' -import { InsertQueryBuilder } from '../Database/QueryBuilder/Insert' -import { ReferenceBuilder } from '../Database/StaticBuilder/Reference' -import { DatabaseQueryBuilder } from '../Database/QueryBuilder/Database' +} from '../../adonis-typings/database.js' + +import { dialects } from '../dialects/index.js' +// import { ModelQueryBuilder } from '../Orm/QueryBuilder' +import { TransactionClient } from '../transaction_client/index.js' +import { RawBuilder } from '../database/static_builder/raw.js' +import { RawQueryBuilder } from '../database/query_builder/raw.js' +import { InsertQueryBuilder } from '../database/query_builder/insert.js' +import { ReferenceBuilder } from '../database/static_builder/reference.js' +import { DatabaseQueryBuilder } from '../database/query_builder/database.js' +import { LucidModel, ModelQueryBuilderContract } from '../../adonis-typings/model.js' +import { + RawQueryBindings, + DatabaseQueryBuilderContract, +} from '../../adonis-typings/querybuilder.js' /** * Query client exposes the API to fetch instance of different query builders @@ -39,41 +41,37 @@ export class QueryClient implements QueryClientContract { /** * Not a transaction client */ - public readonly isTransaction = false + readonly isTransaction = false /** * The dialect in use */ - public dialect: DialectContract = new dialects[this.connection.dialectName]( - this, - this.connection.config - ) - - /** - * The profiler to be used for profiling queries - */ - public profiler?: ProfilerRowContract | ProfilerContract + dialect: DialectContract /** * Name of the connection in use */ - public readonly connectionName = this.connection.name + readonly connectionName: string /** * Is debugging enabled */ - public debug = !!this.connection.config.debug + debug: boolean constructor( - public readonly mode: 'dual' | 'write' | 'read', + public mode: 'dual' | 'write' | 'read', private connection: ConnectionContract, - public emitter: EmitterContract - ) {} + public emitter: Emitter + ) { + this.debug = !!this.connection.config.debug + this.connectionName = this.connection.name + this.dialect = new dialects[this.connection.dialectName](this, this.connection.config) + } /** * Returns schema instance for the write client */ - public get schema() { + get schema(): Knex.SchemaBuilder { return this.getWriteClient().schema } @@ -81,7 +79,7 @@ export class QueryClient implements QueryClientContract { * Returns the read client. The readClient is optional, since we can get * an instance of [[QueryClient]] with a sticky write client. */ - public getReadClient(): Knex { + getReadClient(): Knex { if (this.mode === 'read' || this.mode === 'dual') { return this.connection.readClient! } @@ -92,75 +90,87 @@ export class QueryClient implements QueryClientContract { /** * Returns the write client */ - public getWriteClient(): Knex { + getWriteClient(): Knex { if (this.mode === 'write' || this.mode === 'dual') { return this.connection.client! } throw new Exception( 'Write client is not available for query client instantiated in read mode', - 500, - 'E_RUNTIME_EXCEPTION' + { + status: 500, + code: 'E_RUNTIME_EXCEPTION', + } ) } /** * Truncate table */ - public async truncate(table: string, cascade: boolean = false): Promise { + async truncate(table: string, cascade?: boolean | undefined): Promise { await this.dialect.truncate(table, cascade) } /** * Get information for a table columns */ - public async columnsInfo(table: string, column?: string): Promise { - const result = await this.getWriteClient() - .table(table) - .columnInfo(column ? (column as any) : undefined) + columnsInfo(table: string): Promise<{ [column: string]: Knex.ColumnInfo }> + columnsInfo(table: string, column: string): Promise + async columnsInfo( + table: unknown, + column?: unknown + ): Promise<{ [column: string]: Knex.ColumnInfo } | Knex.ColumnInfo> { + const query = this.getWriteClient().table(table as string) + + if (column) { + query.columnInfo(column as string) + } else { + query.columnInfo() + } + const result = await query return result } /** * Returns an array of table names */ - public async getAllTables(schemas?: string[]): Promise { + async getAllTables(schemas?: string[] | undefined): Promise { return this.dialect.getAllTables(schemas) } /** * Returns an array of all views names */ - public async getAllViews(schemas?: string[]): Promise { + async getAllViews(schemas?: string[] | undefined): Promise { return this.dialect.getAllViews(schemas) } /** * Returns an array of all types names */ - public async getAllTypes(schemas?: string[]): Promise { + async getAllTypes(schemas?: string[] | undefined): Promise { return this.dialect.getAllTypes(schemas) } /** * Drop all tables inside database */ - public async dropAllTables(schemas?: string[]): Promise { + async dropAllTables(schemas?: string[] | undefined): Promise { return this.dialect.dropAllTables(schemas || ['public']) } /** * Drop all views inside the database */ - public async dropAllViews(schemas?: string[]): Promise { + async dropAllViews(schemas?: string[] | undefined): Promise { return this.dialect.dropAllViews(schemas || ['public']) } /** * Drop all custom types inside the database */ - public async dropAllTypes(schemas?: string[]): Promise { + async dropAllTypes(schemas?: string[] | undefined): Promise { return this.dialect.dropAllTypes(schemas || ['public']) } @@ -168,12 +178,12 @@ export class QueryClient implements QueryClientContract { * Returns an instance of a transaction. Each transaction will * query and hold a single connection for all queries. */ - public async transaction( + async transaction( callback?: | { isolationLevel?: IsolationLevels } | ((trx: TransactionClientContract) => Promise), options?: { isolationLevel?: IsolationLevels } - ): Promise { + ): Promise { const trx = await this.getWriteClient().transaction(options) const transaction = new TransactionClient( trx, @@ -183,12 +193,6 @@ export class QueryClient implements QueryClientContract { this.emitter ) - /** - * Always make sure to pass the profiler and emitter down to the transaction - * client as well - */ - transaction.profiler = this.profiler?.create('trx:begin', { state: 'begin' }) - /** * Self managed transaction */ @@ -211,7 +215,7 @@ export class QueryClient implements QueryClientContract { * created from the `write` client, so before executing the query, you * may want to decide which client to use. */ - public knexQuery(): Knex.QueryBuilder { + knexQuery(): Knex.QueryBuilder { return this.connection.client!.queryBuilder() } @@ -220,36 +224,37 @@ export class QueryClient implements QueryClientContract { * created from the `write` client, so before executing the query, you * may want to decide which client to use. */ - public knexRawQuery(sql: string, bindings?: any): Knex.Raw { + knexRawQuery(sql: string, bindings?: RawQueryBindings | undefined): Knex.Raw { return bindings ? this.connection.client!.raw(sql, bindings) : this.connection.client!.raw(sql) } /** * Returns a query builder instance for a given model. */ - public modelQuery(model: any): any { - return new ModelQueryBuilder(this.knexQuery(), model, this) + modelQuery(model: T): ModelQueryBuilderContract { + // modelQuery(model: any): any { + // return new ModelQueryBuilder(this.knexQuery(), model, this) } /** * Returns instance of a query builder for selecting, updating * or deleting rows */ - public query(): any { + query(): DatabaseQueryBuilderContract { return new DatabaseQueryBuilder(this.knexQuery(), this) } /** * Returns instance of a query builder for inserting rows */ - public insertQuery(): any { + insertQuery(): any { return new InsertQueryBuilder(this.getWriteClient().queryBuilder(), this) } /** * Returns instance of raw query builder */ - public rawQuery(sql: any, bindings?: any): any { + rawQuery(sql: any, bindings?: any): any { return new RawQueryBuilder(this.connection.client!.raw(sql, bindings), this) } @@ -258,21 +263,21 @@ export class QueryClient implements QueryClientContract { * cannot be executed. Use `rawQuery`, if you want to execute * queries raw queries. */ - public raw(sql: string, bindings?: any) { + raw(sql: string, bindings?: any) { return new RawBuilder(sql, bindings) } /** * Returns reference builder. */ - public ref(reference: string) { + ref(reference: string) { return new ReferenceBuilder(reference, this.getReadClient().client) } /** * Returns instance of a query builder and selects the table */ - public from(table: any): any { + from(table: any): any { return this.query().from(table) } @@ -280,21 +285,21 @@ export class QueryClient implements QueryClientContract { * Returns instance of a query builder and selects the table * for an insert query */ - public table(table: any): any { + table(table: any): any { return this.insertQuery().table(table) } /** * Get advisory lock on the selected connection */ - public getAdvisoryLock(key: string, timeout?: number): any { + getAdvisoryLock(key: string, timeout?: number): any { return this.dialect.getAdvisoryLock(key, timeout) } /** * Release advisory lock */ - public releaseAdvisoryLock(key: string): any { + releaseAdvisoryLock(key: string): any { return this.dialect.releaseAdvisoryLock(key) } } diff --git a/src/QueryReporter/index.ts b/src/query_reporter/index.ts similarity index 65% rename from src/QueryReporter/index.ts rename to src/query_reporter/index.ts index bbed6bb8..691236bb 100644 --- a/src/QueryReporter/index.ts +++ b/src/query_reporter/index.ts @@ -7,8 +7,7 @@ * file that was distributed with this source code. */ -import { ProfilerActionContract } from '@ioc:Adonis/Core/Profiler' -import { QueryClientContract, TransactionClientContract } from '@ioc:Adonis/Lucid/Database' +import { QueryClientContract, TransactionClientContract } from '../../adonis-typings/database.js' /** * Used for reporting queries using the profiler and the event @@ -17,7 +16,6 @@ import { QueryClientContract, TransactionClientContract } from '@ioc:Adonis/Luci export class QueryReporter { private eventName = 'db:query' private startTime: [number, number] | undefined - private profilerAction: ProfilerActionContract | undefined private isReady = false constructor( @@ -36,27 +34,6 @@ export class QueryReporter { this.startTime = process.hrtime() } - /** - * Init the profiler action when client has profiler attached - * to it - */ - private initProfilerAction() { - if (!this.client.profiler) { - return - } - this.profilerAction = this.client.profiler.profile(this.eventName, this.data) - } - - /** - * Commit the profiler action with optional error - */ - private commitProfilerAction(error?: Error) { - if (!this.profilerAction) { - return - } - error ? this.profilerAction.end({ error }) : this.profilerAction.end() - } - /** * Emit the query with duration */ @@ -73,22 +50,20 @@ export class QueryReporter { * Begin query reporting. Data passed to this method will * overwrite the existing data object */ - public begin(data?: any): this { + begin(data?: any): this { this.isReady = true this.data = data || this.data this.initStartTime() - this.initProfilerAction() return this } /** * End query reporting */ - public end(error?: Error) { + end(error?: Error) { if (!this.isReady) { return } - this.commitProfilerAction(error) this.emitQueryEvent(error) } } diff --git a/src/QueryRunner/index.ts b/src/query_runner/index.ts similarity index 86% rename from src/QueryRunner/index.ts rename to src/query_runner/index.ts index 707086ba..c771ebf1 100644 --- a/src/QueryRunner/index.ts +++ b/src/query_runner/index.ts @@ -9,8 +9,8 @@ import { Knex } from 'knex' import { Exception } from '@poppinss/utils' -import { QueryClientContract, TransactionClientContract } from '@ioc:Adonis/Lucid/Database' -import { QueryReporter } from '../QueryReporter' +import { QueryReporter } from '../query_reporter/index.js' +import { QueryClientContract, TransactionClientContract } from '../../adonis-typings/database.js' /** * Query runner exposes the API for executing knex query builder by using the @@ -19,13 +19,15 @@ import { QueryReporter } from '../QueryReporter' * Also it will emit the query data and profile the queries as well. */ export class QueryRunner { - private reporter = new QueryReporter(this.client, this.debug, this.logData) + private reporter: QueryReporter constructor( private client: QueryClientContract | TransactionClientContract, private debug: boolean, private logData: any - ) {} + ) { + this.reporter = new QueryReporter(this.client, this.debug, this.logData) + } /** * Is query dialect using sqlite database or not @@ -39,14 +41,14 @@ export class QueryRunner { * `useTransaction` method */ private isInTransaction(query: Knex.QueryBuilder | Knex.Raw) { - return query['client'].transacting + return (query as any)['client'].transacting } /** * Find if query is a write query or not. */ private isWriteQuery(query: Knex.QueryBuilder | Knex.Raw) { - return ['update', 'del', 'delete', 'insert'].includes(query['_method']) + return ['update', 'del', 'delete', 'insert'].includes((query as any)['_method']) } /** @@ -80,7 +82,7 @@ export class QueryRunner { * toSQL too many times and also get the actual time it took to * execute the query */ - query['once']('query', (sql: any) => this.reporter.begin({ ...this.logData, ...sql })) + ;(query as any)['once']('query', (sql: any) => this.reporter.begin({ ...this.logData, ...sql })) const [error, result] = await this.executeQuery(query) this.reporter.end(error) @@ -110,7 +112,7 @@ export class QueryRunner { * toSQL too many times and also get the actual time it took to * execute the query */ - query['once']('query', (sql: any) => this.reporter.begin({ ...this.logData, ...sql })) + ;(query as any)['once']('query', (sql: any) => this.reporter.begin({ ...this.logData, ...sql })) /** * Execute query and report event and profiler data @@ -135,7 +137,7 @@ export class QueryRunner { /** * Run query by managing its life-cycle */ - public async run(query: Knex.QueryBuilder | Knex.Raw) { + async run(query: Knex.QueryBuilder | Knex.Raw) { /** * We execute the queries using transaction or using sqlite database * directly. diff --git a/src/TransactionClient/index.ts b/src/transaction_client/index.ts similarity index 66% rename from src/TransactionClient/index.ts rename to src/transaction_client/index.ts index 5dc1c15c..00751a2f 100644 --- a/src/TransactionClient/index.ts +++ b/src/transaction_client/index.ts @@ -7,25 +7,22 @@ * file that was distributed with this source code. */ -/// - import { Knex } from 'knex' -import { EventEmitter } from 'events' -import { Hooks } from '@poppinss/hooks' -import { EmitterContract } from '@ioc:Adonis/Core/Event' -import { ProfilerRowContract } from '@ioc:Adonis/Core/Profiler' +import Hooks from '@poppinss/hooks' +import { EventEmitter } from 'node:events' +import type { Emitter } from '@adonisjs/core/events' import { IsolationLevels, DialectContract, TransactionClientContract, -} from '@ioc:Adonis/Lucid/Database' +} from '../../adonis-typings/database.js' -import { ModelQueryBuilder } from '../Orm/QueryBuilder' -import { RawBuilder } from '../Database/StaticBuilder/Raw' -import { RawQueryBuilder } from '../Database/QueryBuilder/Raw' -import { InsertQueryBuilder } from '../Database/QueryBuilder/Insert' -import { ReferenceBuilder } from '../Database/StaticBuilder/Reference' -import { DatabaseQueryBuilder } from '../Database/QueryBuilder/Database' +import { RawBuilder } from '../database/static_builder/raw.js' +// import { ModelQueryBuilder } from '../Orm/QueryBuilder/index.js' +import { RawQueryBuilder } from '../database/query_builder/raw.js' +import { InsertQueryBuilder } from '../database/query_builder/insert.js' +import { ReferenceBuilder } from '../database/static_builder/reference.js' +import { DatabaseQueryBuilder } from '../database/query_builder/database.js' /** * Transaction uses a dedicated connection from the connection pool @@ -35,27 +32,22 @@ export class TransactionClient extends EventEmitter implements TransactionClient /** * Always true */ - public isTransaction: true = true + isTransaction: true = true /** * Transactions are always in write mode, since they always needs * the primary connection */ - public mode: 'dual' = 'dual' - - /** - * The profiler to be used for profiling queries - */ - public profiler?: ProfilerRowContract + mode: 'dual' = 'dual' - private hooks = new Hooks() + private hooks = new Hooks() constructor( public knexClient: Knex.Transaction, public dialect: DialectContract, public connectionName: string, public debug: boolean, - public emitter: EmitterContract + public emitter: Emitter ) { super() @@ -64,20 +56,20 @@ export class TransactionClient extends EventEmitter implements TransactionClient * testing, it is common to generate more than 10 model instances and hence * the max listeners limit needs to be removed */ - this.setMaxListeners(Infinity) + this.setMaxListeners(Number.POSITIVE_INFINITY) } /** * Whether or not transaction has been completed */ - public get isCompleted() { + get isCompleted() { return this.knexClient.isCompleted() } /** * Returns schema instance for the write client */ - public get schema() { + get schema() { return this.getWriteClient().schema } @@ -85,7 +77,7 @@ export class TransactionClient extends EventEmitter implements TransactionClient * Returns the read client. Which is just a single client in case * of transactions */ - public getReadClient() { + getReadClient() { return this.knexClient } @@ -93,14 +85,14 @@ export class TransactionClient extends EventEmitter implements TransactionClient * Returns the write client. Which is just a single client in case * of transactions */ - public getWriteClient() { + getWriteClient() { return this.knexClient } /** * Truncate tables inside a transaction */ - public async truncate(table: string, cascade: boolean = false): Promise { + async truncate(table: string, cascade: boolean = false): Promise { await this.dialect.truncate(table, cascade) } @@ -108,7 +100,7 @@ export class TransactionClient extends EventEmitter implements TransactionClient * Get columns info inside a transaction. You won't need it here, however * added for API compatibility with the [[QueryClient]] class */ - public async columnsInfo(table: string, column?: string): Promise { + async columnsInfo(table: string, column?: string): Promise { const query = this.knexClient.select(table) const result = await (column ? query.columnInfo(column) : query.columnInfo()) return result @@ -117,49 +109,49 @@ export class TransactionClient extends EventEmitter implements TransactionClient /** * Returns an array of table names */ - public async getAllTables(schemas?: string[]): Promise { + async getAllTables(schemas?: string[]): Promise { return this.dialect.getAllTables(schemas) } /** * Returns an array of all views names */ - public async getAllViews(schemas?: string[]): Promise { + async getAllViews(schemas?: string[]): Promise { return this.dialect.getAllViews(schemas) } /** * Returns an array of all types names */ - public async getAllTypes(schemas?: string[]): Promise { + async getAllTypes(schemas?: string[]): Promise { return this.dialect.getAllTypes(schemas) } /** * Drop all tables inside database */ - public async dropAllTables(schemas?: string[]): Promise { + async dropAllTables(schemas?: string[]): Promise { return this.dialect.dropAllTables(schemas || ['public']) } /** * Drop all views inside the database */ - public async dropAllViews(schemas?: string[]): Promise { + async dropAllViews(schemas?: string[]): Promise { return this.dialect.dropAllViews(schemas || ['public']) } /** * Drop all custom types inside the database */ - public async dropAllTypes(schemas?: string[]): Promise { + async dropAllTypes(schemas?: string[]): Promise { return this.dialect.dropAllTypes(schemas || ['public']) } /** * Get a new query builder instance */ - public knexQuery(): Knex.QueryBuilder { + knexQuery(): Knex.QueryBuilder { return this.knexClient.queryBuilder() } @@ -168,7 +160,7 @@ export class TransactionClient extends EventEmitter implements TransactionClient * created from the `write` client, so before executing the query, you * may want to decide which client to use. */ - public knexRawQuery(sql: string, bindings?: any): Knex.Raw { + knexRawQuery(sql: string, bindings?: any): Knex.Raw { return bindings ? this.knexClient.raw(sql, bindings) : this.knexClient.raw(sql) } @@ -177,28 +169,28 @@ export class TransactionClient extends EventEmitter implements TransactionClient * and `profiler` is passed down to the model, so that it continue * using the same options */ - public modelQuery(model: any): any { - return new ModelQueryBuilder(this.knexQuery(), model, this) + modelQuery(model: any): any { + // return new ModelQueryBuilder(this.knexQuery(), model, this) } /** * Get a new query builder instance */ - public query(): any { + query(): any { return new DatabaseQueryBuilder(this.knexQuery(), this) } /** * Get a new insert query builder instance */ - public insertQuery(): any { + insertQuery(): any { return new InsertQueryBuilder(this.knexQuery(), this) } /** * Execute raw query on transaction */ - public rawQuery(sql: any, bindings?: any): any { + rawQuery(sql: any, bindings?: any): any { return new RawQueryBuilder(this.knexClient.raw(sql, bindings), this) } @@ -207,21 +199,21 @@ export class TransactionClient extends EventEmitter implements TransactionClient * cannot be executed. Use `rawQuery`, if you want to execute * queries raw queries. */ - public raw(sql: string, bindings?: any) { + raw(sql: string, bindings?: any) { return new RawBuilder(sql, bindings) } /** * Returns reference builder. */ - public ref(reference: string) { + ref(reference: string) { return new ReferenceBuilder(reference, this.knexClient.client) } /** * Returns another instance of transaction with save point */ - public async transaction( + async transaction( callback?: | { isolationLevel?: IsolationLevels } | ((trx: TransactionClientContract) => Promise), @@ -236,11 +228,6 @@ export class TransactionClient extends EventEmitter implements TransactionClient this.emitter ) - /** - * Always make sure to pass the profiler down the chain - */ - transaction.profiler = this.profiler?.create('trx:begin', { state: 'begin' }) - /** * Self managed transaction */ @@ -261,78 +248,74 @@ export class TransactionClient extends EventEmitter implements TransactionClient /** * Same as [[Transaction.query]] but also selects the table */ - public from(table: any): any { + from(table: any): any { return this.query().from(table) } /** * Same as [[Transaction.insertTable]] but also selects the table */ - public table(table: any): any { + table(table: any): any { return this.insertQuery().table(table) } /** * Register after commit or rollback hook */ - public after(event: 'rollback' | 'commit', handler: () => void | Promise) { - this.hooks.add('after', event, handler) + after(event: 'rollback' | 'commit', handler: () => void | Promise) { + this.hooks.add(`after:${event}`, handler) return this } /** * Commit the transaction */ - public async commit() { + async commit() { try { await this.knexClient.commit() - this.profiler?.end({ state: 'commit' }) this.emit('commit', this) this.removeAllListeners() } catch (error) { - this.profiler?.end({ state: 'commit' }) this.removeAllListeners() throw error } try { - await this.hooks.exec('after', 'commit') - this.hooks.clear('after') + await this.hooks.runner('after:commit').run() + this.hooks.clear('after:commit') } catch {} } /** * Rollback the transaction */ - public async rollback() { + async rollback() { try { await this.knexClient.rollback() - this.profiler?.end({ state: 'rollback' }) this.emit('rollback', this) this.removeAllListeners() } catch (error) { - this.profiler?.end({ state: 'rollback' }) this.removeAllListeners() throw error } try { - await this.hooks.exec('after', 'rollback') - this.hooks.clear('after') + await this.hooks.runner('after:rollback').run() + this.hooks.clear('after:rollback') } catch {} } /** * Get advisory lock on the selected connection */ - public getAdvisoryLock(key: string, timeout?: number): any { + getAdvisoryLock(key: string, timeout?: number): any { return this.dialect.getAdvisoryLock(key, timeout) } /** * Release advisory lock */ - public releaseAdvisoryLock(key: string): any { + releaseAdvisoryLock(key: string): any { return this.dialect.releaseAdvisoryLock(key) } } diff --git a/src/utils/index.ts b/src/utils/index.ts index 00df1ee3..dd8af42f 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -7,23 +7,16 @@ * file that was distributed with this source code. */ -/// - import slash from 'slash' -import { join, extname } from 'path' -import { Exception, esmRequire } from '@poppinss/utils' -import { fsReadAll, resolveDir } from '@poppinss/utils/build/helpers' -import { - LucidRow, - ModelObject, - CherryPickFields, - RelationshipsContract, -} from '@ioc:Adonis/Lucid/Orm' +import { join, extname } from 'node:path' +import { Exception, fsImportAll } from '@poppinss/utils' +import { RelationshipsContract } from '../../adonis-typings/relations.js' +import { LucidRow, ModelObject, CherryPickFields } from '../../adonis-typings/model.js' import { FileNode, QueryClientContract, TransactionClientContract, -} from '@ioc:Adonis/Lucid/Database' +} from '../../adonis-typings/database.js' /** * Ensure that relation is defined @@ -33,7 +26,7 @@ export function ensureRelation( relation?: T ): relation is T { if (!relation) { - throw new Exception(`Cannot process unregistered relationship ${name}`, 500) + throw new Exception(`Cannot process unregistered relationship ${name}`, { status: 500 }) } return true @@ -67,11 +60,10 @@ export function collectValues(payload: any[], key: string, missingCallback: () = */ export function ensureRelationIsBooted(relation: RelationshipsContract) { if (!relation.booted) { - throw new Exception( - 'Relationship is not booted. Make sure to call boot first', - 500, - 'E_RUNTIME_EXCEPTION' - ) + throw new Exception('Relationship is not booted. Make sure to call boot first', { + status: 500, + code: 'E_RUNTIME_EXCEPTION', + }) } } @@ -88,7 +80,7 @@ export function getValue( return ensureValue(model, key, () => { throw new Exception( `Cannot ${action} "${relation.relationName}", value of "${relation.model.name}.${key}" is undefined`, - 500 + { status: 500 } ) }) } @@ -212,54 +204,48 @@ export function normalizeCherryPickObject(fields: CherryPickFields) { /** * Sources files from a given directory */ -export function sourceFiles( +export async function sourceFiles( fromLocation: string, directory: string, naturalSort: boolean ): Promise<{ directory: string; files: FileNode[] }> { - return new Promise((resolve, reject) => { - const absDirectoryPath = resolveDir(fromLocation, directory) - let files = fsReadAll(absDirectoryPath) - - /** - * Sort files - */ - if (naturalSort) { - files = files.sort((a, b) => - a!.localeCompare(b!, undefined, { numeric: true, sensitivity: 'base' }) - ) - } else { - files = files.sort() - } + const absDirectoryPath = join(fromLocation, directory) + let files = await fsImportAll(absDirectoryPath) + + /** + * Sort files + */ + if (naturalSort) { + files = files.sort((a: string, b: string) => + a!.localeCompare(b!, undefined, { numeric: true, sensitivity: 'base' }) + ) + } else { + files = files.sort() + } - try { - resolve({ - directory, - files: files.map((file: string) => { - const name = join(directory, file.replace(RegExp(`${extname(file)}$`), '')) + return { + directory, + files: files.map((file: string) => { + const name = join(directory, file.replace(RegExp(`${extname(file)}$`), '')) - return { - /** - * Absolute path to the file. Needed to ready the schema source - */ - absPath: join(absDirectoryPath, file), + return { + /** + * Absolute path to the file. Needed to ready the schema source + */ + absPath: join(absDirectoryPath, file), - /** - * Normalizing name to always have unix slashes. - */ - name: slash(name), + /** + * Normalizing name to always have unix slashes. + */ + name: slash(name), - /** - * Import schema file - */ - getSource() { - return esmRequire(this.absPath) - }, - } - }), - }) - } catch (error) { - reject(error) - } - }) + /** + * Import schema file + */ + getSource() { + return esmRequire(this.absPath) + }, + } + }), + } } diff --git a/test-helpers/index.ts b/test-helpers/index.ts index a06758af..7606f4cf 100644 --- a/test-helpers/index.ts +++ b/test-helpers/index.ts @@ -7,49 +7,58 @@ * file that was distributed with this source code. */ -/// - import dotenv from 'dotenv' -import { join } from 'path' +import { join } from 'node:path' import { Chance } from 'chance' import knex, { Knex } from 'knex' -import { Filesystem } from '@poppinss/dev-utils' -import { Application } from '@adonisjs/core/build/standalone' +import { Logger } from '@adonisjs/core/logger' +import { Emitter } from '@adonisjs/core/events' +import { AppFactory } from '@adonisjs/core/factories/app' import { ConnectionConfig, - DatabaseContract, ConnectionContract, QueryClientContract, +} from '../adonis-typings/database.js' + +import { RawQueryBuilderContract, InsertQueryBuilderContract, DatabaseQueryBuilderContract, -} from '@ioc:Adonis/Lucid/Database' - -import { ApplicationContract } from '@ioc:Adonis/Core/Application' -import { SchemaConstructorContract } from '@ioc:Adonis/Lucid/Schema' -import { MigratorContract, MigratorOptions } from '@ioc:Adonis/Lucid/Migrator' -import { LucidRow, LucidModel, AdapterContract } from '@ioc:Adonis/Lucid/Orm' +} from '../adonis-typings/querybuilder.js' + +import { MigratorOptions } from '../adonis-typings/migrator.js' +import { LucidRow, LucidModel, AdapterContract } from '../adonis-typings/model.js' + +import { fileURLToPath } from 'node:url' +// import { QueryClient } from '../src/QueryClient/index.js' +import { DefineCallback, FactoryModelContract } from '../adonis-typings/factory.js' +import { EventsList } from '../adonis-typings/events.js' +import { QueryClient } from '../src/query_client/index.js' +import { Database } from '../src/database/index.js' +import { DatabaseQueryBuilder } from '../src/database/query_builder/database.js' +import { RawQueryBuilder } from '../src/database/query_builder/raw.js' +import { InsertQueryBuilder } from '../src/database/query_builder/insert.js' + +// import { Schema } from '../src/Schema' +// import { Migrator } from '../src/Migrator' +// import { Adapter } from '../src/Orm/Adapter' +// import { Database } from '../src/Database/index' +// import { QueryClient } from '../src/QueryClient' +// import { BaseModel } from '../src/Orm/BaseModel' +// import { FactoryModel } from '../src/Factory/FactoryModel' +// import { RawQueryBuilder } from '../src/Database/QueryBuilder/Raw' +// import { InsertQueryBuilder } from '../src/Database/QueryBuilder/Insert' +// import { DatabaseQueryBuilder } from '../src/Database/QueryBuilder/Database' -import { - DefineCallback, - FactoryModelContract, - FactoryManagerContract, -} from '@ioc:Adonis/Lucid/Factory' - -import { Schema } from '../src/Schema' -import { Migrator } from '../src/Migrator' -import { Adapter } from '../src/Orm/Adapter' -import { Database } from '../src/Database/index' -import { QueryClient } from '../src/QueryClient' -import { BaseModel } from '../src/Orm/BaseModel' -import { FactoryModel } from '../src/Factory/FactoryModel' -import { RawQueryBuilder } from '../src/Database/QueryBuilder/Raw' -import { InsertQueryBuilder } from '../src/Database/QueryBuilder/Insert' -import { DatabaseQueryBuilder } from '../src/Database/QueryBuilder/Database' - -export const fs = new Filesystem(join(__dirname, 'tmp')) dotenv.config() +export const APP_ROOT = new URL('./tmp', import.meta.url) +export const SQLITE_BASE_PATH = fileURLToPath(APP_ROOT) + +export const app = new AppFactory().create(APP_ROOT, () => {}) +export const emitter = new Emitter(app) +export const logger = new Logger({}) +export const createEmitter = () => new Emitter(app) /** * Returns config based upon DB set in environment variables @@ -60,7 +69,7 @@ export function getConfig(): ConnectionConfig { return { client: 'sqlite3', connection: { - filename: join(fs.basePath, 'db.sqlite'), + filename: join(SQLITE_BASE_PATH, 'db.sqlite'), }, useNullAsDefault: true, debug: !!process.env.DEBUG, @@ -69,7 +78,7 @@ export function getConfig(): ConnectionConfig { return { client: 'better-sqlite3', connection: { - filename: join(fs.basePath, 'better-sqlite-db.sqlite'), + filename: join(SQLITE_BASE_PATH, 'better-sqlite-db.sqlite'), }, useNullAsDefault: true, debug: !!process.env.DEBUG, @@ -86,7 +95,7 @@ export function getConfig(): ConnectionConfig { connection: { host: process.env.MYSQL_HOST as string, port: Number(process.env.MYSQL_PORT), - database: process.env.DB_NAME as string, + database: process.env.MYSQL_DATABASE as string, user: process.env.MYSQL_USER as string, password: process.env.MYSQL_PASSWORD as string, }, @@ -97,11 +106,11 @@ export function getConfig(): ConnectionConfig { return { client: 'mysql2', connection: { - host: process.env.MYSQL_LEGACY_HOST as string, - port: Number(process.env.MYSQL_LEGACY_PORT), - database: process.env.DB_NAME as string, - user: process.env.MYSQL_LEGACY_USER as string, - password: process.env.MYSQL_LEGACY_PASSWORD as string, + host: process.env.LEGACY_MYSQL_HOST as string, + port: Number(process.env.LEGACY_MYSQL_PORT), + database: process.env.LEGACY_MYSQL_DATABASE as string, + user: process.env.LEGACY_MYSQL_USER as string, + password: process.env.LEGACY_MYSQL_PASSWORD as string, }, debug: !!process.env.DEBUG, useNullAsDefault: true, @@ -112,7 +121,7 @@ export function getConfig(): ConnectionConfig { connection: { host: process.env.PG_HOST as string, port: Number(process.env.PG_PORT), - database: process.env.DB_NAME as string, + database: process.env.PG_DATABASE as string, user: process.env.PG_USER as string, password: process.env.PG_PASSWORD as string, }, @@ -124,7 +133,8 @@ export function getConfig(): ConnectionConfig { client: 'mssql', connection: { user: process.env.MSSQL_USER as string, - server: process.env.MSSQL_SERVER as string, + port: Number(process.env.MSSQL_PORT! as string), + server: process.env.MSSQL_HOST as string, password: process.env.MSSQL_PASSWORD as string, database: 'master', options: { @@ -146,11 +156,7 @@ export function getConfig(): ConnectionConfig { * Does base setup by creating databases */ export async function setup(destroyDb: boolean = true) { - if (['sqlite', 'better_sqlite'].includes(process.env.DB!)) { - await fs.ensureRoot() - } - - const db = knex(Object.assign({}, getConfig(), { debug: false })) + const db = knex.knex(Object.assign({}, getConfig(), { debug: false })) const hasUsersTable = await db.schema.hasTable('users') if (!hasUsersTable) { @@ -300,7 +306,7 @@ export async function setup(destroyDb: boolean = true) { * Does cleanup removes database */ export async function cleanup(customTables?: string[]) { - const db = knex(Object.assign({}, getConfig(), { debug: false })) + const db = knex.knex(Object.assign({}, getConfig(), { debug: false })) if (customTables) { for (let table of customTables) { @@ -332,7 +338,7 @@ export async function cleanup(customTables?: string[]) { * Reset database tables */ export async function resetTables() { - const db = knex(Object.assign({}, getConfig(), { debug: false })) + const db = knex.knex(Object.assign({}, getConfig(), { debug: false })) await db.table('users').truncate() await db.table('uuid_users').truncate() await db.table('follows').truncate() @@ -354,14 +360,10 @@ export async function resetTables() { */ export function getQueryClient( connection: ConnectionContract, - application: ApplicationContract, + eventEmitter?: Emitter, mode?: 'read' | 'write' | 'dual' ): QueryClientContract { - return new QueryClient( - mode || 'dual', - connection, - application.container.use('Adonis/Core/Event') - ) as QueryClientContract + return new QueryClient(mode || 'dual', connection, eventEmitter || emitter) as QueryClientContract } /** @@ -398,7 +400,7 @@ export function getInsertBuilder(client: QueryClientContract) { /** * Returns the database instance */ -export function getDb(application: ApplicationContract) { +export function getDb() { const config = { connection: 'primary', connections: { @@ -407,12 +409,7 @@ export function getDb(application: ApplicationContract) { }, } - return new Database( - config, - application.container.use('Adonis/Core/Logger'), - application.container.use('Adonis/Core/Profiler'), - application.container.use('Adonis/Core/Event') - ) as DatabaseContract + return new Database(config, logger, createEmitter()) } /** @@ -448,7 +445,7 @@ export function getFactoryModel() { * Fake adapter implementation */ export class FakeAdapter implements AdapterContract { - public operations: any[] = [] + operations: any[] = [] private _handlers: any = { insert: null, @@ -469,7 +466,7 @@ export class FakeAdapter implements AdapterContract { } } - public query(): any { + query(): any { return { client: { dialect: { @@ -479,44 +476,44 @@ export class FakeAdapter implements AdapterContract { } } - public on(action: 'insert', handler: (model: LucidRow, attributes: any) => void): void - public on(action: 'update', handler: (model: LucidRow, attributes: any) => void): void - public on(action: 'delete', handler: (model: LucidRow) => void): void - public on(action: 'refresh', handler: (model: LucidRow) => void): void - public on(action: 'find', handler: (model: LucidModel, options?: any) => void): void - public on(action: 'findAll', handler: (model: LucidModel, options?: any) => void): void - public on( + on(action: 'insert', handler: (model: LucidRow, attributes: any) => void): void + on(action: 'update', handler: (model: LucidRow, attributes: any) => void): void + on(action: 'delete', handler: (model: LucidRow) => void): void + on(action: 'refresh', handler: (model: LucidRow) => void): void + on(action: 'find', handler: (model: LucidModel, options?: any) => void): void + on(action: 'findAll', handler: (model: LucidModel, options?: any) => void): void + on( action: string, handler: ((model: LucidRow, attributes?: any) => void) | ((model: LucidModel) => void) ): void { this._handlers[action] = handler } - public modelClient(): any {} + modelClient(): any {} - public modelConstructorClient(): any {} + modelConstructorClient(): any {} - public async insert(instance: LucidRow, attributes: any) { + async insert(instance: LucidRow, attributes: any) { this.operations.push({ type: 'insert', instance, attributes }) return this._invokeHandler('insert', instance, attributes) } - public async refresh(instance: LucidRow) { + async refresh(instance: LucidRow) { this.operations.push({ type: 'refresh', instance }) return this._invokeHandler('refresh', instance) } - public async delete(instance: LucidRow) { + async delete(instance: LucidRow) { this.operations.push({ type: 'delete', instance }) return this._invokeHandler('delete', instance) } - public async update(instance: LucidRow, attributes: any) { + async update(instance: LucidRow, attributes: any) { this.operations.push({ type: 'update', instance, attributes }) return this._invokeHandler('update', instance, attributes) } - public async find(model: LucidModel, key: string, value: any, options?: any) { + async find(model: LucidModel, key: string, value: any, options?: any) { const payload: any = { type: 'find', model, key, value } if (options) { payload.options = options @@ -526,7 +523,7 @@ export class FakeAdapter implements AdapterContract { return this._invokeHandler('find', model, options) } - public async findAll(model: LucidModel, options?: any) { + async findAll(model: LucidModel, options?: any) { const payload: any = { type: 'findAll', model } if (options) { payload.options = options diff --git a/test/connection/connection.spec.ts b/test/connection/connection.spec.ts index 14604321..36f06551 100644 --- a/test/connection/connection.spec.ts +++ b/test/connection/connection.spec.ts @@ -7,27 +7,21 @@ * file that was distributed with this source code. */ -/// - +import { Knex } from 'knex' import { test } from '@japa/runner' -import { MysqlConfig } from '@ioc:Adonis/Lucid/Database' - -import { Connection } from '../../src/Connection' -import { fs, getConfig, setup, cleanup, resetTables, setupApplication } from '../../test-helpers' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' +import { MysqlConfig } from '../../adonis-typings/database.js' -let app: ApplicationContract +import { Connection } from '../../src/connection/index.js' +import { setup, cleanup, getConfig, resetTables, logger } from '../../test-helpers/index.js' if (process.env.DB !== 'sqlite') { test.group('Connection | config', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) test('get write config by merging values from connection', ({ assert }) => { @@ -47,11 +41,11 @@ if (process.env.DB !== 'sqlite') { }, } - const connection = new Connection('primary', config, app.logger) + const connection = new Connection('primary', config, logger) const writeConfig = connection['getWriteConfig']() assert.equal(writeConfig.client, config.client) - assert.equal(writeConfig.connection!['host'], '10.0.0.1') + assert.equal((writeConfig.connection as Knex.ConnectionConfig).host, '10.0.0.1') }) test('get read config by merging values from connection', ({ assert }) => { @@ -71,7 +65,7 @@ if (process.env.DB !== 'sqlite') { }, } - const connection = new Connection('primary', config, app.logger) + const connection = new Connection('primary', config, logger) const readConfig = connection['getReadConfig']() assert.equal(readConfig.client, config.client) @@ -81,13 +75,11 @@ if (process.env.DB !== 'sqlite') { test.group('Connection | setup', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { @@ -95,13 +87,12 @@ test.group('Connection | setup', (group) => { }) test('do not instantiate knex unless connect is called', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) - + const connection = new Connection('primary', getConfig(), logger) assert.isUndefined(connection.client) }) test('instantiate knex when connect is invoked', async ({ assert }, done) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.on('connect', async () => { assert.isDefined(connection.client!) assert.equal(connection.pool!.numUsed(), 0) @@ -113,16 +104,16 @@ test.group('Connection | setup', (group) => { }).waitForDone() test('on disconnect destroy knex', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() await connection.disconnect() assert.isUndefined(connection.client) - assert.isUndefined(connection['_readClient']) + assert.isUndefined(connection.readClient) }) test('on disconnect emit disconnect event', async ({ assert }, done) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() connection.on('disconnect', () => { @@ -139,7 +130,7 @@ test.group('Connection | setup', (group) => { const connection = new Connection( 'primary', Object.assign({}, getConfig(), { client: null }), - app.logger + logger ) connection.on('error', ({ message }) => { @@ -163,12 +154,12 @@ if (process.env.DB === 'mysql') { config.connection!.charset = 'utf-8' config.connection!.typeCast = false - const connection = new Connection('primary', config, app.logger) + const connection = new Connection('primary', config, logger) connection.connect() - assert.equal(connection.client!['context'].client.constructor.name, 'Client_MySQL2') - assert.equal(connection.client!['context'].client.config.connection.charset, 'utf-8') - assert.equal(connection.client!['context'].client.config.connection.typeCast, false) + assert.equal((connection.client as any)['context'].client.constructor.name, 'Client_MySQL2') + assert.equal((connection.client as any)['context'].client.config.connection.charset, 'utf-8') + assert.equal((connection.client as any)['context'].client.config.connection.typeCast, false) await connection.disconnect() }) }) @@ -176,17 +167,15 @@ if (process.env.DB === 'mysql') { test.group('Health Checks', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) test('get healthcheck report for healthy connection', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() const report = await connection.getReport() @@ -208,7 +197,7 @@ test.group('Health Checks', (group) => { host: 'bad-host', }, }), - app.logger + logger ) connection.connect() @@ -235,7 +224,7 @@ test.group('Health Checks', (group) => { }, }, }), - app.logger + logger ) connection.connect() diff --git a/test/connection/connection-manager.spec.ts b/test/connection/connection_manager.spec.ts similarity index 77% rename from test/connection/connection-manager.spec.ts rename to test/connection/connection_manager.spec.ts index adedbfaa..72488aad 100644 --- a/test/connection/connection-manager.spec.ts +++ b/test/connection/connection_manager.spec.ts @@ -7,34 +7,32 @@ * file that was distributed with this source code. */ -/// - +import { join } from 'node:path' import { test } from '@japa/runner' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -import { Connection } from '../../src/Connection' -import { ConnectionManager } from '../../src/Connection/Manager' -import { fs, getConfig, setup, cleanup, mapToObj, setupApplication } from '../../test-helpers' -import { join } from 'path' -let app: ApplicationContract +import { Connection } from '../../src/connection/index.js' +import { ConnectionManager } from '../../src/connection/manager.js' +import { + getConfig, + setup, + cleanup, + mapToObj, + logger, + createEmitter, + SQLITE_BASE_PATH, +} from '../../test-helpers/index.js' test.group('ConnectionManager', (group) => { group.setup(async () => { await setup() }) - group.each.setup(async () => { - app = await setupApplication() - }) - group.teardown(async () => { await cleanup() - await fs.cleanup() }) test('do not connect until connect is called', async ({ assert }) => { - const manager = new ConnectionManager(app.logger, app.container.use('Adonis/Core/Event')) + const manager = new ConnectionManager(logger, createEmitter()) manager.add('primary', getConfig()) assert.isTrue(manager.has('primary')) @@ -43,7 +41,7 @@ test.group('ConnectionManager', (group) => { }) test('connect and set its state to open', async ({ assert }) => { - const manager = new ConnectionManager(app.logger, app.container.use('Adonis/Core/Event')) + const manager = new ConnectionManager(logger, createEmitter()) manager.add('primary', getConfig()) manager.connect('primary') @@ -53,7 +51,7 @@ test.group('ConnectionManager', (group) => { }) test('on disconnect set state to closed', async ({ assert }) => { - const manager = new ConnectionManager(app.logger, app.container.use('Adonis/Core/Event')) + const manager = new ConnectionManager(logger, createEmitter()) manager.add('primary', getConfig()) manager.connect('primary') @@ -64,7 +62,7 @@ test.group('ConnectionManager', (group) => { }) test('add duplicate connection must be a noop', async ({ assert }) => { - const manager = new ConnectionManager(app.logger, app.container.use('Adonis/Core/Event')) + const manager = new ConnectionManager(logger, createEmitter()) manager.add('primary', getConfig()) manager.connect('primary') @@ -74,7 +72,7 @@ test.group('ConnectionManager', (group) => { }) test('patch config when connection is not in open state', async ({ assert }) => { - const manager = new ConnectionManager(app.logger, app.container.use('Adonis/Core/Event')) + const manager = new ConnectionManager(logger, createEmitter()) manager.add('primary', getConfig()) manager.connect('primary') @@ -86,10 +84,10 @@ test.group('ConnectionManager', (group) => { }) test('ignore multiple calls to `connect` on a single connection', async (_, done) => { - const emitter = app.container.use('Adonis/Core/Event') let counter = 0 - const manager = new ConnectionManager(app.logger, emitter) + const emitter = createEmitter() + const manager = new ConnectionManager(logger, emitter) manager.add('primary', getConfig()) emitter.on('db:connection:connect', () => { @@ -108,9 +106,8 @@ test.group('ConnectionManager', (group) => { test('releasing a connection must close it first', async ({ assert }) => { assert.plan(2) - const emitter = app.container.use('Adonis/Core/Event') - - const manager = new ConnectionManager(app.logger, emitter) + const emitter = createEmitter() + const manager = new ConnectionManager(logger, emitter) manager.add('primary', getConfig()) manager.connect('primary') @@ -125,8 +122,8 @@ test.group('ConnectionManager', (group) => { test('proxy error event', async ({ assert }, done) => { assert.plan(3) - const emitter = app.container.use('Adonis/Core/Event') - const manager = new ConnectionManager(app.logger, emitter) + const emitter = createEmitter() + const manager = new ConnectionManager(logger, emitter) manager.add('primary', Object.assign({}, getConfig(), { client: null })) emitter.on('db:connection:error', async ([{ message }, connection]) => { @@ -152,8 +149,8 @@ test.group('ConnectionManager', (group) => { let connections: any[] = [] - const emitter = app.container.use('Adonis/Core/Event') - const manager = new ConnectionManager(app.logger, emitter) + const emitter = createEmitter() + const manager = new ConnectionManager(logger, emitter) manager.add('primary', getConfig()) emitter.on('db:connection:disconnect', async (connection) => { @@ -195,7 +192,7 @@ test.group('ConnectionManager', (group) => { test('get health check report for connections that has enabled health checks', async ({ assert, }) => { - const manager = new ConnectionManager(app.logger, app.container.use('Adonis/Core/Event')) + const manager = new ConnectionManager(logger, createEmitter()) manager.add('primary', Object.assign({}, getConfig(), { healthCheck: true })) manager.add('secondary', Object.assign({}, getConfig(), { healthCheck: true })) manager.add('secondary-copy', Object.assign({}, getConfig(), { healthCheck: false })) @@ -205,7 +202,7 @@ test.group('ConnectionManager', (group) => { assert.equal(report.health.message, 'All connections are healthy') assert.lengthOf(report.meta, 2) assert.deepEqual( - report.meta.map(({ connection }) => connection), + report.meta.map((node: any) => node.connection), ['primary', 'secondary'] ) @@ -213,7 +210,7 @@ test.group('ConnectionManager', (group) => { }) test('get health check report when one of the connection is unhealthy', async ({ assert }) => { - const manager = new ConnectionManager(app.logger, app.container.use('Adonis/Core/Event')) + const manager = new ConnectionManager(logger, createEmitter()) manager.add('primary', Object.assign({}, getConfig(), { healthCheck: true })) manager.add( 'secondary', @@ -221,7 +218,7 @@ test.group('ConnectionManager', (group) => { healthCheck: true, connection: ['sqlite', 'better_sqlite'].includes(process.env.DB!) ? { - filename: join(fs.basePath, 'nested', 'db.sqlite'), + filename: join(SQLITE_BASE_PATH, 'nested', 'db.sqlite'), } : { host: 'bad-host', @@ -235,7 +232,7 @@ test.group('ConnectionManager', (group) => { assert.equal(report.health.message, 'One or more connections are not healthy') assert.lengthOf(report.meta, 2) assert.deepEqual( - report.meta.map(({ connection }) => connection), + report.meta.map((node: any) => node.connection), ['primary', 'secondary'] ) await manager.closeAll() diff --git a/test/database/database.spec.ts b/test/database/database.spec.ts index 6904faad..acaf6fad 100644 --- a/test/database/database.spec.ts +++ b/test/database/database.spec.ts @@ -7,25 +7,18 @@ * file that was distributed with this source code. */ -/// - import { test } from '@japa/runner' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -import { Database } from '../../src/Database' -import { fs, getConfig, setup, cleanup, getDb, setupApplication } from '../../test-helpers' -let app: ApplicationContract +import { Database } from '../../src/database/index.js' +import { getConfig, setup, cleanup, logger, createEmitter } from '../../test-helpers/index.js' test.group('Database', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) test('register all connections with the manager', ({ assert }) => { @@ -34,12 +27,7 @@ test.group('Database', (group) => { connections: { primary: getConfig() }, } - const db = new Database( - config, - app.logger, - app.profiler, - app.container.use('Adonis/Core/Event') - ) + const db = new Database(config, logger, createEmitter()) assert.isDefined(db.manager.connections.get('primary')) assert.equal(db.manager.connections.get('primary')!.state, 'registered') @@ -54,8 +42,8 @@ test.group('Database', (group) => { connections: { primary: getConfig() }, } - const emitter = app.container.use('Adonis/Core/Event') - const db = new Database(config, app.logger, app.profiler, emitter) + const emitter = createEmitter() + const db = new Database(config, logger, emitter) emitter.on('db:connection:connect', (connection) => { assert.equal(connection.name, 'primary') done() @@ -73,8 +61,8 @@ test.group('Database', (group) => { connections: { primary: getConfig() }, } - const emitter = app.container.use('Adonis/Core/Event') - const db = new Database(config, app.logger, app.profiler, emitter) + const emitter = createEmitter() + const db = new Database(config, logger, emitter) emitter.on('db:connection:connect', (connection) => { assert.equal(connection.name, 'primary') done() @@ -92,12 +80,7 @@ test.group('Database', (group) => { connections: { primary: getConfig() }, } - const db = new Database( - config, - app.logger, - app.profiler, - app.container.use('Adonis/Core/Event') - ) + const db = new Database(config, logger, createEmitter()) const client = db.connection('primary', { mode: 'write' }) assert.equal(client.mode, 'write') @@ -112,12 +95,7 @@ test.group('Database', (group) => { connections: { primary: getConfig() }, } - const db = new Database( - config, - app.logger, - app.profiler, - app.container.use('Adonis/Core/Event') - ) + const db = new Database(config, logger, createEmitter()) const client = db.connection('primary', { mode: 'read' }) assert.equal(client.mode, 'read') @@ -130,12 +108,7 @@ test.group('Database', (group) => { connections: { primary: getConfig() }, } - const db = new Database( - config, - app.logger, - app.profiler, - app.container.use('Adonis/Core/Event') - ) + const db = new Database(config, logger, createEmitter()) const trx = await db.transaction() assert.equal(trx.mode, 'dual') @@ -151,12 +124,7 @@ test.group('Database', (group) => { connections: { primary: getConfig() }, } - const db = new Database( - config, - app.logger, - app.profiler, - app.container.use('Adonis/Core/Event') - ) + const db = new Database(config, logger, createEmitter()) const result = await db.rawQuery('select 1 + 1') assert.isDefined(result) await db.manager.closeAll() @@ -168,12 +136,7 @@ test.group('Database', (group) => { connections: { primary: getConfig() }, } - const db = new Database( - config, - app.logger, - app.profiler, - app.container.use('Adonis/Core/Event') - ) + const db = new Database(config, logger, createEmitter()) const result = await db.rawQuery('select 1 + 1', [], { mode: 'read' }) assert.isDefined(result) await db.manager.closeAll() @@ -185,47 +148,12 @@ test.group('Database', (group) => { connections: { primary: getConfig() }, } - const db = new Database( - config, - app.logger, - app.profiler, - app.container.use('Adonis/Core/Event') - ) + const db = new Database(config, logger, createEmitter()) const result = await db.rawQuery('select 1 + 1', [], { mode: 'write' }) assert.isDefined(result) await db.manager.closeAll() }) - test('pass profiler to query client', async ({ assert }) => { - const config = { - connection: 'primary', - connections: { primary: getConfig() }, - } - - const profiler = app.profiler - const db = new Database(config, app.logger, profiler, app.container.use('Adonis/Core/Event')) - const client = db.connection('primary') - assert.deepEqual(client.profiler, profiler) - - await db.manager.closeAll() - }) - - test('pass custom profiler to query client', async ({ assert }) => { - const config = { - connection: 'primary', - connections: { primary: getConfig() }, - } - - const profiler = app.profiler - const row = profiler.create('scoped') - - const db = new Database(config, app.logger, profiler, app.container.use('Adonis/Core/Event')) - const client = db.connection('primary', { profiler: row }) - assert.deepEqual(client.profiler, row) - - await db.manager.closeAll() - }) - test('set hasHealthChecks enabled flag to true, when one ore more connections are using health checks', async ({ assert, }) => { @@ -234,89 +162,19 @@ test.group('Database', (group) => { connections: { primary: Object.assign({}, getConfig(), { healthCheck: true }) }, } - const db = new Database( - config, - app.logger, - app.profiler, - app.container.use('Adonis/Core/Event') - ) + const db = new Database(config, logger, createEmitter()) assert.isTrue(db.hasHealthChecksEnabled) await db.manager.closeAll() }) }) -test.group('Database | extend', (group) => { - group.setup(async () => { - app = await setupApplication() - await setup() - }) - - group.teardown(async () => { - await cleanup() - await fs.cleanup() - }) - - test('extend database query builder by adding macros', async ({ assert }) => { - const db = getDb(app) - - db.DatabaseQueryBuilder.macro('whereActive', function whereActive() { - this.where('is_active', true) - return this - }) - - const knexClient = db.connection().getReadClient() - - const { sql, bindings } = db.query().from('users')['whereActive']().toSQL() - const { sql: knexSql, bindings: knexBindings } = knexClient - .from('users') - .where('is_active', true) - .toSQL() - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - - await db.manager.closeAll() - }) - - test('extend insert query builder by adding macros', async ({ assert }) => { - const db = getDb(app) - - db.InsertQueryBuilder.macro('returnId', function whereActive() { - this.knexQuery.returning('id') - return this - }) - - const knexClient = db.connection().getReadClient() - - const { sql, bindings } = db - .insertQuery() - .table('users') - ['returnId']() - .insert({ id: 1 }) - .toSQL() - - const { sql: knexSql, bindings: knexBindings } = knexClient - .from('users') - .returning('id') - .insert({ id: 1 }) - .toSQL() - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - - await db.manager.closeAll() - }) -}) - test.group('Database | global transaction', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) test('perform queries inside a global transaction', async ({ assert }) => { @@ -325,12 +183,7 @@ test.group('Database | global transaction', (group) => { connections: { primary: getConfig() }, } - const db = new Database( - config, - app.logger, - app.profiler, - app.container.use('Adonis/Core/Event') - ) + const db = new Database(config, logger, createEmitter()) await db.beginGlobalTransaction() await db.table('users').insert({ username: 'virk' }) @@ -349,12 +202,7 @@ test.group('Database | global transaction', (group) => { connections: { primary: getConfig() }, } - const db = new Database( - config, - app.logger, - app.profiler, - app.container.use('Adonis/Core/Event') - ) + const db = new Database(config, logger, createEmitter()) await db.beginGlobalTransaction() const trx = await db.transaction() @@ -376,12 +224,7 @@ test.group('Database | global transaction', (group) => { connections: { primary: getConfig() }, } - const db = new Database( - config, - app.logger, - app.profiler, - app.container.use('Adonis/Core/Event') - ) + const db = new Database(config, logger, createEmitter()) await db.beginGlobalTransaction() await db.beginGlobalTransaction() await db.beginGlobalTransaction() diff --git a/test/database/drop-tables.spec.ts b/test/database/drop_tables.spec.ts similarity index 75% rename from test/database/drop-tables.spec.ts rename to test/database/drop_tables.spec.ts index d6d83cc4..97ee6c3f 100644 --- a/test/database/drop-tables.spec.ts +++ b/test/database/drop_tables.spec.ts @@ -7,33 +7,24 @@ * file that was distributed with this source code. */ -/// - import { test } from '@japa/runner' -import { join } from 'path' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -import { Connection } from '../../src/Connection' -import { QueryClient } from '../../src/QueryClient' -import { fs, getConfig, setup, cleanup, setupApplication } from '../../test-helpers' -let app: ApplicationContract +import { Connection } from '../../src/connection/index.js' +import { QueryClient } from '../../src/query_client/index.js' +import { getConfig, setup, cleanup, logger, createEmitter } from '../../test-helpers/index.js' test.group('Query client | drop tables', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup(['temp_posts', 'temp_users', 'table_that_should_not_be_dropped', 'ignore_me']) await cleanup() - await fs.cleanup() }) test('drop all tables', async ({ assert }) => { - await fs.fsExtra.ensureDir(join(fs.basePath, 'temp')) - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() await connection.client!.schema.createTableIfNotExists('temp_users', (table) => { @@ -45,7 +36,7 @@ test.group('Query client | drop tables', (group) => { table.integer('temp_users_id').unsigned().references('id').inTable('temp_users') }) - const client = new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('dual', connection, createEmitter()) await client.dialect.dropAllTables(['public']) assert.isFalse(await connection.client!.schema.hasTable('temp_users')) @@ -66,11 +57,10 @@ test.group('Query client | drop tables', (group) => { }) test('drop all tables should not throw when there are no tables', async ({ assert }) => { - await fs.fsExtra.ensureDir(join(fs.basePath, 'temp')) - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('dual', connection, createEmitter()) try { await client.dropAllTables() @@ -83,12 +73,11 @@ test.group('Query client | drop tables', (group) => { }) test('drop all tables except those defined in ignoreTables', async ({ assert }) => { - await fs.fsExtra.ensureDir(join(fs.basePath, 'temp')) const config = getConfig() config.wipe = {} config.wipe.ignoreTables = ['table_that_should_not_be_dropped', 'ignore_me'] - const connection = new Connection('primary', config, app.logger) + const connection = new Connection('primary', config, logger) connection.connect() await connection.client!.schema.createTableIfNotExists('temp_users', (table) => { @@ -108,7 +97,7 @@ test.group('Query client | drop tables', (group) => { table.increments('id') ) - const client = new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('dual', connection, createEmitter()) await client.dialect.dropAllTables(['public']) assert.isFalse(await connection.client!.schema.hasTable('temp_users')) diff --git a/test/database/insert-query-builder.spec.ts b/test/database/insert_query_builder.spec.ts similarity index 75% rename from test/database/insert-query-builder.spec.ts rename to test/database/insert_query_builder.spec.ts index 2def9a82..9c5965ed 100644 --- a/test/database/insert-query-builder.spec.ts +++ b/test/database/insert_query_builder.spec.ts @@ -7,41 +7,32 @@ * file that was distributed with this source code. */ -/// - -import { ApplicationContract } from '@ioc:Adonis/Core/Application' import { test } from '@japa/runner' - -import { Connection } from '../../src/Connection' +import { Connection } from '../../src/connection/index.js' import { - fs, setup, cleanup, getConfig, getQueryClient, getInsertBuilder, - setupApplication, getRawQueryBuilder, -} from '../../test-helpers' - -let app: ApplicationContract + logger, +} from '../../test-helpers/index.js' test.group('Query Builder | insert', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) test('perform insert', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getInsertBuilder(getQueryClient(connection, app)) + const db = getInsertBuilder(getQueryClient(connection)) const { sql, bindings } = db.table('users').insert({ username: 'virk' }).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -56,10 +47,10 @@ test.group('Query Builder | insert', (group) => { }) test('perform multi insert', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getInsertBuilder(getQueryClient(connection, app)) + const db = getInsertBuilder(getQueryClient(connection)) const { sql, bindings } = db .table('users') .multiInsert([{ username: 'virk' }, { username: 'nikk' }]) @@ -77,10 +68,10 @@ test.group('Query Builder | insert', (group) => { }) test('define returning columns', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getInsertBuilder(getQueryClient(connection, app)) + const db = getInsertBuilder(getQueryClient(connection)) const canReturnColumns = db.table('users').client.dialect.supportsReturningStatement const { sql, bindings } = db @@ -104,16 +95,16 @@ test.group('Query Builder | insert', (group) => { }) test('derive key value from raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getInsertBuilder(getQueryClient(connection, app)) + const db = getInsertBuilder(getQueryClient(connection)) const { sql, bindings } = db .table('users') .insert({ username: getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), `ST_GeomFromText(POINT('row.lat_lng'))` ), }) diff --git a/test/database/query-builder.spec.ts b/test/database/query_builder.spec.ts similarity index 78% rename from test/database/query-builder.spec.ts rename to test/database/query_builder.spec.ts index 8eb25cf2..1940044d 100644 --- a/test/database/query-builder.spec.ts +++ b/test/database/query_builder.spec.ts @@ -7,14 +7,11 @@ * file that was distributed with this source code. */ -/// - import { test } from '@japa/runner' -import { Connection } from '../../src/Connection' -import { QueryRunner } from '../../src/QueryRunner' -import { DatabaseQueryBuilder } from '../../src/Database/QueryBuilder/Database' +import { Connection } from '../../src/connection/index.js' +import { QueryRunner } from '../../src/query_runner/index.js' +import { DatabaseQueryBuilder } from '../../src/database/query_builder/database.js' import { - fs, setup, cleanup, getDb, @@ -25,40 +22,36 @@ import { getQueryBuilder, getInsertBuilder, getRawQueryBuilder, - setupApplication, -} from '../../test-helpers' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -let app: ApplicationContract + logger, + createEmitter, +} from '../../test-helpers/index.js' +import { QueryClient } from '../../src/query_client/index.js' if (process.env.DB !== 'sqlite') { test.group('Query Builder | client', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('use read client when making select query', async ({ assert }) => { assert.plan(1) - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) const db = getQueryBuilder(client) - client.getReadClient = function getReadClient() { + client.getReadClient = function getReadClient(this: QueryClient) { assert.isTrue(true) - return this.connection.client + return this['connection'].client! } await new QueryRunner(client, false, null).run(db.select('*').from('users').knexQuery) @@ -67,15 +60,15 @@ if (process.env.DB !== 'sqlite') { test('use write client for update', async ({ assert }) => { assert.plan(1) - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) const db = getQueryBuilder(client) - client.getWriteClient = function getWriteClient() { + client.getWriteClient = function getWriteClient(this: QueryClient) { assert.isTrue(true) - return this.connection.client + return this['connection'].client! } await new QueryRunner(client, false, null).run( @@ -86,15 +79,15 @@ if (process.env.DB !== 'sqlite') { test('use write client for delete', async ({ assert }) => { assert.plan(1) - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) const db = getQueryBuilder(client) - client.getWriteClient = function getWriteClient() { + client.getWriteClient = function getWriteClient(this: QueryClient) { assert.isTrue(true) - return this.connection.client + return this['connection'].client! } await new QueryRunner(client, false, null).run(db.from('users').del().knexQuery) @@ -103,15 +96,15 @@ if (process.env.DB !== 'sqlite') { test('use write client for inserts', async ({ assert }) => { assert.plan(1) - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) const db = getInsertBuilder(client) - client.getWriteClient = function getWriteClient() { + client.getWriteClient = function getWriteClient(this: QueryClient) { assert.isTrue(true) - return this.connection.client + return this['connection'].client! } await new QueryRunner(client, false, null).run( @@ -121,10 +114,10 @@ if (process.env.DB !== 'sqlite') { }) test('use transaction client when query is used inside a transaction', async () => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) const db = getQueryBuilder(client) client.getReadClient = function getReadClient() { @@ -140,10 +133,10 @@ if (process.env.DB !== 'sqlite') { }) test('use transaction client when insert query is used inside a transaction', async () => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) const db = getInsertBuilder(client) client.getReadClient = function getReadClient() { @@ -161,10 +154,10 @@ if (process.env.DB !== 'sqlite') { }) test('use transaction client when query is issued from transaction client', async () => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) client.getReadClient = function getReadClient() { throw new Error('Never expected to reach here') @@ -179,10 +172,10 @@ if (process.env.DB !== 'sqlite') { }) test('use transaction client when insert query is issued from transaction client', async () => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) const trx = await client.transaction() trx.getReadClient = function getReadClient() { @@ -201,25 +194,22 @@ if (process.env.DB !== 'sqlite') { test.group('Query Builder | from', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('define query table', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').toSQL() const { sql: knexSql, bindings: knexBindings } = connection.client!.from('users').toSQL() @@ -229,10 +219,10 @@ test.group('Query Builder | from', (group) => { }) test('define table alias', ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from({ u: 'users' }).toSQL() const { sql: knexSql, bindings: knexBindings } = connection.client!.from({ u: 'users' }).toSQL() @@ -243,25 +233,22 @@ test.group('Query Builder | from', (group) => { test.group('Query Builder | select', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('define columns as array', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').select(['username']).toSQL() const { sql: knexSql, bindings: knexBindings } = connection .client!.from('users') @@ -274,10 +261,10 @@ test.group('Query Builder | select', (group) => { }) test('define columns with aliases', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').select(['username as u']).toSQL() const { sql: knexSql, bindings: knexBindings } = connection .client!.from('users') @@ -290,10 +277,10 @@ test.group('Query Builder | select', (group) => { }) test('define columns as multiple arguments', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').select('username', 'email').toSQL() const { sql: knexSql, bindings: knexBindings } = connection .client!.from('users') @@ -306,10 +293,10 @@ test.group('Query Builder | select', (group) => { }) test('define columns as multiple arguments with aliases', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').select('username as u', 'email as e').toSQL() const { sql: knexSql, bindings: knexBindings } = connection .client!.from('users') @@ -322,11 +309,11 @@ test.group('Query Builder | select', (group) => { }) test('define columns as subqueries', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) - const db1 = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) + const db1 = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') @@ -344,11 +331,11 @@ test.group('Query Builder | select', (group) => { }) test('define columns as subqueries inside an array', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) - const db1 = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) + const db1 = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') @@ -366,11 +353,11 @@ test.group('Query Builder | select', (group) => { }) test('chain select calls', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) - const db1 = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) + const db1 = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') @@ -389,15 +376,15 @@ test.group('Query Builder | select', (group) => { }) test('define columns as raw queries', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .select( - getQueryClient(connection, app).raw( + getQueryClient(connection).raw( '(select count(*) as total from addresses) as addresses_total' ) ) @@ -418,25 +405,22 @@ test.group('Query Builder | select', (group) => { test.group('Query Builder | where', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add where clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').where('username', 'virk').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -450,7 +434,7 @@ test.group('Query Builder | where', (group) => { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') @@ -468,10 +452,10 @@ test.group('Query Builder | where', (group) => { }) test('wrap where clause to its own group', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .where('username', 'virk') @@ -492,7 +476,7 @@ test.group('Query Builder | where', (group) => { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') @@ -514,10 +498,10 @@ test.group('Query Builder | where', (group) => { }) test('add where clause as an object', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').where({ username: 'virk', age: 22 }).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -528,7 +512,7 @@ test.group('Query Builder | where', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -547,10 +531,10 @@ test.group('Query Builder | where', (group) => { }) test('add where wrapped clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .where((builder) => builder.where('username', 'virk')) @@ -564,7 +548,7 @@ test.group('Query Builder | where', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -583,10 +567,10 @@ test.group('Query Builder | where', (group) => { }) test('wrap already wrapped where clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .where((builder) => builder.where('username', 'virk')) @@ -603,7 +587,7 @@ test.group('Query Builder | where', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -625,10 +609,10 @@ test.group('Query Builder | where', (group) => { }) test('add where clause with operator', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').where('age', '>', 22).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -639,7 +623,7 @@ test.group('Query Builder | where', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -658,10 +642,10 @@ test.group('Query Builder | where', (group) => { }) test('wrap where clause with operator', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .where('age', '>', 22) @@ -678,7 +662,7 @@ test.group('Query Builder | where', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -700,16 +684,16 @@ test.group('Query Builder | where', (group) => { }) test('add where clause as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .where( 'age', '>', - getRawQueryBuilder(getQueryClient(connection, app), 'select min_age from ages limit 1;') + getRawQueryBuilder(getQueryClient(connection), 'select min_age from ages limit 1;') ) .toSQL() @@ -724,16 +708,16 @@ test.group('Query Builder | where', (group) => { }) test('wrap raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .where( 'age', '>', - getRawQueryBuilder(getQueryClient(connection, app), 'select min_age from ages limit 1;') + getRawQueryBuilder(getQueryClient(connection), 'select min_age from ages limit 1;') ) .wrapExisting() .whereNotNull('deleted_at') @@ -753,13 +737,13 @@ test.group('Query Builder | where', (group) => { }) test('add where clause as a raw builder query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .where('age', '>', getDb(app).raw('select min_age from ages limit 1;')) + .where('age', '>', getDb().raw('select min_age from ages limit 1;')) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -773,13 +757,13 @@ test.group('Query Builder | where', (group) => { }) test('wrap raw query builder query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .where('age', '>', getDb(app).raw('select min_age from ages limit 1;')) + .where('age', '>', getDb().raw('select min_age from ages limit 1;')) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -793,10 +777,10 @@ test.group('Query Builder | where', (group) => { }) test('add orWhere clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').where('age', '>', 22).orWhere('age', 18).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -808,7 +792,7 @@ test.group('Query Builder | where', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -830,10 +814,10 @@ test.group('Query Builder | where', (group) => { }) test('wrap orWhere clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .where('age', '>', 22) @@ -850,7 +834,7 @@ test.group('Query Builder | where', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -873,10 +857,10 @@ test.group('Query Builder | where', (group) => { }) test('add orWhere wrapped clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .where('age', '>', 22) @@ -897,7 +881,7 @@ test.group('Query Builder | where', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -924,10 +908,10 @@ test.group('Query Builder | where', (group) => { }) test('wrap orWhere wrapped clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .where('age', '>', 22) @@ -947,7 +931,7 @@ test.group('Query Builder | where', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -975,10 +959,10 @@ test.group('Query Builder | where', (group) => { }) test('add where clause using ref', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').where('username', 'virk').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -992,11 +976,11 @@ test.group('Query Builder | where', (group) => { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') - .where('username', getDb(app).ref('foo.username')) + .where('username', getDb().ref('foo.username')) .toSQL() const { sql: knexResolverSql, bindings: knexResolverBindings } = connection @@ -1010,13 +994,13 @@ test.group('Query Builder | where', (group) => { }) test('wrap where clause using ref', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .where('username', getDb(app).ref('foo.username')) + .where('username', getDb().ref('foo.username')) .wrapExisting() .orWhereNotNull('deleted_at') .toSQL() @@ -1033,11 +1017,11 @@ test.group('Query Builder | where', (group) => { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') - .where('username', getDb(app).ref('foo.username')) + .where('username', getDb().ref('foo.username')) .wrapExisting() .orWhereNotNull('deleted_at') .toSQL() @@ -1054,10 +1038,10 @@ test.group('Query Builder | where', (group) => { }) test('allow raw query for the column name', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) let db = getQueryBuilder(client) const { sql, bindings } = db .from('users') @@ -1078,25 +1062,22 @@ test.group('Query Builder | where', (group) => { test.group('Query Builder | whereNot', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add where not clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').whereNot('username', 'virk').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -1107,7 +1088,7 @@ test.group('Query Builder | whereNot', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -1127,10 +1108,10 @@ test.group('Query Builder | whereNot', (group) => { }) test('wrap where not clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNot('username', 'virk') @@ -1147,7 +1128,7 @@ test.group('Query Builder | whereNot', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -1170,10 +1151,10 @@ test.group('Query Builder | whereNot', (group) => { }) test('add where not clause as an object', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').whereNot({ username: 'virk', age: 22 }).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -1184,7 +1165,7 @@ test.group('Query Builder | whereNot', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -1203,10 +1184,10 @@ test.group('Query Builder | whereNot', (group) => { }) test('add where not wrapped clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNot((builder) => builder.where('username', 'virk')) @@ -1220,7 +1201,7 @@ test.group('Query Builder | whereNot', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -1240,10 +1221,10 @@ test.group('Query Builder | whereNot', (group) => { }) test('wrap where not wrapped clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNot((builder) => builder.where('username', 'virk')) @@ -1260,7 +1241,7 @@ test.group('Query Builder | whereNot', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -1283,10 +1264,10 @@ test.group('Query Builder | whereNot', (group) => { }) test('add where not clause with operator', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').whereNot('age', '>', 22).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -1297,7 +1278,7 @@ test.group('Query Builder | whereNot', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -1317,10 +1298,10 @@ test.group('Query Builder | whereNot', (group) => { }) test('wrap where not clause with operator', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNot('age', '>', 22) @@ -1337,7 +1318,7 @@ test.group('Query Builder | whereNot', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -1360,16 +1341,16 @@ test.group('Query Builder | whereNot', (group) => { }) test('add where not clause as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNot( 'age', '>', - getRawQueryBuilder(getQueryClient(connection, app), 'select min_age from ages limit 1;') + getRawQueryBuilder(getQueryClient(connection), 'select min_age from ages limit 1;') ) .toSQL() @@ -1381,7 +1362,7 @@ test.group('Query Builder | whereNot', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -1389,7 +1370,7 @@ test.group('Query Builder | whereNot', (group) => { .whereNot( 'age', '>', - getRawQueryBuilder(getQueryClient(connection, app), 'select min_age from ages limit 1;') + getRawQueryBuilder(getQueryClient(connection), 'select min_age from ages limit 1;') ) .toSQL() @@ -1405,13 +1386,13 @@ test.group('Query Builder | whereNot', (group) => { }) test('add where not clause as a raw builder query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .whereNot('age', '>', getDb(app).raw('select min_age from ages limit 1;')) + .whereNot('age', '>', getDb().raw('select min_age from ages limit 1;')) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -1422,12 +1403,12 @@ test.group('Query Builder | whereNot', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') - .whereNot('age', '>', getDb(app).raw('select min_age from ages limit 1;')) + .whereNot('age', '>', getDb().raw('select min_age from ages limit 1;')) .toSQL() const { sql: knexResolverSql, bindings: knexResolverBindings } = connection @@ -1442,10 +1423,10 @@ test.group('Query Builder | whereNot', (group) => { }) test('add orWhereNot clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNot('age', '>', 22) @@ -1461,7 +1442,7 @@ test.group('Query Builder | whereNot', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -1483,10 +1464,10 @@ test.group('Query Builder | whereNot', (group) => { }) test('wrap orWhereNot clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNot('age', '>', 22) @@ -1503,7 +1484,7 @@ test.group('Query Builder | whereNot', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -1526,10 +1507,10 @@ test.group('Query Builder | whereNot', (group) => { }) test('add orWhereNot wrapped clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .where('age', '>', 22) @@ -1550,7 +1531,7 @@ test.group('Query Builder | whereNot', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -1579,25 +1560,20 @@ test.group('Query Builder | whereNot', (group) => { test.group('Query Builder | whereIn', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) - group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') - await resetTables() - }) + group.each.teardown(async () => {}) test('add whereIn clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').whereIn('username', ['virk', 'nikk']).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -1608,7 +1584,7 @@ test.group('Query Builder | whereIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -1627,10 +1603,10 @@ test.group('Query Builder | whereIn', (group) => { }) test('wrap whereIn clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereIn('username', ['virk', 'nikk']) @@ -1647,7 +1623,7 @@ test.group('Query Builder | whereIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -1669,10 +1645,11 @@ test.group('Query Builder | whereIn', (group) => { }) test('add whereIn as a query callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) + const { sql, bindings } = db .from('users') .whereIn('username', (builder) => { @@ -1690,7 +1667,7 @@ test.group('Query Builder | whereIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -1713,10 +1690,10 @@ test.group('Query Builder | whereIn', (group) => { }) test('wrap whereIn as a query callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereIn('username', (builder) => { @@ -1739,7 +1716,7 @@ test.group('Query Builder | whereIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -1767,15 +1744,15 @@ test.group('Query Builder | whereIn', (group) => { }) test('add whereIn as a subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereIn( 'username', - getQueryBuilder(getQueryClient(connection, app)).select('id').from('accounts') + getQueryBuilder(getQueryClient(connection)).select('id').from('accounts') ) .toSQL() @@ -1787,14 +1764,14 @@ test.group('Query Builder | whereIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .whereIn( 'username', - getQueryBuilder(getQueryClient(connection, app)).select('id').from('accounts') + getQueryBuilder(getQueryClient(connection)).select('id').from('accounts') ) .toSQL() @@ -1809,17 +1786,17 @@ test.group('Query Builder | whereIn', (group) => { }) test('add whereIn as a rawquery inside array', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() const ref = connection.client!.ref.bind(connection.client!) - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereIn('username', [ getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), `select ${ref('id')} from ${ref('accounts')}` ), ]) @@ -1833,14 +1810,14 @@ test.group('Query Builder | whereIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .whereIn('username', [ getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), `select ${ref('id')} from ${ref('accounts')}` ), ]) @@ -1860,17 +1837,17 @@ test.group('Query Builder | whereIn', (group) => { }) test('wrap whereIn as a rawquery inside array', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() const ref = connection.client!.ref.bind(connection.client!) - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereIn('username', [ getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), `select ${ref('id')} from ${ref('accounts')}` ), ]) @@ -1891,14 +1868,14 @@ test.group('Query Builder | whereIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .whereIn('username', [ getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), `select ${ref('id')} from ${ref('accounts')}` ), ]) @@ -1923,18 +1900,18 @@ test.group('Query Builder | whereIn', (group) => { }) test('add whereIn as a rawquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() const ref = connection.client!.ref.bind(connection.client!) - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereIn( 'username', getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), `select ${ref('id')} from ${ref('accounts')}` ) ) @@ -1948,7 +1925,7 @@ test.group('Query Builder | whereIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -1956,7 +1933,7 @@ test.group('Query Builder | whereIn', (group) => { .whereIn( 'username', getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), `select ${ref('id')} from ${ref('accounts')}` ) ) @@ -1976,15 +1953,15 @@ test.group('Query Builder | whereIn', (group) => { }) test('add whereIn as a raw builder query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() const ref = connection.client!.ref.bind(connection.client!) - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .whereIn('username', [getDb(app).raw(`select ${ref('id')} from ${ref('accounts')}`)]) + .whereIn('username', [getDb().raw(`select ${ref('id')} from ${ref('accounts')}`)]) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -1995,12 +1972,12 @@ test.group('Query Builder | whereIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') - .whereIn('username', [getDb(app).raw(`select ${ref('id')} from ${ref('accounts')}`)]) + .whereIn('username', [getDb().raw(`select ${ref('id')} from ${ref('accounts')}`)]) .toSQL() const { sql: knexResolverSql, bindings: knexResolverBindings } = connection @@ -2017,17 +1994,15 @@ test.group('Query Builder | whereIn', (group) => { }) test('add whereIn as a subquery with array of keys', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereIn( ['username', 'email'], - getQueryBuilder(getQueryClient(connection, app)) - .select('username', 'email') - .from('accounts') + getQueryBuilder(getQueryClient(connection)).select('username', 'email').from('accounts') ) .toSQL() @@ -2042,16 +2017,14 @@ test.group('Query Builder | whereIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .whereIn( ['username', 'email'], - getQueryBuilder(getQueryClient(connection, app)) - .select('username', 'email') - .from('accounts') + getQueryBuilder(getQueryClient(connection)).select('username', 'email').from('accounts') ) .toSQL() @@ -2070,10 +2043,10 @@ test.group('Query Builder | whereIn', (group) => { }) test('add whereIn as a 2d array', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereIn(['username', 'email'], [['foo', 'bar']]) @@ -2087,7 +2060,7 @@ test.group('Query Builder | whereIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -2107,10 +2080,10 @@ test.group('Query Builder | whereIn', (group) => { }) test('add orWhereIn clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereIn('username', ['virk', 'nikk']) @@ -2126,7 +2099,7 @@ test.group('Query Builder | whereIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -2148,10 +2121,10 @@ test.group('Query Builder | whereIn', (group) => { }) test('wrap orWhereIn clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereIn('username', ['virk', 'nikk']) @@ -2168,7 +2141,7 @@ test.group('Query Builder | whereIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -2191,10 +2164,10 @@ test.group('Query Builder | whereIn', (group) => { }) test('add orWhereIn as a query callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereIn('username', (builder) => { @@ -2218,7 +2191,7 @@ test.group('Query Builder | whereIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -2250,25 +2223,22 @@ test.group('Query Builder | whereIn', (group) => { test.group('Query Builder | whereNotIn', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add whereNotIn clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').whereNotIn('username', ['virk', 'nikk']).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -2279,7 +2249,7 @@ test.group('Query Builder | whereNotIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -2298,10 +2268,10 @@ test.group('Query Builder | whereNotIn', (group) => { }) test('wrap whereNotIn clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotIn('username', ['virk', 'nikk']) @@ -2318,7 +2288,7 @@ test.group('Query Builder | whereNotIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -2340,10 +2310,10 @@ test.group('Query Builder | whereNotIn', (group) => { }) test('add whereNotIn as a query callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotIn('username', (builder) => { @@ -2361,7 +2331,7 @@ test.group('Query Builder | whereNotIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -2384,15 +2354,15 @@ test.group('Query Builder | whereNotIn', (group) => { }) test('add whereNotIn as a sub query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotIn( 'username', - getQueryBuilder(getQueryClient(connection, app)).select('username').from('accounts') + getQueryBuilder(getQueryClient(connection)).select('username').from('accounts') ) .toSQL() @@ -2404,14 +2374,14 @@ test.group('Query Builder | whereNotIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .whereNotIn( 'username', - getQueryBuilder(getQueryClient(connection, app)).select('username').from('accounts') + getQueryBuilder(getQueryClient(connection)).select('username').from('accounts') ) .toSQL() @@ -2426,15 +2396,15 @@ test.group('Query Builder | whereNotIn', (group) => { }) test('wrap whereNotIn as a sub query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotIn( 'username', - getQueryBuilder(getQueryClient(connection, app)).select('username').from('accounts') + getQueryBuilder(getQueryClient(connection)).select('username').from('accounts') ) .wrapExisting() .orWhereNull('deleted_at') @@ -2451,14 +2421,14 @@ test.group('Query Builder | whereNotIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .whereNotIn( 'username', - getQueryBuilder(getQueryClient(connection, app)).select('username').from('accounts') + getQueryBuilder(getQueryClient(connection)).select('username').from('accounts') ) .wrapExisting() .orWhereNull('deleted_at') @@ -2478,10 +2448,10 @@ test.group('Query Builder | whereNotIn', (group) => { }) test('add whereNotIn as a 2d array', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotIn(['username', 'email'], [['foo', 'bar']]) @@ -2495,7 +2465,7 @@ test.group('Query Builder | whereNotIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -2515,10 +2485,10 @@ test.group('Query Builder | whereNotIn', (group) => { }) test('add orWhereNotIn clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotIn('username', ['virk', 'nikk']) @@ -2534,7 +2504,7 @@ test.group('Query Builder | whereNotIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -2556,10 +2526,10 @@ test.group('Query Builder | whereNotIn', (group) => { }) test('wrap orWhereNotIn clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotIn('username', ['virk', 'nikk']) @@ -2576,7 +2546,7 @@ test.group('Query Builder | whereNotIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -2599,10 +2569,10 @@ test.group('Query Builder | whereNotIn', (group) => { }) test('add orWhereNotIn as a subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotIn('username', (builder) => { @@ -2626,7 +2596,7 @@ test.group('Query Builder | whereNotIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -2658,25 +2628,22 @@ test.group('Query Builder | whereNotIn', (group) => { test.group('Query Builder | whereNull', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add where null clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').whereNull('deleted_at').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -2687,7 +2654,7 @@ test.group('Query Builder | whereNull', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -2707,10 +2674,10 @@ test.group('Query Builder | whereNull', (group) => { }) test('wrap where null clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNull('deleted_at') @@ -2727,7 +2694,7 @@ test.group('Query Builder | whereNull', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -2750,10 +2717,10 @@ test.group('Query Builder | whereNull', (group) => { }) test('add or where null clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNull('deleted_at') @@ -2769,7 +2736,7 @@ test.group('Query Builder | whereNull', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -2793,25 +2760,22 @@ test.group('Query Builder | whereNull', (group) => { test.group('Query Builder | whereNotNull', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add where not null clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').whereNotNull('deleted_at').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -2822,7 +2786,7 @@ test.group('Query Builder | whereNotNull', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -2842,10 +2806,10 @@ test.group('Query Builder | whereNotNull', (group) => { }) test('wrap where not null clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotNull('deleted_at') @@ -2862,7 +2826,7 @@ test.group('Query Builder | whereNotNull', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -2885,10 +2849,10 @@ test.group('Query Builder | whereNotNull', (group) => { }) test('add or where not null clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotNull('deleted_at') @@ -2904,7 +2868,7 @@ test.group('Query Builder | whereNotNull', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -2928,25 +2892,22 @@ test.group('Query Builder | whereNotNull', (group) => { test.group('Query Builder | whereExists', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add where exists clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereExists((builder) => { @@ -2967,10 +2928,10 @@ test.group('Query Builder | whereExists', (group) => { }) test('wrap where exists clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereExists((builder) => { @@ -2996,13 +2957,13 @@ test.group('Query Builder | whereExists', (group) => { }) test('add where exists clause as a subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .whereExists(getQueryBuilder(getQueryClient(connection, app)).from('accounts')) + .whereExists(getQueryBuilder(getQueryClient(connection)).from('accounts')) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -3017,13 +2978,13 @@ test.group('Query Builder | whereExists', (group) => { }) test('wrap where exists clause as a subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .whereExists(getQueryBuilder(getQueryClient(connection, app)).from('accounts')) + .whereExists(getQueryBuilder(getQueryClient(connection)).from('accounts')) .wrapExisting() .orWhereNull('deleted_at') .toSQL() @@ -3041,14 +3002,14 @@ test.group('Query Builder | whereExists', (group) => { }) test('wrap subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereExists( - getQueryBuilder(getQueryClient(connection, app)) + getQueryBuilder(getQueryClient(connection)) .from('accounts') .where('status', 'active') .orWhere('status', 'pending') @@ -3076,13 +3037,13 @@ test.group('Query Builder | whereExists', (group) => { }) test('add where exists clause as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .whereExists(getRawQueryBuilder(getQueryClient(connection, app), 'select * from accounts')) + .whereExists(getRawQueryBuilder(getQueryClient(connection), 'select * from accounts')) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -3097,10 +3058,10 @@ test.group('Query Builder | whereExists', (group) => { }) test('add or where exists clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .orWhereExists((builder) => { @@ -3122,10 +3083,10 @@ test.group('Query Builder | whereExists', (group) => { }) test('wrap or where exists clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereExists((builder) => { @@ -3158,13 +3119,13 @@ test.group('Query Builder | whereExists', (group) => { }) test('add or where exists clause as a subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .orWhereExists(getQueryBuilder(getQueryClient(connection, app)).from('accounts')) + .orWhereExists(getQueryBuilder(getQueryClient(connection)).from('accounts')) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -3179,15 +3140,15 @@ test.group('Query Builder | whereExists', (group) => { }) test('wrap or where exists clause as a subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .whereExists(getQueryBuilder(getQueryClient(connection, app)).from('teams')) + .whereExists(getQueryBuilder(getQueryClient(connection)).from('teams')) .wrapExisting() - .orWhereExists(getQueryBuilder(getQueryClient(connection, app)).from('accounts')) + .orWhereExists(getQueryBuilder(getQueryClient(connection)).from('accounts')) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -3205,25 +3166,22 @@ test.group('Query Builder | whereExists', (group) => { test.group('Query Builder | whereNotExists', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add where not exists clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotExists((builder) => { @@ -3245,10 +3203,10 @@ test.group('Query Builder | whereNotExists', (group) => { }) test('wrap where not exists clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotExists((builder) => { @@ -3275,13 +3233,13 @@ test.group('Query Builder | whereNotExists', (group) => { }) test('add where not exists clause as a subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .whereNotExists(getQueryBuilder(getQueryClient(connection, app)).from('accounts')) + .whereNotExists(getQueryBuilder(getQueryClient(connection)).from('accounts')) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -3296,10 +3254,10 @@ test.group('Query Builder | whereNotExists', (group) => { }) test('add or where not exists clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .orWhereNotExists((builder) => { @@ -3321,10 +3279,10 @@ test.group('Query Builder | whereNotExists', (group) => { }) test('wrap or where not exists clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotExists((builder) => { @@ -3357,13 +3315,13 @@ test.group('Query Builder | whereNotExists', (group) => { }) test('add or where not exists clause as a subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .orWhereNotExists(getQueryBuilder(getQueryClient(connection, app)).from('accounts')) + .orWhereNotExists(getQueryBuilder(getQueryClient(connection)).from('accounts')) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -3380,25 +3338,22 @@ test.group('Query Builder | whereNotExists', (group) => { test.group('Query Builder | whereBetween', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add where between clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').whereBetween('age', [0, 20]).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -3409,7 +3364,7 @@ test.group('Query Builder | whereBetween', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -3429,10 +3384,10 @@ test.group('Query Builder | whereBetween', (group) => { }) test('wrap where between clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereBetween('age', [0, 20]) @@ -3449,7 +3404,7 @@ test.group('Query Builder | whereBetween', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -3472,15 +3427,15 @@ test.group('Query Builder | whereBetween', (group) => { }) test('add where between clause as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereBetween('age', [ - getRawQueryBuilder(getQueryClient(connection, app), 'select min_age from ages;'), - getRawQueryBuilder(getQueryClient(connection, app), 'select max_age from ages;'), + getRawQueryBuilder(getQueryClient(connection), 'select min_age from ages;'), + getRawQueryBuilder(getQueryClient(connection), 'select max_age from ages;'), ]) .toSQL() @@ -3495,14 +3450,14 @@ test.group('Query Builder | whereBetween', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .whereBetween('age', [ - getRawQueryBuilder(getQueryClient(connection, app), 'select min_age from ages;'), - getRawQueryBuilder(getQueryClient(connection, app), 'select max_age from ages;'), + getRawQueryBuilder(getQueryClient(connection), 'select min_age from ages;'), + getRawQueryBuilder(getQueryClient(connection), 'select max_age from ages;'), ]) .toSQL() @@ -3521,10 +3476,10 @@ test.group('Query Builder | whereBetween', (group) => { }) test('add or where between clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').orWhereBetween('age', [18, 20]).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -3535,7 +3490,7 @@ test.group('Query Builder | whereBetween', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -3555,10 +3510,10 @@ test.group('Query Builder | whereBetween', (group) => { }) test('wrap or where between clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereBetween('age', [18, 20]) @@ -3576,7 +3531,7 @@ test.group('Query Builder | whereBetween', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -3600,15 +3555,15 @@ test.group('Query Builder | whereBetween', (group) => { }) test('add or where between clause as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .orWhereBetween('age', [ - getRawQueryBuilder(getQueryClient(connection, app), 'select min_age from ages;'), - getRawQueryBuilder(getQueryClient(connection, app), 'select max_age from ages;'), + getRawQueryBuilder(getQueryClient(connection), 'select min_age from ages;'), + getRawQueryBuilder(getQueryClient(connection), 'select max_age from ages;'), ]) .toSQL() @@ -3623,14 +3578,14 @@ test.group('Query Builder | whereBetween', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .orWhereBetween('age', [ - getRawQueryBuilder(getQueryClient(connection, app), 'select min_age from ages;'), - getRawQueryBuilder(getQueryClient(connection, app), 'select max_age from ages;'), + getRawQueryBuilder(getQueryClient(connection), 'select min_age from ages;'), + getRawQueryBuilder(getQueryClient(connection), 'select max_age from ages;'), ]) .toSQL() @@ -3651,25 +3606,22 @@ test.group('Query Builder | whereBetween', (group) => { test.group('Query Builder | whereNotBetween', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add where not between clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').whereNotBetween('age', [18, 20]).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -3680,7 +3632,7 @@ test.group('Query Builder | whereNotBetween', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -3700,10 +3652,10 @@ test.group('Query Builder | whereNotBetween', (group) => { }) test('wrap where not between clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotBetween('age', [18, 20]) @@ -3720,7 +3672,7 @@ test.group('Query Builder | whereNotBetween', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -3743,15 +3695,15 @@ test.group('Query Builder | whereNotBetween', (group) => { }) test('add where not between clause as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotBetween('age', [ - getRawQueryBuilder(getQueryClient(connection, app), 'select min_age from ages;'), - getRawQueryBuilder(getQueryClient(connection, app), 'select max_age from ages;'), + getRawQueryBuilder(getQueryClient(connection), 'select min_age from ages;'), + getRawQueryBuilder(getQueryClient(connection), 'select max_age from ages;'), ]) .toSQL() @@ -3766,14 +3718,14 @@ test.group('Query Builder | whereNotBetween', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .whereNotBetween('age', [ - getRawQueryBuilder(getQueryClient(connection, app), 'select min_age from ages;'), - getRawQueryBuilder(getQueryClient(connection, app), 'select max_age from ages;'), + getRawQueryBuilder(getQueryClient(connection), 'select min_age from ages;'), + getRawQueryBuilder(getQueryClient(connection), 'select max_age from ages;'), ]) .toSQL() @@ -3792,10 +3744,10 @@ test.group('Query Builder | whereNotBetween', (group) => { }) test('add or where not between clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotBetween('age', [18, 20]) @@ -3812,7 +3764,7 @@ test.group('Query Builder | whereNotBetween', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -3835,15 +3787,15 @@ test.group('Query Builder | whereNotBetween', (group) => { }) test('add or where not between clause as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .orWhereNotBetween('age', [ - getRawQueryBuilder(getQueryClient(connection, app), 'select min_age from ages;'), - getRawQueryBuilder(getQueryClient(connection, app), 'select max_age from ages;'), + getRawQueryBuilder(getQueryClient(connection), 'select min_age from ages;'), + getRawQueryBuilder(getQueryClient(connection), 'select max_age from ages;'), ]) .toSQL() @@ -3858,14 +3810,14 @@ test.group('Query Builder | whereNotBetween', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .orWhereNotBetween('age', [ - getRawQueryBuilder(getQueryClient(connection, app), 'select min_age from ages;'), - getRawQueryBuilder(getQueryClient(connection, app), 'select max_age from ages;'), + getRawQueryBuilder(getQueryClient(connection), 'select min_age from ages;'), + getRawQueryBuilder(getQueryClient(connection), 'select max_age from ages;'), ]) .toSQL() @@ -3886,25 +3838,22 @@ test.group('Query Builder | whereNotBetween', (group) => { test.group('Query Builder | whereRaw', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add where raw clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').whereRaw('id = ?', [1]).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -3919,10 +3868,10 @@ test.group('Query Builder | whereRaw', (group) => { }) test('wrap where raw clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereRaw('id = ?', [1]) @@ -3943,10 +3892,10 @@ test.group('Query Builder | whereRaw', (group) => { }) test('add where raw clause without bindings', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').whereRaw('id = 1').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -3961,10 +3910,10 @@ test.group('Query Builder | whereRaw', (group) => { }) test('add where raw clause with object of bindings', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').whereRaw('id = :id', { id: 1 }).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -3978,13 +3927,13 @@ test.group('Query Builder | whereRaw', (group) => { }) test('add where raw clause from a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .whereRaw(getRawQueryBuilder(getQueryClient(connection, app), 'select id from accounts;')) + .whereRaw(getRawQueryBuilder(getQueryClient(connection), 'select id from accounts;')) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -3999,10 +3948,10 @@ test.group('Query Builder | whereRaw', (group) => { }) test('add or where raw clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereRaw('id = ?', [1]) @@ -4022,10 +3971,10 @@ test.group('Query Builder | whereRaw', (group) => { }) test('wrap or where raw clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereRaw('id = ?', [1]) @@ -4048,25 +3997,22 @@ test.group('Query Builder | whereRaw', (group) => { test.group('Query Builder | join', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add query join', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .join('profiles', 'users.id', 'profiles.user_id') @@ -4084,10 +4030,10 @@ test.group('Query Builder | join', (group) => { }) test('add query join with operator', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .join('profiles', 'users.id', '!=', 'profiles.user_id') @@ -4105,10 +4051,10 @@ test.group('Query Builder | join', (group) => { }) test('add query join using join callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .join('profiles', (builder) => { @@ -4130,16 +4076,16 @@ test.group('Query Builder | join', (group) => { }) test('add query join as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .join( 'profiles', 'profiles.type', - getRawQueryBuilder(getQueryClient(connection, app), '?', ['social']) + getRawQueryBuilder(getQueryClient(connection), '?', ['social']) ) .toSQL() @@ -4155,13 +4101,13 @@ test.group('Query Builder | join', (group) => { }) test('add query join as a raw builder query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .join('profiles', 'profiles.type', getDb(app).raw('?', ['social'])) + .join('profiles', 'profiles.type', getDb().raw('?', ['social'])) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -4176,10 +4122,10 @@ test.group('Query Builder | join', (group) => { }) test('use onJsonPathEquals method from the join callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .join('profiles', (builder) => { @@ -4213,25 +4159,22 @@ test.group('Query Builder | join', (group) => { test.group('Query Builder | innerJoin', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add query innerJoin', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .innerJoin('profiles', 'users.id', 'profiles.user_id') @@ -4249,10 +4192,10 @@ test.group('Query Builder | innerJoin', (group) => { }) test('add query innerJoin with operator', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .innerJoin('profiles', 'users.id', '!=', 'profiles.user_id') @@ -4270,10 +4213,10 @@ test.group('Query Builder | innerJoin', (group) => { }) test('add query innerJoin using join callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .innerJoin('profiles', (builder) => { @@ -4295,16 +4238,16 @@ test.group('Query Builder | innerJoin', (group) => { }) test('add query innerJoin as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .innerJoin( 'profiles', 'profiles.type', - getRawQueryBuilder(getQueryClient(connection, app), '?', ['social']) + getRawQueryBuilder(getQueryClient(connection), '?', ['social']) ) .toSQL() @@ -4320,13 +4263,13 @@ test.group('Query Builder | innerJoin', (group) => { }) test('add query innerJoin as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .innerJoin('profiles', 'profiles.type', getDb(app).raw('?', ['social'])) + .innerJoin('profiles', 'profiles.type', getDb().raw('?', ['social'])) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -4343,25 +4286,22 @@ test.group('Query Builder | innerJoin', (group) => { test.group('Query Builder | leftJoin', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add query leftJoin', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .leftJoin('profiles', 'users.id', 'profiles.user_id') @@ -4379,10 +4319,10 @@ test.group('Query Builder | leftJoin', (group) => { }) test('add query leftJoin with operator', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .leftJoin('profiles', 'users.id', '!=', 'profiles.user_id') @@ -4400,10 +4340,10 @@ test.group('Query Builder | leftJoin', (group) => { }) test('add query leftJoin using join callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .leftJoin('profiles', (builder) => { @@ -4425,16 +4365,16 @@ test.group('Query Builder | leftJoin', (group) => { }) test('add query leftJoin as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .leftJoin( 'profiles', 'profiles.type', - getRawQueryBuilder(getQueryClient(connection, app), '?', ['social']) + getRawQueryBuilder(getQueryClient(connection), '?', ['social']) ) .toSQL() @@ -4452,25 +4392,20 @@ test.group('Query Builder | leftJoin', (group) => { test.group('Query Builder | leftOuterJoin', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) - group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') - await resetTables() - }) + group.each.teardown(async () => {}) test('add query leftOuterJoin', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .leftOuterJoin('profiles', 'users.id', 'profiles.user_id') @@ -4488,10 +4423,10 @@ test.group('Query Builder | leftOuterJoin', (group) => { }) test('add query leftOuterJoin with operator', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .leftOuterJoin('profiles', 'users.id', '!=', 'profiles.user_id') @@ -4509,10 +4444,10 @@ test.group('Query Builder | leftOuterJoin', (group) => { }) test('add query leftOuterJoin using join callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .leftOuterJoin('profiles', (builder) => { @@ -4534,16 +4469,16 @@ test.group('Query Builder | leftOuterJoin', (group) => { }) test('add query leftOuterJoin as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .leftOuterJoin( 'profiles', 'profiles.type', - getRawQueryBuilder(getQueryClient(connection, app), '?', ['social']) + getRawQueryBuilder(getQueryClient(connection), '?', ['social']) ) .toSQL() @@ -4561,25 +4496,22 @@ test.group('Query Builder | leftOuterJoin', (group) => { test.group('Query Builder | rightJoin', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add query rightJoin', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .rightJoin('profiles', 'users.id', 'profiles.user_id') @@ -4597,10 +4529,10 @@ test.group('Query Builder | rightJoin', (group) => { }) test('add query rightJoin with operator', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .rightJoin('profiles', 'users.id', '!=', 'profiles.user_id') @@ -4618,10 +4550,10 @@ test.group('Query Builder | rightJoin', (group) => { }) test('add query rightJoin using join callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .rightJoin('profiles', (builder) => { @@ -4643,16 +4575,16 @@ test.group('Query Builder | rightJoin', (group) => { }) test('add query rightJoin as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .rightJoin( 'profiles', 'profiles.type', - getRawQueryBuilder(getQueryClient(connection, app), '?', ['social']) + getRawQueryBuilder(getQueryClient(connection), '?', ['social']) ) .toSQL() @@ -4670,25 +4602,22 @@ test.group('Query Builder | rightJoin', (group) => { test.group('Query Builder | rightOuterJoin', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add query rightOuterJoin', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .rightOuterJoin('profiles', 'users.id', 'profiles.user_id') @@ -4706,10 +4635,10 @@ test.group('Query Builder | rightOuterJoin', (group) => { }) test('add query rightOuterJoin with operator', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .rightOuterJoin('profiles', 'users.id', '!=', 'profiles.user_id') @@ -4727,10 +4656,10 @@ test.group('Query Builder | rightOuterJoin', (group) => { }) test('add query rightOuterJoin using join callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .rightOuterJoin('profiles', (builder) => { @@ -4752,16 +4681,16 @@ test.group('Query Builder | rightOuterJoin', (group) => { }) test('add query rightOuterJoin as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .rightOuterJoin( 'profiles', 'profiles.type', - getRawQueryBuilder(getQueryClient(connection, app), '?', ['social']) + getRawQueryBuilder(getQueryClient(connection), '?', ['social']) ) .toSQL() @@ -4779,25 +4708,22 @@ test.group('Query Builder | rightOuterJoin', (group) => { test.group('Query Builder | fullOuterJoin', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add query fullOuterJoin', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .fullOuterJoin('profiles', 'users.id', 'profiles.user_id') @@ -4815,10 +4741,10 @@ test.group('Query Builder | fullOuterJoin', (group) => { }) test('add query fullOuterJoin with operator', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .fullOuterJoin('profiles', 'users.id', '!=', 'profiles.user_id') @@ -4836,10 +4762,10 @@ test.group('Query Builder | fullOuterJoin', (group) => { }) test('add query fullOuterJoin using join callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .fullOuterJoin('profiles', (builder) => { @@ -4861,16 +4787,16 @@ test.group('Query Builder | fullOuterJoin', (group) => { }) test('add query fullOuterJoin as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .fullOuterJoin( 'profiles', 'profiles.type', - getRawQueryBuilder(getQueryClient(connection, app), '?', ['social']) + getRawQueryBuilder(getQueryClient(connection), '?', ['social']) ) .toSQL() @@ -4888,25 +4814,22 @@ test.group('Query Builder | fullOuterJoin', (group) => { test.group('Query Builder | crossJoin', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add query crossJoin', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .crossJoin('profiles', 'users.id', 'profiles.user_id') @@ -4924,10 +4847,10 @@ test.group('Query Builder | crossJoin', (group) => { }) test('add query crossJoin with operator', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .crossJoin('profiles', 'users.id', '!=', 'profiles.user_id') @@ -4945,10 +4868,10 @@ test.group('Query Builder | crossJoin', (group) => { }) test('add query crossJoin using join callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .crossJoin('profiles', (builder) => { @@ -4970,16 +4893,16 @@ test.group('Query Builder | crossJoin', (group) => { }) test('add query crossJoin as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .crossJoin( 'profiles', 'profiles.type', - getRawQueryBuilder(getQueryClient(connection, app), '?', ['social']) + getRawQueryBuilder(getQueryClient(connection), '?', ['social']) ) .toSQL() @@ -4997,25 +4920,22 @@ test.group('Query Builder | crossJoin', (group) => { test.group('Query Builder | joinRaw', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add join as a raw join', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').joinRaw('natural full join table1').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -5030,13 +4950,13 @@ test.group('Query Builder | joinRaw', (group) => { }) test('add join as a raw join by passing the raw query output', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .joinRaw(getRawQueryBuilder(getQueryClient(connection, app), 'natural full join table1')) + .joinRaw(getRawQueryBuilder(getQueryClient(connection), 'natural full join table1')) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -5053,25 +4973,22 @@ test.group('Query Builder | joinRaw', (group) => { test.group('Query Builder | distinct', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('define distinct columns', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').distinct('name', 'age').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -5082,7 +4999,7 @@ test.group('Query Builder | distinct', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -5104,26 +5021,23 @@ test.group('Query Builder | distinct', (group) => { test.group('Query Builder | distinctOn', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) if (process.env.DB === 'pg') { test('define distinct columns', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').distinctOn('name', 'age').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -5134,7 +5048,7 @@ test.group('Query Builder | distinctOn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -5157,25 +5071,22 @@ test.group('Query Builder | distinctOn', (group) => { test.group('Query Builder | groupBy', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('define group by columns', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').groupBy('name', 'age').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -5186,7 +5097,7 @@ test.group('Query Builder | groupBy', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -5208,25 +5119,22 @@ test.group('Query Builder | groupBy', (group) => { test.group('Query Builder | groupByRaw', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('define group by columns as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').groupByRaw('select (age) from user_profiles').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -5243,25 +5151,22 @@ test.group('Query Builder | groupByRaw', (group) => { test.group('Query Builder | orderBy', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('define order by columns', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').orderBy('name').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -5272,7 +5177,7 @@ test.group('Query Builder | orderBy', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -5292,10 +5197,10 @@ test.group('Query Builder | orderBy', (group) => { }) test('define order by columns with explicit direction', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').orderBy('name', 'desc').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -5306,7 +5211,7 @@ test.group('Query Builder | orderBy', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -5326,10 +5231,10 @@ test.group('Query Builder | orderBy', (group) => { }) test('define order by columns as an array', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').orderBy('name', 'desc').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -5340,7 +5245,7 @@ test.group('Query Builder | orderBy', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -5360,10 +5265,10 @@ test.group('Query Builder | orderBy', (group) => { }) test('define order by columns as an array of objects', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .orderBy([ @@ -5383,7 +5288,7 @@ test.group('Query Builder | orderBy', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -5409,18 +5314,18 @@ test.group('Query Builder | orderBy', (group) => { }) test('define order by columns as subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) let db = getQueryBuilder(client) const { sql, bindings } = db .from('users') .orderBy( - getQueryBuilder(getQueryClient(connection, app)) + getQueryBuilder(getQueryClient(connection)) .from('user_logins') - .where('user_id', '=', getRawQueryBuilder(getQueryClient(connection, app), 'users.id')) + .where('user_id', '=', getRawQueryBuilder(getQueryClient(connection), 'users.id')) ) .toSQL() @@ -5440,19 +5345,19 @@ test.group('Query Builder | orderBy', (group) => { }) test('define order by columns as an array of subqueries', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) let db = getQueryBuilder(client) const { sql, bindings } = db .from('users') .orderBy([ { - column: getQueryBuilder(getQueryClient(connection, app)) + column: getQueryBuilder(getQueryClient(connection)) .from('user_logins') - .where('user_id', '=', getRawQueryBuilder(getQueryClient(connection, app), 'users.id')), + .where('user_id', '=', getRawQueryBuilder(getQueryClient(connection), 'users.id')), order: 'desc' as const, }, ]) @@ -5479,25 +5384,22 @@ test.group('Query Builder | orderBy', (group) => { test.group('Query Builder | orderByRaw', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('define order by columns as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').orderByRaw('col DESC NULLS LAST').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -5512,25 +5414,22 @@ test.group('Query Builder | orderByRaw', (group) => { test.group('Query Builder | offset', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('define select offset', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').offset(10).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -5547,25 +5446,22 @@ test.group('Query Builder | offset', (group) => { test.group('Query Builder | limit', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('define results limit', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').limit(10).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -5582,25 +5478,22 @@ test.group('Query Builder | limit', (group) => { test.group('Query Builder | union', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('define union query as a callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .union((builder) => { @@ -5622,13 +5515,13 @@ test.group('Query Builder | union', (group) => { }) test('define union query as a subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .union(getQueryBuilder(getQueryClient(connection, app)).from('users').whereNull('first_name')) + .union(getQueryBuilder(getQueryClient(connection)).from('users').whereNull('first_name')) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -5643,15 +5536,15 @@ test.group('Query Builder | union', (group) => { }) test('define union query as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .union( getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from users where first_name is null' ) ) @@ -5669,10 +5562,10 @@ test.group('Query Builder | union', (group) => { }) test('define union query as an array of callbacks', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .union([ @@ -5698,15 +5591,13 @@ test.group('Query Builder | union', (group) => { }) test('define union query as an array of subqueries', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .union([ - getQueryBuilder(getQueryClient(connection, app)).from('users').whereNull('first_name'), - ]) + .union([getQueryBuilder(getQueryClient(connection)).from('users').whereNull('first_name')]) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -5721,15 +5612,15 @@ test.group('Query Builder | union', (group) => { }) test('define union query as an array of raw queries', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .union([ getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from users where first_name is null' ), ]) @@ -5747,11 +5638,11 @@ test.group('Query Builder | union', (group) => { }) test('add limit to union set', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) - await getInsertBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) + await getInsertBuilder(getQueryClient(connection)) .table('users') .multiInsert([ { @@ -5768,7 +5659,7 @@ test.group('Query Builder | union', (group) => { }, ]) - await getInsertBuilder(getQueryClient(connection, app)) + await getInsertBuilder(getQueryClient(connection)) .table('friends') .multiInsert([ { @@ -5802,11 +5693,11 @@ test.group('Query Builder | union', (group) => { }) test('add limit to union subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) - await getInsertBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) + await getInsertBuilder(getQueryClient(connection)) .table('users') .multiInsert([ { @@ -5823,7 +5714,7 @@ test.group('Query Builder | union', (group) => { }, ]) - await getInsertBuilder(getQueryClient(connection, app)) + await getInsertBuilder(getQueryClient(connection)) .table('friends') .multiInsert([ { @@ -5861,11 +5752,11 @@ test.group('Query Builder | union', (group) => { }) test('count union set', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) - await getInsertBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) + await getInsertBuilder(getQueryClient(connection)) .table('users') .multiInsert([ { @@ -5882,7 +5773,7 @@ test.group('Query Builder | union', (group) => { }, ]) - await getInsertBuilder(getQueryClient(connection, app)) + await getInsertBuilder(getQueryClient(connection)) .table('friends') .multiInsert([ { @@ -5911,11 +5802,11 @@ test.group('Query Builder | union', (group) => { }) test('count union set with limit on subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) - await getInsertBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) + await getInsertBuilder(getQueryClient(connection)) .table('users') .multiInsert([ { @@ -5932,7 +5823,7 @@ test.group('Query Builder | union', (group) => { }, ]) - await getInsertBuilder(getQueryClient(connection, app)) + await getInsertBuilder(getQueryClient(connection)) .table('friends') .multiInsert([ { @@ -5965,25 +5856,22 @@ test.group('Query Builder | union', (group) => { test.group('Query Builder | unionAll', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('define unionAll query as a callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .unionAll((builder) => { @@ -6005,15 +5893,13 @@ test.group('Query Builder | unionAll', (group) => { }) test('define unionAll query as a subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .unionAll( - getQueryBuilder(getQueryClient(connection, app)).from('users').whereNull('first_name') - ) + .unionAll(getQueryBuilder(getQueryClient(connection)).from('users').whereNull('first_name')) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -6028,15 +5914,15 @@ test.group('Query Builder | unionAll', (group) => { }) test('define unionAll query as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .unionAll( getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from users where first_name is null' ) ) @@ -6054,10 +5940,10 @@ test.group('Query Builder | unionAll', (group) => { }) test('define unionAll query as an array of callbacks', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .unionAll([ @@ -6083,15 +5969,13 @@ test.group('Query Builder | unionAll', (group) => { }) test('define unionAll query as an array of subqueries', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .unionAll([ - getQueryBuilder(getQueryClient(connection, app)).from('users').whereNull('first_name'), - ]) + .unionAll([getQueryBuilder(getQueryClient(connection)).from('users').whereNull('first_name')]) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -6106,15 +5990,15 @@ test.group('Query Builder | unionAll', (group) => { }) test('define unionAll query as an array of raw queries', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .unionAll([ getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from users where first_name is null' ), ]) @@ -6132,25 +6016,22 @@ test.group('Query Builder | unionAll', (group) => { test.group('Query Builder | forUpdate', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('define FOR UPDATE lock', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').forUpdate().toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -6165,10 +6046,10 @@ test.group('Query Builder | forUpdate', (group) => { }) test('define FOR UPDATE lock with additional tables (pg only)', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').forUpdate('profiles').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -6185,25 +6066,22 @@ test.group('Query Builder | forUpdate', (group) => { test.group('Query Builder | forShare', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('define FOR SHARE lock', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').forShare().toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -6218,10 +6096,10 @@ test.group('Query Builder | forShare', (group) => { }) test('define FOR SHARE lock with additional tables (pg only)', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').forShare('profiles').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -6247,15 +6125,14 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add no wait instruction to the query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').forShare().noWait().toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -6281,10 +6158,10 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { }) test('add skip locked instruction to the query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').forShare().skipLocked().toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -6303,25 +6180,22 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { test.group('Query Builder | having', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add having clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').having('count', '>', 10).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -6332,7 +6206,7 @@ test.group('Query Builder | having', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -6352,10 +6226,10 @@ test.group('Query Builder | having', (group) => { }) test('add having clause as a callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .having((builder) => { @@ -6373,7 +6247,7 @@ test.group('Query Builder | having', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -6397,18 +6271,18 @@ test.group('Query Builder | having', (group) => { }) test('add having clause value being a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() const ref = connection.client!.ref.bind(connection.client!) - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .having( 'user_id', '=', getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), `(select ${ref('user_id')} from ${ref('accounts')})` ) ) @@ -6426,7 +6300,7 @@ test.group('Query Builder | having', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -6435,7 +6309,7 @@ test.group('Query Builder | having', (group) => { 'user_id', '=', getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), `(select ${ref('user_id')} from ${ref('accounts')})` ) ) @@ -6457,16 +6331,16 @@ test.group('Query Builder | having', (group) => { }) test('add having clause value being a sub query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .having( 'user_id', '=', - getQueryBuilder(getQueryClient(connection, app)).from('accounts').select('id') + getQueryBuilder(getQueryClient(connection)).from('accounts').select('id') ) .toSQL() @@ -6478,7 +6352,7 @@ test.group('Query Builder | having', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -6486,7 +6360,7 @@ test.group('Query Builder | having', (group) => { .having( 'user_id', '=', - getQueryBuilder(getQueryClient(connection, app)).from('accounts').select('id') + getQueryBuilder(getQueryClient(connection)).from('accounts').select('id') ) .toSQL() @@ -6502,14 +6376,14 @@ test.group('Query Builder | having', (group) => { }) test('add having clause as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .having(getRawQueryBuilder(getQueryClient(connection, app), 'id > ?', [4])) + .having(getRawQueryBuilder(getQueryClient(connection), 'id > ?', [4])) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -6524,13 +6398,13 @@ test.group('Query Builder | having', (group) => { }) test('add having clause as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .havingRaw(getRawQueryBuilder(getQueryClient(connection, app), 'sum(likes) > ?', [200])) + .havingRaw(getRawQueryBuilder(getQueryClient(connection), 'sum(likes) > ?', [200])) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -6545,13 +6419,13 @@ test.group('Query Builder | having', (group) => { }) test('add having clause as a raw builder query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .havingRaw(getDb(app).raw('sum(likes) > ?', [200])) + .havingRaw(getDb().raw('sum(likes) > ?', [200])) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -6566,10 +6440,10 @@ test.group('Query Builder | having', (group) => { }) test('add or having clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .having('count', '>', 10) @@ -6585,7 +6459,7 @@ test.group('Query Builder | having', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -6609,25 +6483,22 @@ test.group('Query Builder | having', (group) => { test.group('Query Builder | havingIn', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add having in clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').havingIn('id', [10, 20]).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -6638,7 +6509,7 @@ test.group('Query Builder | havingIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -6658,15 +6529,13 @@ test.group('Query Builder | havingIn', (group) => { }) test('add having in clause values as subqueries', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .havingIn('id', [ - getQueryBuilder(getQueryClient(connection, app)).select('id').from('accounts'), - ]) + .havingIn('id', [getQueryBuilder(getQueryClient(connection)).select('id').from('accounts')]) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -6677,14 +6546,12 @@ test.group('Query Builder | havingIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') - .havingIn('id', [ - getQueryBuilder(getQueryClient(connection, app)).select('id').from('accounts'), - ]) + .havingIn('id', [getQueryBuilder(getQueryClient(connection)).select('id').from('accounts')]) .toSQL() const { sql: knexResolverSql, bindings: knexResolverBindings } = connection @@ -6699,15 +6566,13 @@ test.group('Query Builder | havingIn', (group) => { }) test('add having in clause values as raw queries', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .havingIn('id', [ - getRawQueryBuilder(getQueryClient(connection, app), 'select id from accounts'), - ]) + .havingIn('id', [getRawQueryBuilder(getQueryClient(connection), 'select id from accounts')]) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -6718,14 +6583,12 @@ test.group('Query Builder | havingIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') - .havingIn('id', [ - getRawQueryBuilder(getQueryClient(connection, app), 'select id from accounts'), - ]) + .havingIn('id', [getRawQueryBuilder(getQueryClient(connection), 'select id from accounts')]) .toSQL() const { sql: knexResolverSql, bindings: knexResolverBindings } = connection @@ -6740,14 +6603,14 @@ test.group('Query Builder | havingIn', (group) => { }) test('add having in clause values as query callbacks', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const fn = (builder) => { + const fn = (builder: any) => { builder.select('id').from('accounts') } - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').havingIn('id', fn).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -6758,7 +6621,7 @@ test.group('Query Builder | havingIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -6766,7 +6629,7 @@ test.group('Query Builder | havingIn', (group) => { .havingIn('id', fn) .toSQL() - const fnKnex = (builder) => { + const fnKnex = (builder: any) => { builder.select('my_id').from('accounts') } const { sql: knexResolverSql, bindings: knexResolverBindings } = connection @@ -6781,18 +6644,18 @@ test.group('Query Builder | havingIn', (group) => { }) test('add or having in clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .havingIn('id', [10, 20]) .orHavingIn('id', [10, 30]) .toSQL() - const { sql: knexSql, bindings: knexBindings } = connection - .client!.from('users') + const { sql: knexSql, bindings: knexBindings } = (connection.client as any) + .from('users') .havingIn('id', [10, 20]) ['orHavingIn']('id', [10, 30]) .toSQL() @@ -6800,7 +6663,7 @@ test.group('Query Builder | havingIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -6809,8 +6672,8 @@ test.group('Query Builder | havingIn', (group) => { .orHavingIn('id', [10, 30]) .toSQL() - const { sql: knexResolverSql, bindings: knexResolverBindings } = connection - .client!.from('users') + const { sql: knexResolverSql, bindings: knexResolverBindings } = (connection.client as any) + .from('users') .havingIn('my_id', [10, 20]) ['orHavingIn']('my_id', [10, 30]) .toSQL() @@ -6824,25 +6687,22 @@ test.group('Query Builder | havingIn', (group) => { test.group('Query Builder | havingNotIn', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add not having in clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').havingNotIn('id', [10, 20]).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -6853,7 +6713,7 @@ test.group('Query Builder | havingNotIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -6873,14 +6733,14 @@ test.group('Query Builder | havingNotIn', (group) => { }) test('add having in clause values as subqueries', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .havingNotIn('id', [ - getQueryBuilder(getQueryClient(connection, app)).select('id').from('accounts'), + getQueryBuilder(getQueryClient(connection)).select('id').from('accounts'), ]) .toSQL() @@ -6892,13 +6752,13 @@ test.group('Query Builder | havingNotIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .havingNotIn('id', [ - getQueryBuilder(getQueryClient(connection, app)).select('id').from('accounts'), + getQueryBuilder(getQueryClient(connection)).select('id').from('accounts'), ]) .toSQL() @@ -6914,14 +6774,14 @@ test.group('Query Builder | havingNotIn', (group) => { }) test('add having in clause values as raw queries', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .havingNotIn('id', [ - getRawQueryBuilder(getQueryClient(connection, app), 'select id from accounts'), + getRawQueryBuilder(getQueryClient(connection), 'select id from accounts'), ]) .toSQL() @@ -6933,13 +6793,13 @@ test.group('Query Builder | havingNotIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .havingNotIn('id', [ - getRawQueryBuilder(getQueryClient(connection, app), 'select id from accounts'), + getRawQueryBuilder(getQueryClient(connection), 'select id from accounts'), ]) .toSQL() @@ -6955,14 +6815,14 @@ test.group('Query Builder | havingNotIn', (group) => { }) test('add having in clause values as query callbacks', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const fn = (builder) => { + const fn = (builder: any) => { builder.select('id').from('accounts') } - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').havingNotIn('id', fn).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -6973,7 +6833,7 @@ test.group('Query Builder | havingNotIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -6981,7 +6841,7 @@ test.group('Query Builder | havingNotIn', (group) => { .havingNotIn('id', fn) .toSQL() - const fnKnex = (builder) => { + const fnKnex = (builder: any) => { builder.select('my_id').from('accounts') } @@ -6997,10 +6857,10 @@ test.group('Query Builder | havingNotIn', (group) => { }) test('add or having in clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .havingNotIn('id', [10, 20]) @@ -7016,7 +6876,7 @@ test.group('Query Builder | havingNotIn', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -7039,25 +6899,22 @@ test.group('Query Builder | havingNotIn', (group) => { test.group('Query Builder | havingNull', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add having null clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').havingNull('deleted_at').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -7068,7 +6925,7 @@ test.group('Query Builder | havingNull', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -7088,18 +6945,18 @@ test.group('Query Builder | havingNull', (group) => { }) test('add or having null clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .havingNull('deleted_at') .orHavingNull('updated_at') .toSQL() - const { sql: knexSql, bindings: knexBindings } = connection - .client!.from('users') + const { sql: knexSql, bindings: knexBindings } = (connection.client as any) + .from('users') ['havingNull']('deleted_at') .orHavingNull('updated_at') .toSQL() @@ -7107,7 +6964,7 @@ test.group('Query Builder | havingNull', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -7116,8 +6973,8 @@ test.group('Query Builder | havingNull', (group) => { .orHavingNull('updated_at') .toSQL() - const { sql: knexResolverSql, bindings: knexResolverBindings } = connection - .client!.from('users') + const { sql: knexResolverSql, bindings: knexResolverBindings } = (connection.client as any) + .from('users') ['havingNull']('my_deleted_at') .orHavingNull('my_updated_at') .toSQL() @@ -7131,25 +6988,22 @@ test.group('Query Builder | havingNull', (group) => { test.group('Query Builder | havingNotNull', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add having null clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').havingNotNull('deleted_at').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -7160,7 +7014,7 @@ test.group('Query Builder | havingNotNull', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -7180,18 +7034,19 @@ test.group('Query Builder | havingNotNull', (group) => { }) test('add or having not null clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .havingNotNull('deleted_at') .orHavingNotNull('updated_at') .toSQL() - const { sql: knexSql, bindings: knexBindings } = connection - .client!.from('users') + const { sql: knexSql, bindings: knexBindings } = (connection.client as any) + .from('users') + .from('users') ['havingNotNull']('deleted_at') .orHavingNotNull('updated_at') .toSQL() @@ -7199,7 +7054,7 @@ test.group('Query Builder | havingNotNull', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -7208,8 +7063,8 @@ test.group('Query Builder | havingNotNull', (group) => { .orHavingNotNull('updated_at') .toSQL() - const { sql: knexResolverSql, bindings: knexResolverBindings } = connection - .client!.from('users') + const { sql: knexResolverSql, bindings: knexResolverBindings } = (connection.client as any) + .from('users') ['havingNotNull']('my_deleted_at') .orHavingNotNull('my_updated_at') .toSQL() @@ -7223,25 +7078,22 @@ test.group('Query Builder | havingNotNull', (group) => { test.group('Query Builder | havingExists', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add having exists clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .havingExists((builder) => { @@ -7249,9 +7101,9 @@ test.group('Query Builder | havingExists', (group) => { }) .toSQL() - const { sql: knexSql, bindings: knexBindings } = connection - .client!.from('users') - ['havingExists']((builder) => { + const { sql: knexSql, bindings: knexBindings } = (connection.client as any) + .from('users') + ['havingExists']((builder: any) => { builder.select('*').from('accounts').whereRaw('users.account_id = accounts.id') }) .toSQL() @@ -7262,17 +7114,17 @@ test.group('Query Builder | havingExists', (group) => { }) test('add having exists clause as a subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .havingExists(getQueryBuilder(getQueryClient(connection, app)).select('*').from('accounts')) + .havingExists(getQueryBuilder(getQueryClient(connection)).select('*').from('accounts')) .toSQL() - const { sql: knexSql, bindings: knexBindings } = connection - .client!.from('users') + const { sql: knexSql, bindings: knexBindings } = (connection.client as any) + .from('users') ['havingExists'](connection.client!.select('*').from('accounts')) .toSQL() @@ -7283,10 +7135,10 @@ test.group('Query Builder | havingExists', (group) => { }) test('add or having exists clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .havingExists((builder) => { @@ -7297,12 +7149,12 @@ test.group('Query Builder | havingExists', (group) => { }) .toSQL() - const { sql: knexSql, bindings: knexBindings } = connection - .client!.from('users') - ['havingExists']((builder) => { + const { sql: knexSql, bindings: knexBindings } = (connection.client as any) + .from('users') + ['havingExists']((builder: any) => { builder.select('*').from('accounts') }) - .orHavingExists((builder) => { + .orHavingExists((builder: any) => { builder.select('*').from('profiles') }) .toSQL() @@ -7316,25 +7168,22 @@ test.group('Query Builder | havingExists', (group) => { test.group('Query Builder | havingNotExists', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add having not exists clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .havingNotExists((builder) => { @@ -7342,9 +7191,9 @@ test.group('Query Builder | havingNotExists', (group) => { }) .toSQL() - const { sql: knexSql, bindings: knexBindings } = connection - .client!.from('users') - ['havingNotExists']((builder) => { + const { sql: knexSql, bindings: knexBindings } = (connection.client as any) + .from('users') + ['havingNotExists']((builder: any) => { builder.select('*').from('accounts').whereRaw('users.account_id = accounts.id') }) .toSQL() @@ -7356,19 +7205,17 @@ test.group('Query Builder | havingNotExists', (group) => { }) test('add having not exists clause as a subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .havingNotExists( - getQueryBuilder(getQueryClient(connection, app)).select('*').from('accounts') - ) + .havingNotExists(getQueryBuilder(getQueryClient(connection)).select('*').from('accounts')) .toSQL() - const { sql: knexSql, bindings: knexBindings } = connection - .client!.from('users') + const { sql: knexSql, bindings: knexBindings } = (connection.client as any) + .from('users') ['havingNotExists'](connection.client!.select('*').from('accounts')) .toSQL() @@ -7379,10 +7226,10 @@ test.group('Query Builder | havingNotExists', (group) => { }) test('add or having not exists clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .havingNotExists((builder) => { @@ -7393,12 +7240,12 @@ test.group('Query Builder | havingNotExists', (group) => { }) .toSQL() - const { sql: knexSql, bindings: knexBindings } = connection - .client!.from('users') - ['havingNotExists']((builder) => { + const { sql: knexSql, bindings: knexBindings } = (connection.client as any) + .from('users') + ['havingNotExists']((builder: any) => { builder.select('*').from('accounts') }) - .orHavingNotExists((builder) => { + .orHavingNotExists((builder: any) => { builder.select('*').from('profiles') }) .toSQL() @@ -7412,25 +7259,22 @@ test.group('Query Builder | havingNotExists', (group) => { test.group('Query Builder | havingBetween', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add having between clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').havingBetween('id', [5, 10]).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -7441,7 +7285,7 @@ test.group('Query Builder | havingBetween', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -7461,15 +7305,15 @@ test.group('Query Builder | havingBetween', (group) => { }) test('add having between clause with raw values', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .havingBetween('id', [ - getRawQueryBuilder(getQueryClient(connection, app), 'select min(id) from users;'), - getRawQueryBuilder(getQueryClient(connection, app), 'select max(id) from users;'), + getRawQueryBuilder(getQueryClient(connection), 'select min(id) from users;'), + getRawQueryBuilder(getQueryClient(connection), 'select max(id) from users;'), ]) .toSQL() @@ -7484,14 +7328,14 @@ test.group('Query Builder | havingBetween', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .havingBetween('id', [ - getRawQueryBuilder(getQueryClient(connection, app), 'select min(id) from users;'), - getRawQueryBuilder(getQueryClient(connection, app), 'select max(id) from users;'), + getRawQueryBuilder(getQueryClient(connection), 'select min(id) from users;'), + getRawQueryBuilder(getQueryClient(connection), 'select max(id) from users;'), ]) .toSQL() @@ -7510,15 +7354,15 @@ test.group('Query Builder | havingBetween', (group) => { }) test('add having between clause with subqueries', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .havingBetween('id', [ - getQueryBuilder(getQueryClient(connection, app)).select('id'), - getQueryBuilder(getQueryClient(connection, app)).select('id'), + getQueryBuilder(getQueryClient(connection)).select('id'), + getQueryBuilder(getQueryClient(connection)).select('id'), ]) .toSQL() @@ -7533,14 +7377,14 @@ test.group('Query Builder | havingBetween', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .havingBetween('id', [ - getQueryBuilder(getQueryClient(connection, app)).select('id'), - getQueryBuilder(getQueryClient(connection, app)).select('id'), + getQueryBuilder(getQueryClient(connection)).select('id'), + getQueryBuilder(getQueryClient(connection)).select('id'), ]) .toSQL() @@ -7559,10 +7403,10 @@ test.group('Query Builder | havingBetween', (group) => { }) test('add or having between clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .havingBetween('id', [5, 10]) @@ -7578,7 +7422,7 @@ test.group('Query Builder | havingBetween', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -7602,25 +7446,22 @@ test.group('Query Builder | havingBetween', (group) => { test.group('Query Builder | havingNotBetween', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add having not between clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').havingNotBetween('id', [5, 10]).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -7631,7 +7472,7 @@ test.group('Query Builder | havingNotBetween', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -7651,15 +7492,15 @@ test.group('Query Builder | havingNotBetween', (group) => { }) test('add having not between clause with raw values', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .havingNotBetween('id', [ - getRawQueryBuilder(getQueryClient(connection, app), 'select min(id) from users;'), - getRawQueryBuilder(getQueryClient(connection, app), 'select max(id) from users;'), + getRawQueryBuilder(getQueryClient(connection), 'select min(id) from users;'), + getRawQueryBuilder(getQueryClient(connection), 'select max(id) from users;'), ]) .toSQL() @@ -7674,14 +7515,14 @@ test.group('Query Builder | havingNotBetween', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .havingNotBetween('id', [ - getRawQueryBuilder(getQueryClient(connection, app), 'select min(id) from users;'), - getRawQueryBuilder(getQueryClient(connection, app), 'select max(id) from users;'), + getRawQueryBuilder(getQueryClient(connection), 'select min(id) from users;'), + getRawQueryBuilder(getQueryClient(connection), 'select max(id) from users;'), ]) .toSQL() @@ -7700,15 +7541,15 @@ test.group('Query Builder | havingNotBetween', (group) => { }) test('add having not between clause with subqueries', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .havingNotBetween('id', [ - getQueryBuilder(getQueryClient(connection, app)).select('id'), - getQueryBuilder(getQueryClient(connection, app)).select('id'), + getQueryBuilder(getQueryClient(connection)).select('id'), + getQueryBuilder(getQueryClient(connection)).select('id'), ]) .toSQL() @@ -7723,14 +7564,14 @@ test.group('Query Builder | havingNotBetween', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .havingNotBetween('id', [ - getQueryBuilder(getQueryClient(connection, app)).select('id'), - getQueryBuilder(getQueryClient(connection, app)).select('id'), + getQueryBuilder(getQueryClient(connection)).select('id'), + getQueryBuilder(getQueryClient(connection)).select('id'), ]) .toSQL() @@ -7749,10 +7590,10 @@ test.group('Query Builder | havingNotBetween', (group) => { }) test('add or having not between clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .havingNotBetween('id', [5, 10]) @@ -7768,7 +7609,7 @@ test.group('Query Builder | havingNotBetween', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -7792,25 +7633,22 @@ test.group('Query Builder | havingNotBetween', (group) => { test.group('Query Builder | havingRaw', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add having raw clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').havingRaw('id = ?', [1]).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -7825,10 +7663,10 @@ test.group('Query Builder | havingRaw', (group) => { }) test('add having raw clause without bindings', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').havingRaw('id = 1').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -7842,10 +7680,10 @@ test.group('Query Builder | havingRaw', (group) => { }) test('add having raw clause with object of bindings', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').havingRaw('id = :id', { id: 1 }).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -7860,13 +7698,13 @@ test.group('Query Builder | havingRaw', (group) => { }) test('add having raw clause from a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .havingRaw(getRawQueryBuilder(getQueryClient(connection, app), 'select id from accounts;')) + .havingRaw(getRawQueryBuilder(getQueryClient(connection), 'select id from accounts;')) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -7881,10 +7719,10 @@ test.group('Query Builder | havingRaw', (group) => { }) test('add or having raw clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .havingRaw('id = ?', [1]) @@ -7906,25 +7744,22 @@ test.group('Query Builder | havingRaw', (group) => { test.group('Query Builder | clearSelect', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('clear selected columns', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').select('id', 'username').clearSelect().toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -7942,25 +7777,22 @@ test.group('Query Builder | clearSelect', (group) => { test.group('Query Builder | clearWhere', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('clear where clauses', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').where('username', 'virk').clearWhere().toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -7978,25 +7810,22 @@ test.group('Query Builder | clearWhere', (group) => { test.group('Query Builder | clearOrder', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('clear order by columns', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').orderBy('id', 'desc').clearOrder().toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -8014,25 +7843,22 @@ test.group('Query Builder | clearOrder', (group) => { test.group('Query Builder | clearHaving', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('clear having clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').having('id', '>', 10).clearHaving().toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -8050,25 +7876,22 @@ test.group('Query Builder | clearHaving', (group) => { test.group('Query Builder | clearLimit', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('clear limit', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').limit(10).clearLimit().toSQL() const { sql: knexSql, bindings: knexBindings } = connection.client!.from('users').toSQL() @@ -8082,25 +7905,22 @@ test.group('Query Builder | clearLimit', (group) => { test.group('Query Builder | clearOffset', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('clear offset', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').offset(1).clearOffset().toSQL() const { sql: knexSql, bindings: knexBindings } = connection.client!.from('users').toSQL() @@ -8114,25 +7934,22 @@ test.group('Query Builder | clearOffset', (group) => { test.group('Query Builder | count', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('count all rows', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').count('*', 'total').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -8143,7 +7960,7 @@ test.group('Query Builder | count', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -8163,10 +7980,10 @@ test.group('Query Builder | count', (group) => { }) test('count multiple rows', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').count({ u: 'username', e: 'email' }).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -8177,7 +7994,7 @@ test.group('Query Builder | count', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -8197,15 +8014,15 @@ test.group('Query Builder | count', (group) => { }) test('count by raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .count( getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -8223,14 +8040,14 @@ test.group('Query Builder | count', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .count( getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -8252,16 +8069,14 @@ test.group('Query Builder | count', (group) => { }) test('count by subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .count( - getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), 'u' ) .toSQL() @@ -8276,15 +8091,13 @@ test.group('Query Builder | count', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .count( - getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), 'u' ) .toSQL() @@ -8303,15 +8116,15 @@ test.group('Query Builder | count', (group) => { }) test('count by raw query on multiple columns', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .count({ u: getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -8330,14 +8143,14 @@ test.group('Query Builder | count', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .count({ u: getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -8360,16 +8173,14 @@ test.group('Query Builder | count', (group) => { }) test('count by subquery on multiple columns', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .count({ - u: getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + u: getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), e: 'email', }) .toSQL() @@ -8385,15 +8196,13 @@ test.group('Query Builder | count', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .count({ - u: getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + u: getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), e: 'email', }) .toSQL() @@ -8415,25 +8224,22 @@ test.group('Query Builder | count', (group) => { test.group('Query Builder | countDistinct', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('count all rows', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').countDistinct('*', 'total').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -8444,7 +8250,7 @@ test.group('Query Builder | countDistinct', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -8464,10 +8270,10 @@ test.group('Query Builder | countDistinct', (group) => { }) test('count multiple rows', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').countDistinct({ u: 'username', e: 'email' }).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -8478,7 +8284,7 @@ test.group('Query Builder | countDistinct', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -8498,15 +8304,15 @@ test.group('Query Builder | countDistinct', (group) => { }) test('count by raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .countDistinct( getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -8524,14 +8330,14 @@ test.group('Query Builder | countDistinct', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .countDistinct( getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -8553,16 +8359,14 @@ test.group('Query Builder | countDistinct', (group) => { }) test('count by subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .countDistinct( - getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), 'u' ) .toSQL() @@ -8577,15 +8381,13 @@ test.group('Query Builder | countDistinct', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .countDistinct( - getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), 'u' ) .toSQL() @@ -8604,15 +8406,15 @@ test.group('Query Builder | countDistinct', (group) => { }) test('count by raw query on multiple columns', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .countDistinct({ u: getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -8631,14 +8433,14 @@ test.group('Query Builder | countDistinct', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .countDistinct({ u: getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -8661,16 +8463,14 @@ test.group('Query Builder | countDistinct', (group) => { }) test('count by subquery on multiple columns', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .countDistinct({ - u: getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + u: getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), e: 'email', }) .toSQL() @@ -8686,15 +8486,13 @@ test.group('Query Builder | countDistinct', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .countDistinct({ - u: getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + u: getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), e: 'email', }) .toSQL() @@ -8716,25 +8514,22 @@ test.group('Query Builder | countDistinct', (group) => { test.group('Query Builder | min', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('use min function', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').min('*', 'smallest').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -8745,7 +8540,7 @@ test.group('Query Builder | min', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -8765,10 +8560,10 @@ test.group('Query Builder | min', (group) => { }) test('use min function for multiple times', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').min({ u: 'username', e: 'email' }).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -8779,7 +8574,7 @@ test.group('Query Builder | min', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -8799,15 +8594,15 @@ test.group('Query Builder | min', (group) => { }) test('use raw queries to compute min', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .min( getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -8825,14 +8620,14 @@ test.group('Query Builder | min', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .min( getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -8854,16 +8649,14 @@ test.group('Query Builder | min', (group) => { }) test('use subqueries to compute min', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .min( - getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), 'u' ) .toSQL() @@ -8878,15 +8671,13 @@ test.group('Query Builder | min', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .min( - getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), 'u' ) .toSQL() @@ -8905,15 +8696,15 @@ test.group('Query Builder | min', (group) => { }) test('use raw query to compute min with multiple columns', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .min({ u: getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -8932,14 +8723,14 @@ test.group('Query Builder | min', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .min({ u: getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -8962,16 +8753,14 @@ test.group('Query Builder | min', (group) => { }) test('use subquery to compute min with multiple columns', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .min({ - u: getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + u: getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), e: 'email', }) .toSQL() @@ -8987,15 +8776,13 @@ test.group('Query Builder | min', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .min({ - u: getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + u: getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), e: 'email', }) .toSQL() @@ -9016,25 +8803,22 @@ test.group('Query Builder | min', (group) => { test.group('Query Builder | max', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('use max function', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').max('*', 'biggest').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -9045,7 +8829,7 @@ test.group('Query Builder | max', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -9065,10 +8849,10 @@ test.group('Query Builder | max', (group) => { }) test('use max function for multiple times', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').max({ u: 'username', e: 'email' }).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -9079,7 +8863,7 @@ test.group('Query Builder | max', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -9099,15 +8883,15 @@ test.group('Query Builder | max', (group) => { }) test('use raw queries to compute max', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .max( getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -9125,14 +8909,14 @@ test.group('Query Builder | max', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .max( getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -9154,16 +8938,14 @@ test.group('Query Builder | max', (group) => { }) test('use subqueries to compute max', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .max( - getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), 'u' ) .toSQL() @@ -9178,15 +8960,13 @@ test.group('Query Builder | max', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .max( - getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), 'u' ) .toSQL() @@ -9205,15 +8985,15 @@ test.group('Query Builder | max', (group) => { }) test('use raw query to compute max with multiple columns', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .max({ u: getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -9232,14 +9012,14 @@ test.group('Query Builder | max', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .max({ u: getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -9262,16 +9042,14 @@ test.group('Query Builder | max', (group) => { }) test('use subquery to compute max with multiple columns', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .max({ - u: getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + u: getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), e: 'email', }) .toSQL() @@ -9287,15 +9065,13 @@ test.group('Query Builder | max', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .max({ - u: getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + u: getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), e: 'email', }) .toSQL() @@ -9317,25 +9093,22 @@ test.group('Query Builder | max', (group) => { test.group('Query Builder | sum', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('use sum function', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').sum('*', 'total').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -9346,7 +9119,7 @@ test.group('Query Builder | sum', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -9366,10 +9139,10 @@ test.group('Query Builder | sum', (group) => { }) test('use sum function for multiple times', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').sum({ u: 'username', e: 'email' }).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -9380,7 +9153,7 @@ test.group('Query Builder | sum', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -9400,15 +9173,15 @@ test.group('Query Builder | sum', (group) => { }) test('use raw queries to compute sum', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .sum( getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -9426,14 +9199,14 @@ test.group('Query Builder | sum', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .sum( getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -9455,16 +9228,14 @@ test.group('Query Builder | sum', (group) => { }) test('use subqueries to compute sum', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .sum( - getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), 'u' ) .toSQL() @@ -9479,15 +9250,13 @@ test.group('Query Builder | sum', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .sum( - getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), 'u' ) .toSQL() @@ -9506,15 +9275,15 @@ test.group('Query Builder | sum', (group) => { }) test('use raw query to compute sum with multiple columns', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .sum({ u: getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -9533,14 +9302,14 @@ test.group('Query Builder | sum', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .sum({ u: getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -9563,16 +9332,14 @@ test.group('Query Builder | sum', (group) => { }) test('use subquery to compute sum with multiple columns', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .sum({ - u: getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + u: getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), e: 'email', }) .toSQL() @@ -9588,15 +9355,13 @@ test.group('Query Builder | sum', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .sum({ - u: getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + u: getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), e: 'email', }) .toSQL() @@ -9617,25 +9382,22 @@ test.group('Query Builder | sum', (group) => { test.group('Query Builder | sumDistinct', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('use sumDistinct function', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').sumDistinct('*', 'sumDistinct').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -9646,7 +9408,7 @@ test.group('Query Builder | sumDistinct', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -9666,10 +9428,10 @@ test.group('Query Builder | sumDistinct', (group) => { }) test('use sumDistinct function for multiple times', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').sumDistinct({ u: 'username', e: 'email' }).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -9680,7 +9442,7 @@ test.group('Query Builder | sumDistinct', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -9700,15 +9462,15 @@ test.group('Query Builder | sumDistinct', (group) => { }) test('use raw queries to compute sumDistinct', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .sumDistinct( getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -9726,14 +9488,14 @@ test.group('Query Builder | sumDistinct', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .sumDistinct( getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -9755,16 +9517,14 @@ test.group('Query Builder | sumDistinct', (group) => { }) test('use subqueries to compute sumDistinct', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .sumDistinct( - getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), 'u' ) .toSQL() @@ -9779,15 +9539,13 @@ test.group('Query Builder | sumDistinct', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .sumDistinct( - getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), 'u' ) .toSQL() @@ -9806,15 +9564,15 @@ test.group('Query Builder | sumDistinct', (group) => { }) test('use raw query to compute sumDistinct with multiple columns', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .sumDistinct({ u: getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -9833,14 +9591,14 @@ test.group('Query Builder | sumDistinct', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .sumDistinct({ u: getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -9863,16 +9621,14 @@ test.group('Query Builder | sumDistinct', (group) => { }) test('use subquery to compute sumDistinct with multiple columns', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .sumDistinct({ - u: getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + u: getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), e: 'email', }) .toSQL() @@ -9888,15 +9644,13 @@ test.group('Query Builder | sumDistinct', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .sumDistinct({ - u: getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + u: getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), e: 'email', }) .toSQL() @@ -9918,25 +9672,22 @@ test.group('Query Builder | sumDistinct', (group) => { test.group('Query Builder | avg', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('use avg function', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').avg('*', 'avg').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -9947,7 +9698,7 @@ test.group('Query Builder | avg', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -9967,10 +9718,10 @@ test.group('Query Builder | avg', (group) => { }) test('use avg function for multiple fields', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').avg({ u: 'username', e: 'email' }).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -9981,7 +9732,7 @@ test.group('Query Builder | avg', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -10001,15 +9752,15 @@ test.group('Query Builder | avg', (group) => { }) test('use raw queries to compute avg', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .avg( getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -10027,14 +9778,14 @@ test.group('Query Builder | avg', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .avg( getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -10056,16 +9807,14 @@ test.group('Query Builder | avg', (group) => { }) test('use subqueries to compute avg', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .avg( - getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), 'u' ) .toSQL() @@ -10080,15 +9829,13 @@ test.group('Query Builder | avg', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .avg( - getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), 'u' ) .toSQL() @@ -10107,15 +9854,15 @@ test.group('Query Builder | avg', (group) => { }) test('use raw query to compute avg with multiple columns', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .avg({ u: getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -10134,14 +9881,14 @@ test.group('Query Builder | avg', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .avg({ u: getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -10164,16 +9911,14 @@ test.group('Query Builder | avg', (group) => { }) test('use subquery to compute avg with multiple columns', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .avg({ - u: getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + u: getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), e: 'email', }) .toSQL() @@ -10189,15 +9934,13 @@ test.group('Query Builder | avg', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .avg({ - u: getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + u: getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), e: 'email', }) .toSQL() @@ -10219,25 +9962,22 @@ test.group('Query Builder | avg', (group) => { test.group('Query Builder | avgDistinct', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('use avgDistinct function', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').avgDistinct('*', 'avgDistinct').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -10248,7 +9988,7 @@ test.group('Query Builder | avgDistinct', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -10268,10 +10008,10 @@ test.group('Query Builder | avgDistinct', (group) => { }) test('use avgDistinct function for multiple times', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').avgDistinct({ u: 'username', e: 'email' }).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -10282,7 +10022,7 @@ test.group('Query Builder | avgDistinct', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -10302,15 +10042,15 @@ test.group('Query Builder | avgDistinct', (group) => { }) test('use raw queries to compute avgDistinct', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .avgDistinct( getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -10328,14 +10068,14 @@ test.group('Query Builder | avgDistinct', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .avgDistinct( getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -10357,16 +10097,14 @@ test.group('Query Builder | avgDistinct', (group) => { }) test('use subqueries to compute avgDistinct', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .avgDistinct( - getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), 'u' ) .toSQL() @@ -10381,15 +10119,13 @@ test.group('Query Builder | avgDistinct', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .avgDistinct( - getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), 'u' ) .toSQL() @@ -10408,15 +10144,15 @@ test.group('Query Builder | avgDistinct', (group) => { }) test('use raw query to compute avgDistinct with multiple columns', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .avgDistinct({ u: getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -10435,14 +10171,14 @@ test.group('Query Builder | avgDistinct', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .avgDistinct({ u: getRawQueryBuilder( - getQueryClient(connection, app), + getQueryClient(connection), 'select * from profiles where is_verified = ?', [true] ), @@ -10465,16 +10201,14 @@ test.group('Query Builder | avgDistinct', (group) => { }) test('use subquery to compute avgDistinct with multiple columns', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .avgDistinct({ - u: getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + u: getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), e: 'email', }) .toSQL() @@ -10490,15 +10224,13 @@ test.group('Query Builder | avgDistinct', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .avgDistinct({ - u: getQueryBuilder(getQueryClient(connection, app)) - .where('is_verified', true) - .from('profiles'), + u: getQueryBuilder(getQueryClient(connection)).where('is_verified', true).from('profiles'), e: 'email', }) .toSQL() @@ -10520,26 +10252,23 @@ test.group('Query Builder | avgDistinct', (group) => { test.group('Query Builder | paginate', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('paginate through rows', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) - await getInsertBuilder(getQueryClient(connection, app)).table('users').multiInsert(getUsers(18)) + let db = getQueryBuilder(getQueryClient(connection)) + await getInsertBuilder(getQueryClient(connection)).table('users').multiInsert(getUsers(18)) const users = await db.from('users').paginate(1, 5) users.baseUrl('/users') @@ -10570,11 +10299,11 @@ test.group('Query Builder | paginate', (group) => { }) test('paginate through rows and select columns', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) - await getInsertBuilder(getQueryClient(connection, app)).table('users').multiInsert(getUsers(18)) + let db = getQueryBuilder(getQueryClient(connection)) + await getInsertBuilder(getQueryClient(connection)).table('users').multiInsert(getUsers(18)) const users = await db.from('users').select('username').paginate(1, 5) users.baseUrl('/users') @@ -10605,11 +10334,11 @@ test.group('Query Builder | paginate', (group) => { }) test('paginate through rows when there is orderBy clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) - await getInsertBuilder(getQueryClient(connection, app)).table('users').multiInsert(getUsers(18)) + let db = getQueryBuilder(getQueryClient(connection)) + await getInsertBuilder(getQueryClient(connection)).table('users').multiInsert(getUsers(18)) const users = await db.from('users').orderBy('username').paginate(1, 5) users.baseUrl('/users') @@ -10639,11 +10368,11 @@ test.group('Query Builder | paginate', (group) => { }) test('paginate through rows for the last page', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) - await getInsertBuilder(getQueryClient(connection, app)).table('users').multiInsert(getUsers(18)) + let db = getQueryBuilder(getQueryClient(connection)) + await getInsertBuilder(getQueryClient(connection)).table('users').multiInsert(getUsers(18)) const users = await db.from('users').orderBy('username').paginate(4, 5) users.baseUrl('/users') @@ -10674,11 +10403,11 @@ test.group('Query Builder | paginate', (group) => { }) test('paginate through rows with group by clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) - await getInsertBuilder(getQueryClient(connection, app)).table('users').multiInsert(getUsers(18)) + let db = getQueryBuilder(getQueryClient(connection)) + await getInsertBuilder(getQueryClient(connection)).table('users').multiInsert(getUsers(18)) const users = await db .from('users') @@ -10714,10 +10443,10 @@ test.group('Query Builder | paginate', (group) => { }) test('paginate through rows with select distinct', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) let usersToInsert = getUsers(18).map((user, index) => { return { ...user, @@ -10725,9 +10454,7 @@ test.group('Query Builder | paginate', (group) => { } }) - await getInsertBuilder(getQueryClient(connection, app)) - .table('users') - .multiInsert(usersToInsert) + await getInsertBuilder(getQueryClient(connection)).table('users').multiInsert(usersToInsert) const query = db.from('users').distinct('users.country_id').joinRaw('cross join users u2') @@ -10758,11 +10485,11 @@ test.group('Query Builder | paginate', (group) => { }) test('generate range of pagination urls', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) - await getInsertBuilder(getQueryClient(connection, app)).table('users').multiInsert(getUsers(18)) + let db = getQueryBuilder(getQueryClient(connection)) + await getInsertBuilder(getQueryClient(connection)).table('users').multiInsert(getUsers(18)) const users = await db.from('users').paginate(1, 5) users.baseUrl('/users') @@ -10794,11 +10521,11 @@ test.group('Query Builder | paginate', (group) => { }) test('loop over pagination rows', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) - await getInsertBuilder(getQueryClient(connection, app)).table('users').multiInsert(getUsers(18)) + let db = getQueryBuilder(getQueryClient(connection)) + await getInsertBuilder(getQueryClient(connection)).table('users').multiInsert(getUsers(18)) const users = await db.from('users').paginate(1, 5) users.forEach((user) => { @@ -10809,11 +10536,11 @@ test.group('Query Builder | paginate', (group) => { }) test('use custom strategy for pagination keys', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) - await getInsertBuilder(getQueryClient(connection, app)).table('users').multiInsert(getUsers(18)) + let db = getQueryBuilder(getQueryClient(connection)) + await getInsertBuilder(getQueryClient(connection)).table('users').multiInsert(getUsers(18)) const users = await db.from('users').paginate(1, 5) users.baseUrl('/users') @@ -10860,12 +10587,12 @@ test.group('Query Builder | paginate', (group) => { }) test('use table aliases', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const usersList = getUsers(18) - await getInsertBuilder(getQueryClient(connection, app)).table('users').multiInsert(usersList) + await getInsertBuilder(getQueryClient(connection)).table('users').multiInsert(usersList) const users = await db .from({ u: 'users' }) @@ -10902,25 +10629,22 @@ test.group('Query Builder | paginate', (group) => { test.group('Query Builder | clone', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('clone query builder', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const clonedQuery = db.from('users').clone() assert.deepEqual(clonedQuery, db) @@ -10928,10 +10652,10 @@ test.group('Query Builder | clone', (group) => { }) test('clone query builder with where clauses', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').where('username', 'virk').clone().toSQL() @@ -10947,10 +10671,10 @@ test.group('Query Builder | clone', (group) => { }) test('deep clone where clauses', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const query = db.from('users').where('username', 'virk') const { sql, bindings } = query.clone().orWhere('username', 'romain').toSQL() @@ -10977,10 +10701,10 @@ test.group('Query Builder | clone', (group) => { }) test('copy internals to the cloned query builder', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const clonedQuery = db.from('users').groupBy('id').clone() assert.isTrue(clonedQuery.hasGroupBy) @@ -10990,17 +10714,14 @@ test.group('Query Builder | clone', (group) => { test.group('Query Builder | event', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) @@ -11008,12 +10729,12 @@ test.group('Query Builder | event', (group) => { assert.plan(4) const config = Object.assign({}, getConfig(), { debug: true }) - const emitter = app.container.use('Adonis/Core/Event') + const emitter = createEmitter() - const connection = new Connection('primary', config, app.logger) + const connection = new Connection('primary', config, logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app, 'dual')) + let db = getQueryBuilder(getQueryClient(connection, emitter, 'dual')) emitter.on('db:query', (query) => { assert.property(query, 'sql') assert.property(query, 'inTransaction') @@ -11028,12 +10749,12 @@ test.group('Query Builder | event', (group) => { test('do not emit db:query event when debug not enabled', async () => { const config = Object.assign({}, getConfig(), { debug: false }) - const emitter = app.container.use('Adonis/Core/Event') + const emitter = createEmitter() - const connection = new Connection('primary', config, app.logger) + const connection = new Connection('primary', config, logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app, 'dual')) + let db = getQueryBuilder(getQueryClient(connection, emitter, 'dual')) emitter.on('db:query', () => { throw new Error('Never expected to reach here') }) @@ -11044,12 +10765,12 @@ test.group('Query Builder | event', (group) => { test('emit db:query event when enabled on a single query', async ({ assert }, done) => { const config = Object.assign({}, getConfig(), { debug: false }) - const emitter = app.container.use('Adonis/Core/Event') + const emitter = createEmitter() - const connection = new Connection('primary', config, app.logger) + const connection = new Connection('primary', config, logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app, 'dual')) + let db = getQueryBuilder(getQueryClient(connection, emitter, 'dual')) emitter.on('db:query', (query) => { assert.property(query, 'sql') assert.property(query, 'inTransaction') @@ -11065,25 +10786,22 @@ test.group('Query Builder | event', (group) => { test.group('Query Builder | update', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('update columns by defining object', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').update({ account_status: 'active' }).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -11094,7 +10812,7 @@ test.group('Query Builder | update', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -11114,10 +10832,10 @@ test.group('Query Builder | update', (group) => { }) test('update columns by defining key-value pair', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').update('account_status', 'active').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -11128,7 +10846,7 @@ test.group('Query Builder | update', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -11148,10 +10866,10 @@ test.group('Query Builder | update', (group) => { }) test('handle use case where update value is false or 0', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').update('account_status', 0).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -11162,7 +10880,7 @@ test.group('Query Builder | update', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -11184,25 +10902,22 @@ test.group('Query Builder | update', (group) => { test.group('Query Builder | whereColumn', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add where clause on another column', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereColumn('account_id', 'user_accounts.user_id') @@ -11219,7 +10934,7 @@ test.group('Query Builder | whereColumn', (group) => { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') @@ -11237,10 +10952,10 @@ test.group('Query Builder | whereColumn', (group) => { }) test('add or where clause on another column', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereColumn('account_id', 'user_accounts.user_id') @@ -11259,7 +10974,7 @@ test.group('Query Builder | whereColumn', (group) => { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') @@ -11279,10 +10994,10 @@ test.group('Query Builder | whereColumn', (group) => { }) test('add where not clause on another column', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotColumn('account_id', 'user_accounts.user_id') @@ -11299,7 +11014,7 @@ test.group('Query Builder | whereColumn', (group) => { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') @@ -11317,10 +11032,10 @@ test.group('Query Builder | whereColumn', (group) => { }) test('add or where not clause on another column', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotColumn('account_id', 'user_accounts.user_id') @@ -11339,7 +11054,7 @@ test.group('Query Builder | whereColumn', (group) => { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') @@ -11361,25 +11076,22 @@ test.group('Query Builder | whereColumn', (group) => { test.group('Query Builder | conditionals', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add constraints to query using if condition', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .if(true, (query) => { @@ -11401,10 +11113,10 @@ test.group('Query Builder | conditionals', (group) => { }) test('define else block for the if condition', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .if( @@ -11429,10 +11141,10 @@ test.group('Query Builder | conditionals', (group) => { }) test('add constraints to query using unless condition', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .unless(true, (query) => { @@ -11454,10 +11166,10 @@ test.group('Query Builder | conditionals', (group) => { }) test('define else block for the unless condition', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .unless( @@ -11482,10 +11194,10 @@ test.group('Query Builder | conditionals', (group) => { }) test('invoke conditional function to find the conditional value', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .unless( @@ -11513,10 +11225,10 @@ test.group('Query Builder | conditionals', (group) => { }) test('define a match block with no else statement', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .match( @@ -11536,10 +11248,10 @@ test.group('Query Builder | conditionals', (group) => { }) test('define match conditionals as functions', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .match( @@ -11559,10 +11271,10 @@ test.group('Query Builder | conditionals', (group) => { }) test('use the first matching block', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .match( @@ -11582,10 +11294,10 @@ test.group('Query Builder | conditionals', (group) => { }) test('use the else block when nothing matches', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .match( @@ -11608,25 +11320,22 @@ test.group('Query Builder | conditionals', (group) => { test.group('Query Builder | wrapExisting', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('apply where clauses only once, when calling toSQL multiple times', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const query = db.from('users').where('username', 'virk') @@ -11638,10 +11347,10 @@ test.group('Query Builder | wrapExisting', (group) => { }) test('allow mutating query where clauses post toSQL call', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const query = db.from('users').where('username', 'virk') const knexQuery = connection.client!.from('users').where('username', 'virk') @@ -11654,25 +11363,22 @@ test.group('Query Builder | wrapExisting', (group) => { test.group('Query Builder | with', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('define with clause as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) let db = getQueryBuilder(client) const { sql, bindings } = db @@ -11692,10 +11398,10 @@ test.group('Query Builder | with', (group) => { }) test('define with clause as a callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) let db = getQueryBuilder(client) const { sql, bindings } = db @@ -11715,10 +11421,10 @@ test.group('Query Builder | with', (group) => { }) test('define with clause as a subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) let db = getQueryBuilder(client) const { sql, bindings } = db @@ -11738,10 +11444,10 @@ test.group('Query Builder | with', (group) => { }) test('define with clause and column list', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) let db = getQueryBuilder(client) const { sql, bindings } = db @@ -11763,25 +11469,22 @@ test.group('Query Builder | with', (group) => { test.group('Query Builder | withRecursive', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('define with recursive clause as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) let db = getQueryBuilder(client) const { sql, bindings } = db @@ -11801,10 +11504,10 @@ test.group('Query Builder | withRecursive', (group) => { }) test('define with recursive clause as a callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) let db = getQueryBuilder(client) const { sql, bindings } = db @@ -11824,10 +11527,10 @@ test.group('Query Builder | withRecursive', (group) => { }) test('define with recursive clause as a subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) let db = getQueryBuilder(client) const { sql, bindings } = db @@ -11847,10 +11550,10 @@ test.group('Query Builder | withRecursive', (group) => { }) test('define with recursive clause and column list', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) let db = getQueryBuilder(client) const { sql, bindings } = db @@ -11873,25 +11576,22 @@ test.group('Query Builder | withRecursive', (group) => { if (['pg', 'sqlite', 'better_sqlite'].includes(process.env.DB!)) { test.group('Query Builder | withMaterialized', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('define withMaterialized clause as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) let db = getQueryBuilder(client) const { sql, bindings } = db @@ -11911,10 +11611,10 @@ if (['pg', 'sqlite', 'better_sqlite'].includes(process.env.DB!)) { }) test('define withMaterialized clause as a callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) let db = getQueryBuilder(client) const { sql, bindings } = db @@ -11934,10 +11634,10 @@ if (['pg', 'sqlite', 'better_sqlite'].includes(process.env.DB!)) { }) test('define withMaterialized clause as a subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) let db = getQueryBuilder(client) const { sql, bindings } = db @@ -11957,10 +11657,10 @@ if (['pg', 'sqlite', 'better_sqlite'].includes(process.env.DB!)) { }) test('define withMaterialized clause and column list', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) let db = getQueryBuilder(client) const { sql, bindings } = db @@ -11982,25 +11682,22 @@ if (['pg', 'sqlite', 'better_sqlite'].includes(process.env.DB!)) { test.group('Query Builder | withNotMaterialized', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('define withNotMaterialized clause as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) let db = getQueryBuilder(client) const { sql, bindings } = db @@ -12020,10 +11717,10 @@ if (['pg', 'sqlite', 'better_sqlite'].includes(process.env.DB!)) { }) test('define withNotMaterialized clause as a callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) let db = getQueryBuilder(client) const { sql, bindings } = db @@ -12043,10 +11740,10 @@ if (['pg', 'sqlite', 'better_sqlite'].includes(process.env.DB!)) { }) test('define withNotMaterialized clause as a subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) let db = getQueryBuilder(client) const { sql, bindings } = db @@ -12066,10 +11763,10 @@ if (['pg', 'sqlite', 'better_sqlite'].includes(process.env.DB!)) { }) test('define withNotMaterialized clause and column list', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = getQueryClient(connection, app) + const client = getQueryClient(connection) let db = getQueryBuilder(client) const { sql, bindings } = db @@ -12092,25 +11789,22 @@ if (['pg', 'sqlite', 'better_sqlite'].includes(process.env.DB!)) { test.group('Query Builder | whereLike', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add where like clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').whereLike('username', 'virk').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -12124,7 +11818,7 @@ test.group('Query Builder | whereLike', (group) => { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') @@ -12142,10 +11836,10 @@ test.group('Query Builder | whereLike', (group) => { }) test('wrap where like clause to its own group', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereLike('username', 'virk') @@ -12166,7 +11860,7 @@ test.group('Query Builder | whereLike', (group) => { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') @@ -12188,15 +11882,15 @@ test.group('Query Builder | whereLike', (group) => { }) test('add where like clause as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereLike( 'age', - getRawQueryBuilder(getQueryClient(connection, app), 'select min_age from ages limit 1;') + getRawQueryBuilder(getQueryClient(connection), 'select min_age from ages limit 1;') ) .toSQL() @@ -12211,15 +11905,15 @@ test.group('Query Builder | whereLike', (group) => { }) test('wrap raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereLike( 'age', - getRawQueryBuilder(getQueryClient(connection, app), 'select min_age from ages limit 1;') + getRawQueryBuilder(getQueryClient(connection), 'select min_age from ages limit 1;') ) .wrapExisting() .whereNotNull('deleted_at') @@ -12237,13 +11931,13 @@ test.group('Query Builder | whereLike', (group) => { }) test('add where like clause as a raw builder query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .whereLike('age', getDb(app).raw('select min_age from ages limit 1;')) + .whereLike('age', getDb().raw('select min_age from ages limit 1;')) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -12257,13 +11951,13 @@ test.group('Query Builder | whereLike', (group) => { }) test('wrap raw query builder query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .whereLike('age', getDb(app).raw('select min_age from ages limit 1;')) + .whereLike('age', getDb().raw('select min_age from ages limit 1;')) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -12277,10 +11971,10 @@ test.group('Query Builder | whereLike', (group) => { }) test('add orWhereLike clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').whereLike('age', 22).orWhereLike('age', 18).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -12292,7 +11986,7 @@ test.group('Query Builder | whereLike', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -12314,10 +12008,10 @@ test.group('Query Builder | whereLike', (group) => { }) test('wrap orWhereLike clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereLike('age', 22) @@ -12334,7 +12028,7 @@ test.group('Query Builder | whereLike', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -12357,10 +12051,10 @@ test.group('Query Builder | whereLike', (group) => { }) test('add whereLike clause using ref', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').whereLike('username', 'virk').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -12374,11 +12068,11 @@ test.group('Query Builder | whereLike', (group) => { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') - .whereLike('username', getDb(app).ref('foo.username')) + .whereLike('username', getDb().ref('foo.username')) .toSQL() const { sql: knexResolverSql, bindings: knexResolverBindings } = connection @@ -12392,13 +12086,13 @@ test.group('Query Builder | whereLike', (group) => { }) test('wrap whereLike clause using ref', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .whereLike('username', getDb(app).ref('foo.username')) + .whereLike('username', getDb().ref('foo.username')) .wrapExisting() .orWhereNotNull('deleted_at') .toSQL() @@ -12415,11 +12109,11 @@ test.group('Query Builder | whereLike', (group) => { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') - .whereLike('username', getDb(app).ref('foo.username')) + .whereLike('username', getDb().ref('foo.username')) .wrapExisting() .orWhereNotNull('deleted_at') .toSQL() @@ -12438,25 +12132,22 @@ test.group('Query Builder | whereLike', (group) => { test.group('Query Builder | whereILike', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add whereILike clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').whereILike('username', 'virk').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -12470,7 +12161,7 @@ test.group('Query Builder | whereILike', (group) => { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') @@ -12488,10 +12179,10 @@ test.group('Query Builder | whereILike', (group) => { }) test('wrap whereILike clause to its own group', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereILike('username', 'virk') @@ -12512,7 +12203,7 @@ test.group('Query Builder | whereILike', (group) => { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') @@ -12534,15 +12225,15 @@ test.group('Query Builder | whereILike', (group) => { }) test('add whereILike clause as a raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereILike( 'age', - getRawQueryBuilder(getQueryClient(connection, app), 'select min_age from ages limit 1;') + getRawQueryBuilder(getQueryClient(connection), 'select min_age from ages limit 1;') ) .toSQL() @@ -12557,15 +12248,15 @@ test.group('Query Builder | whereILike', (group) => { }) test('wrap raw query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereILike( 'age', - getRawQueryBuilder(getQueryClient(connection, app), 'select min_age from ages limit 1;') + getRawQueryBuilder(getQueryClient(connection), 'select min_age from ages limit 1;') ) .wrapExisting() .whereNotNull('deleted_at') @@ -12585,13 +12276,13 @@ test.group('Query Builder | whereILike', (group) => { }) test('add whereILike clause as a raw builder query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .whereILike('age', getDb(app).raw('select min_age from ages limit 1;')) + .whereILike('age', getDb().raw('select min_age from ages limit 1;')) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -12605,13 +12296,13 @@ test.group('Query Builder | whereILike', (group) => { }) test('wrap raw query builder query', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const db = getQueryBuilder(getQueryClient(connection, app)) + const db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .whereILike('age', getDb(app).raw('select min_age from ages limit 1;')) + .whereILike('age', getDb().raw('select min_age from ages limit 1;')) .toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -12625,10 +12316,10 @@ test.group('Query Builder | whereILike', (group) => { }) test('add orWhereILike clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').whereILike('age', 22).orWhereILike('age', 18).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -12640,7 +12331,7 @@ test.group('Query Builder | whereILike', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -12662,10 +12353,10 @@ test.group('Query Builder | whereILike', (group) => { }) test('wrap orWhereILike clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereILike('age', 22) @@ -12682,7 +12373,7 @@ test.group('Query Builder | whereILike', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -12705,10 +12396,10 @@ test.group('Query Builder | whereILike', (group) => { }) test('add whereILike clause using ref', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').whereILike('username', 'virk').toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -12722,11 +12413,11 @@ test.group('Query Builder | whereILike', (group) => { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') - .whereILike('username', getDb(app).ref('foo.username')) + .whereILike('username', getDb().ref('foo.username')) .toSQL() const { sql: knexResolverSql, bindings: knexResolverBindings } = connection @@ -12740,13 +12431,13 @@ test.group('Query Builder | whereILike', (group) => { }) test('wrap whereILike clause using ref', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') - .whereILike('username', getDb(app).ref('foo.username')) + .whereILike('username', getDb().ref('foo.username')) .wrapExisting() .orWhereNotNull('deleted_at') .toSQL() @@ -12763,11 +12454,11 @@ test.group('Query Builder | whereILike', (group) => { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') - .whereILike('username', getDb(app).ref('foo.username')) + .whereILike('username', getDb().ref('foo.username')) .wrapExisting() .orWhereNotNull('deleted_at') .toSQL() @@ -12786,25 +12477,22 @@ test.group('Query Builder | whereILike', (group) => { test.group('Query Builder | whereJson', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add where json clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db.from('users').whereJson('location', { country: 'India' }).toSQL() const { sql: knexSql, bindings: knexBindings } = connection @@ -12818,7 +12506,7 @@ test.group('Query Builder | whereJson', (group) => { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') @@ -12836,10 +12524,10 @@ test.group('Query Builder | whereJson', (group) => { }) test('wrap where json clause to its own group', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereJson('location', { country: 'India' }) @@ -12864,7 +12552,7 @@ test.group('Query Builder | whereJson', (group) => { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') @@ -12890,10 +12578,10 @@ test.group('Query Builder | whereJson', (group) => { }) test('add orWhereJson clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereJson('location', { country: 'India' }) @@ -12909,7 +12597,7 @@ test.group('Query Builder | whereJson', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -12931,10 +12619,10 @@ test.group('Query Builder | whereJson', (group) => { }) test('wrap orWhereJson clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereJson('location', { country: 'India' }) @@ -12951,7 +12639,7 @@ test.group('Query Builder | whereJson', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -12974,10 +12662,10 @@ test.group('Query Builder | whereJson', (group) => { }) test('define whereJson value as a callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereJson('location', (q) => q.from('locations').where('user_id', '1')) @@ -12985,13 +12673,13 @@ test.group('Query Builder | whereJson', (group) => { const { sql: knexSql, bindings: knexBindings } = connection .client!.from('users') - .whereJsonObject('location', (q) => q.from('locations').where('user_id', '1')) + .whereJsonObject('location', (q: any) => q.from('locations').where('user_id', '1')) .toSQL() assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -13001,7 +12689,7 @@ test.group('Query Builder | whereJson', (group) => { const { sql: knexResolverSql, bindings: knexResolverBindings } = connection .client!.from('users') - .whereJsonObject('my_location', (q) => q.from('locations').where('my_user_id', '1')) + .whereJsonObject('my_location', (q: any) => q.from('locations').where('my_user_id', '1')) .toSQL() assert.equal(resolverSql, knexResolverSql) @@ -13011,15 +12699,15 @@ test.group('Query Builder | whereJson', (group) => { }) test('define whereJson value as a subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereJson( 'location', - getQueryBuilder(getQueryClient(connection, app)).from('locations').where('user_id', '1') + getQueryBuilder(getQueryClient(connection)).from('locations').where('user_id', '1') ) .toSQL() @@ -13031,14 +12719,14 @@ test.group('Query Builder | whereJson', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .whereJson( 'location', - getQueryBuilder(getQueryClient(connection, app)).from('locations').where('user_id', '1') + getQueryBuilder(getQueryClient(connection)).from('locations').where('user_id', '1') ) .toSQL() @@ -13056,25 +12744,22 @@ test.group('Query Builder | whereJson', (group) => { test.group('Query Builder | whereNotJson', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add where not json clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotJson('location', { country: 'India' }) @@ -13091,7 +12776,7 @@ test.group('Query Builder | whereNotJson', (group) => { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') @@ -13109,10 +12794,10 @@ test.group('Query Builder | whereNotJson', (group) => { }) test('wrap where not json clause to its own group', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotJson('location', { country: 'India' }) @@ -13137,7 +12822,7 @@ test.group('Query Builder | whereNotJson', (group) => { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') @@ -13163,10 +12848,10 @@ test.group('Query Builder | whereNotJson', (group) => { }) test('add orWhereNotJson clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotJson('location', { country: 'India' }) @@ -13182,7 +12867,7 @@ test.group('Query Builder | whereNotJson', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -13204,10 +12889,10 @@ test.group('Query Builder | whereNotJson', (group) => { }) test('wrap orWhereNotJson clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotJson('location', { country: 'India' }) @@ -13224,7 +12909,7 @@ test.group('Query Builder | whereNotJson', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -13247,10 +12932,10 @@ test.group('Query Builder | whereNotJson', (group) => { }) test('define whereNotJson value as a callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotJson('location', (q) => q.from('locations').where('user_id', '1')) @@ -13258,13 +12943,13 @@ test.group('Query Builder | whereNotJson', (group) => { const { sql: knexSql, bindings: knexBindings } = connection .client!.from('users') - .whereNotJsonObject('location', (q) => q.from('locations').where('user_id', '1')) + .whereNotJsonObject('location', (q: any) => q.from('locations').where('user_id', '1')) .toSQL() assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -13274,7 +12959,7 @@ test.group('Query Builder | whereNotJson', (group) => { const { sql: knexResolverSql, bindings: knexResolverBindings } = connection .client!.from('users') - .whereNotJsonObject('my_location', (q) => q.from('locations').where('my_user_id', '1')) + .whereNotJsonObject('my_location', (q: any) => q.from('locations').where('my_user_id', '1')) .toSQL() assert.equal(resolverSql, knexResolverSql) @@ -13284,15 +12969,15 @@ test.group('Query Builder | whereNotJson', (group) => { }) test('define whereNotJson value as a subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotJson( 'location', - getQueryBuilder(getQueryClient(connection, app)).from('locations').where('user_id', '1') + getQueryBuilder(getQueryClient(connection)).from('locations').where('user_id', '1') ) .toSQL() @@ -13304,14 +12989,14 @@ test.group('Query Builder | whereNotJson', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .whereNotJson( 'location', - getQueryBuilder(getQueryClient(connection, app)).from('locations').where('user_id', '1') + getQueryBuilder(getQueryClient(connection)).from('locations').where('user_id', '1') ) .toSQL() @@ -13330,25 +13015,22 @@ test.group('Query Builder | whereNotJson', (group) => { if (['pg', 'mysql'].includes(process.env.DB!)) { test.group('Query Builder | whereJsonSuperset', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add where json superset clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereJsonSuperset('location', { country: 'India' }) @@ -13365,7 +13047,7 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') @@ -13383,10 +13065,10 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { }) test('wrap where json superset clause to its own group', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereJsonSuperset('location', { country: 'India' }) @@ -13411,7 +13093,7 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') @@ -13437,10 +13119,10 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { }) test('add orWhereJsonSuperset clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereJsonSuperset('location', { country: 'India' }) @@ -13456,7 +13138,7 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -13478,10 +13160,10 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { }) test('wrap orWhereJsonSuperset clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereJsonSuperset('location', { country: 'India' }) @@ -13498,7 +13180,7 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -13521,10 +13203,10 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { }) test('define whereJsonSuperset value as a callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereJsonSuperset('location', (q) => q.from('locations').where('user_id', '1')) @@ -13532,13 +13214,13 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { const { sql: knexSql, bindings: knexBindings } = connection .client!.from('users') - .whereJsonSupersetOf('location', (q) => q.from('locations').where('user_id', '1')) + .whereJsonSupersetOf('location', (q: any) => q.from('locations').where('user_id', '1')) .toSQL() assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -13548,7 +13230,9 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { const { sql: knexResolverSql, bindings: knexResolverBindings } = connection .client!.from('users') - .whereJsonSupersetOf('my_location', (q) => q.from('locations').where('my_user_id', '1')) + .whereJsonSupersetOf('my_location', (q: any) => + q.from('locations').where('my_user_id', '1') + ) .toSQL() assert.equal(resolverSql, knexResolverSql) @@ -13558,15 +13242,15 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { }) test('define whereJsonSuperset value as a subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereJsonSuperset( 'location', - getQueryBuilder(getQueryClient(connection, app)).from('locations').where('user_id', '1') + getQueryBuilder(getQueryClient(connection)).from('locations').where('user_id', '1') ) .toSQL() @@ -13578,14 +13262,14 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .whereJsonSuperset( 'location', - getQueryBuilder(getQueryClient(connection, app)).from('locations').where('user_id', '1') + getQueryBuilder(getQueryClient(connection)).from('locations').where('user_id', '1') ) .toSQL() @@ -13606,25 +13290,22 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { test.group('Query Builder | whereNotJsonSuperset', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add where not json superset clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotJsonSuperset('location', { country: 'India' }) @@ -13641,7 +13322,7 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') @@ -13659,10 +13340,10 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { }) test('wrap where not json superset clause to its own group', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotJsonSuperset('location', { country: 'India' }) @@ -13687,7 +13368,7 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') @@ -13713,10 +13394,10 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { }) test('add orWhereNotJsonSuperset clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotJsonSuperset('location', { country: 'India' }) @@ -13732,7 +13413,7 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -13754,10 +13435,10 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { }) test('wrap orWhereNotJsonSuperset clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotJsonSuperset('location', { country: 'India' }) @@ -13774,7 +13455,7 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -13797,10 +13478,10 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { }) test('define whereNotJsonSuperset value as a callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotJsonSuperset('location', (q) => q.from('locations').where('user_id', '1')) @@ -13808,13 +13489,13 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { const { sql: knexSql, bindings: knexBindings } = connection .client!.from('users') - .whereJsonNotSupersetOf('location', (q) => q.from('locations').where('user_id', '1')) + .whereJsonNotSupersetOf('location', (q: any) => q.from('locations').where('user_id', '1')) .toSQL() assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -13824,7 +13505,9 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { const { sql: knexResolverSql, bindings: knexResolverBindings } = connection .client!.from('users') - .whereJsonNotSupersetOf('my_location', (q) => q.from('locations').where('my_user_id', '1')) + .whereJsonNotSupersetOf('my_location', (q: any) => + q.from('locations').where('my_user_id', '1') + ) .toSQL() assert.equal(resolverSql, knexResolverSql) @@ -13834,15 +13517,15 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { }) test('define whereNotJsonSuperset value as a subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotJsonSuperset( 'location', - getQueryBuilder(getQueryClient(connection, app)).from('locations').where('user_id', '1') + getQueryBuilder(getQueryClient(connection)).from('locations').where('user_id', '1') ) .toSQL() @@ -13857,14 +13540,14 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .whereNotJsonSuperset( 'location', - getQueryBuilder(getQueryClient(connection, app)).from('locations').where('user_id', '1') + getQueryBuilder(getQueryClient(connection)).from('locations').where('user_id', '1') ) .toSQL() @@ -13885,25 +13568,22 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { test.group('Query Builder | whereJsonSubset', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add where json subset clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereJsonSubset('location', { country: 'India' }) @@ -13920,7 +13600,7 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') @@ -13938,10 +13618,10 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { }) test('wrap where json subset clause to its own group', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereJsonSubset('location', { country: 'India' }) @@ -13966,7 +13646,7 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') @@ -13992,10 +13672,10 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { }) test('add orWhereJsonSubset clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereJsonSubset('location', { country: 'India' }) @@ -14011,7 +13691,7 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -14033,10 +13713,10 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { }) test('wrap orWhereJsonSubset clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereJsonSubset('location', { country: 'India' }) @@ -14053,7 +13733,7 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -14076,10 +13756,10 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { }) test('define whereJsonSubset value as a callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereJsonSubset('location', (q) => q.from('locations').where('user_id', '1')) @@ -14087,13 +13767,13 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { const { sql: knexSql, bindings: knexBindings } = connection .client!.from('users') - .whereJsonSubsetOf('location', (q) => q.from('locations').where('user_id', '1')) + .whereJsonSubsetOf('location', (q: any) => q.from('locations').where('user_id', '1')) .toSQL() assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -14103,7 +13783,7 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { const { sql: knexResolverSql, bindings: knexResolverBindings } = connection .client!.from('users') - .whereJsonSubsetOf('my_location', (q) => q.from('locations').where('my_user_id', '1')) + .whereJsonSubsetOf('my_location', (q: any) => q.from('locations').where('my_user_id', '1')) .toSQL() assert.equal(resolverSql, knexResolverSql) @@ -14113,15 +13793,15 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { }) test('define whereJsonSubset value as a subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereJsonSubset( 'location', - getQueryBuilder(getQueryClient(connection, app)).from('locations').where('user_id', '1') + getQueryBuilder(getQueryClient(connection)).from('locations').where('user_id', '1') ) .toSQL() @@ -14133,14 +13813,14 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .whereJsonSubset( 'location', - getQueryBuilder(getQueryClient(connection, app)).from('locations').where('user_id', '1') + getQueryBuilder(getQueryClient(connection)).from('locations').where('user_id', '1') ) .toSQL() @@ -14161,25 +13841,22 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { test.group('Query Builder | whereNotJsonSubset', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { - app.container.use('Adonis/Core/Event').clearListeners('db:query') await resetTables() }) test('add where not json subset clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotJsonSubset('location', { country: 'India' }) @@ -14196,7 +13873,7 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') @@ -14214,10 +13891,10 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { }) test('wrap where not json Subset clause to its own group', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotJsonSubset('location', { country: 'India' }) @@ -14242,7 +13919,7 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { /** * Using keys resolver */ - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') @@ -14268,10 +13945,10 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { }) test('add orWhereNotJsonSubset clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotJsonSubset('location', { country: 'India' }) @@ -14287,7 +13964,7 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -14309,10 +13986,10 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { }) test('wrap orWhereNotJsonSubset clause', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotJsonSubset('location', { country: 'India' }) @@ -14329,7 +14006,7 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -14352,10 +14029,10 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { }) test('define whereNotJsonSubset value as a callback', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotJsonSubset('location', (q) => q.from('locations').where('user_id', '1')) @@ -14363,13 +14040,13 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { const { sql: knexSql, bindings: knexBindings } = connection .client!.from('users') - .whereJsonNotSubsetOf('location', (q) => q.from('locations').where('user_id', '1')) + .whereJsonNotSubsetOf('location', (q: any) => q.from('locations').where('user_id', '1')) .toSQL() assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db @@ -14379,7 +14056,9 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { const { sql: knexResolverSql, bindings: knexResolverBindings } = connection .client!.from('users') - .whereJsonNotSubsetOf('my_location', (q) => q.from('locations').where('my_user_id', '1')) + .whereJsonNotSubsetOf('my_location', (q: any) => + q.from('locations').where('my_user_id', '1') + ) .toSQL() assert.equal(resolverSql, knexResolverSql) @@ -14389,15 +14068,15 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { }) test('define whereNotJsonSubset value as a subquery', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - let db = getQueryBuilder(getQueryClient(connection, app)) + let db = getQueryBuilder(getQueryClient(connection)) const { sql, bindings } = db .from('users') .whereNotJsonSubset( 'location', - getQueryBuilder(getQueryClient(connection, app)).from('locations').where('user_id', '1') + getQueryBuilder(getQueryClient(connection)).from('locations').where('user_id', '1') ) .toSQL() @@ -14412,14 +14091,14 @@ if (['pg', 'mysql'].includes(process.env.DB!)) { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) - db = getQueryBuilder(getQueryClient(connection, app)) + db = getQueryBuilder(getQueryClient(connection)) db.keysResolver = (key) => `my_${key}` const { sql: resolverSql, bindings: resolverBindings } = db .from('users') .whereNotJsonSubset( 'location', - getQueryBuilder(getQueryClient(connection, app)).from('locations').where('user_id', '1') + getQueryBuilder(getQueryClient(connection)).from('locations').where('user_id', '1') ) .toSQL() diff --git a/test/database/query-client.spec.ts b/test/database/query_client.spec.ts similarity index 70% rename from test/database/query-client.spec.ts rename to test/database/query_client.spec.ts index b6cc94c4..dd7b5e79 100644 --- a/test/database/query-client.spec.ts +++ b/test/database/query_client.spec.ts @@ -7,26 +7,26 @@ * file that was distributed with this source code. */ -/// - import { test } from '@japa/runner' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -import { Connection } from '../../src/Connection' -import { QueryClient } from '../../src/QueryClient' -import { fs, getConfig, setup, cleanup, resetTables, setupApplication } from '../../test-helpers' -let app: ApplicationContract +import { Connection } from '../../src/connection/index.js' +import { QueryClient } from '../../src/query_client/index.js' +import { + logger, + setup, + cleanup, + getConfig, + resetTables, + createEmitter, +} from '../../test-helpers/index.js' test.group('Query client', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { @@ -34,28 +34,28 @@ test.group('Query client', (group) => { }) test('get query client in dual mode', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('dual', connection, createEmitter()) assert.equal(client.mode, 'dual') await connection.disconnect() }) test('get query client in read only mode', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('read', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('read', connection, createEmitter()) assert.equal(client.mode, 'read') await connection.disconnect() }) test('get query client in write only mode', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('write', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('write', connection, createEmitter()) assert.equal(client.mode, 'write') await connection.disconnect() }) @@ -64,23 +64,23 @@ test.group('Query client', (group) => { * We cannot rely on knexjs for this and have to write our own code */ test('get query client dialect version', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('write', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('write', connection, createEmitter()) await client.rawQuery('SELECT 1 + 1 AS result') - const client1 = new QueryClient('write', connection, app.container.use('Adonis/Core/Event')) + const client1 = new QueryClient('write', connection, createEmitter()) assert.exists(client1.dialect.version) await connection.disconnect() }).skip(true) test('get columns info', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('write', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('write', connection, createEmitter()) const columns = await client.columnsInfo('users') assert.property(columns, 'id') assert.property(columns, 'country_id') @@ -95,10 +95,10 @@ test.group('Query client', (group) => { }) test('get single column info', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('write', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('write', connection, createEmitter()) const column = await client.columnsInfo('users', 'id') assert.oneOf(column.type, ['integer', 'int']) @@ -107,7 +107,7 @@ test.group('Query client', (group) => { if (process.env.DB !== 'mssql') { test('truncate table with cascade', async () => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() /** @@ -131,7 +131,7 @@ test.group('Query client', (group) => { /** * Truncate */ - const client = new QueryClient('write', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('write', connection, createEmitter()) await client.truncate('test_users', true) /** @@ -145,7 +145,7 @@ test.group('Query client', (group) => { } test('truncate a table with reserved keywork', async () => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() await connection.client?.schema.createTableIfNotExists('user', (table) => { @@ -153,7 +153,7 @@ test.group('Query client', (group) => { table.string('username') }) - const client = new QueryClient('write', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('write', connection, createEmitter()) await client.truncate('user', true) await connection.client?.schema.dropTable('user') @@ -163,13 +163,11 @@ test.group('Query client', (group) => { test.group('Query client | dual mode', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { @@ -177,9 +175,9 @@ test.group('Query client | dual mode', (group) => { }) test('perform select queries in dual mode', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('dual', connection, createEmitter()) const results = await client.query().from('users') assert.isArray(results) @@ -189,9 +187,9 @@ test.group('Query client | dual mode', (group) => { }) test('perform insert queries in dual mode', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('dual', connection, createEmitter()) await client.insertQuery().table('users').insert({ username: 'virk' }) const results = await client.query().from('users') @@ -204,9 +202,9 @@ test.group('Query client | dual mode', (group) => { }) test('perform raw queries in dual mode', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('dual', connection, createEmitter()) const command = process.env.DB === 'sqlite' || process.env.DB === 'better_sqlite' @@ -226,9 +224,9 @@ test.group('Query client | dual mode', (group) => { }) test('perform queries inside a transaction in dual mode', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('dual', connection, createEmitter()) const trx = await client.transaction() await trx.insertQuery().table('users').insert({ username: 'virk' }) @@ -245,13 +243,11 @@ test.group('Query client | dual mode', (group) => { test.group('Query client | read mode', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { @@ -259,9 +255,9 @@ test.group('Query client | read mode', (group) => { }) test('perform select queries in read mode', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('read', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('read', connection, createEmitter()) const results = await client.query().from('users') assert.isArray(results) @@ -271,9 +267,9 @@ test.group('Query client | read mode', (group) => { }) test('raise error when attempting to perform insert in read mode', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('read', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('read', connection, createEmitter()) const fn = () => client.insertQuery() assert.throws(fn, 'Write client is not available for query client instantiated in read mode') @@ -282,9 +278,9 @@ test.group('Query client | read mode', (group) => { }) test('perform raw queries in read mode', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('read', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('read', connection, createEmitter()) const result = await client.rawQuery('SELECT 1 + 1').exec() assert.isDefined(result) @@ -295,16 +291,16 @@ test.group('Query client | read mode', (group) => { test('raise error when attempting to get transaction in read mode', async ({ assert }) => { assert.plan(1) - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('read', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('read', connection, createEmitter()) try { await client.transaction() } catch ({ message }) { assert.equal( message, - 'E_RUNTIME_EXCEPTION: Write client is not available for query client instantiated in read mode' + 'Write client is not available for query client instantiated in read mode' ) } @@ -314,13 +310,11 @@ test.group('Query client | read mode', (group) => { test.group('Query client | write mode', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { @@ -328,9 +322,9 @@ test.group('Query client | write mode', (group) => { }) test('perform select queries in write mode', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('write', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('write', connection, createEmitter()) const results = await client.query().from('users') assert.isArray(results) @@ -340,9 +334,9 @@ test.group('Query client | write mode', (group) => { }) test('perform insert queries in write mode', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('write', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('write', connection, createEmitter()) await client.insertQuery().table('users').insert({ username: 'virk' }) const results = await client.query().from('users') @@ -355,9 +349,9 @@ test.group('Query client | write mode', (group) => { }) test('perform raw queries in write mode', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('write', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('write', connection, createEmitter()) const command = process.env.DB === 'sqlite' || process.env.DB === 'better_sqlite' @@ -377,9 +371,9 @@ test.group('Query client | write mode', (group) => { }) test('perform queries inside a transaction in write mode', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('write', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('write', connection, createEmitter()) const trx = await client.transaction() await trx.insertQuery().table('users').insert({ username: 'virk' }) @@ -397,13 +391,11 @@ test.group('Query client | write mode', (group) => { if (!['sqlite', 'mssql', 'better_sqlite'].includes(process.env.DB as string)) { test.group('Query client | advisory locks', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { @@ -411,10 +403,10 @@ if (!['sqlite', 'mssql', 'better_sqlite'].includes(process.env.DB as string)) { }) test('get advisory lock', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('dual', connection, createEmitter()) const lock = await client.dialect.getAdvisoryLock(1) assert.isTrue(lock) @@ -423,10 +415,10 @@ if (!['sqlite', 'mssql', 'better_sqlite'].includes(process.env.DB as string)) { }) test('release advisory lock', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('dual', connection, createEmitter()) if (client.dialect.name === 'sqlite3') { await connection.disconnect() return @@ -443,13 +435,11 @@ if (!['sqlite', 'mssql', 'better_sqlite'].includes(process.env.DB as string)) { test.group('Query client | get tables', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { @@ -457,10 +447,10 @@ test.group('Query client | get tables', (group) => { }) test('get an array of tables', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('dual', connection, createEmitter()) const tables = await client.getAllTables(['public']) if (process.env.DB !== 'mysql_legacy') { assert.deepEqual(tables, [ diff --git a/test/database/transaction_client.spec.ts b/test/database/transaction_client.spec.ts new file mode 100644 index 00000000..85f2c027 --- /dev/null +++ b/test/database/transaction_client.spec.ts @@ -0,0 +1,265 @@ +/* + * @adonisjs/lucid + * + * (c) Harminder Virk + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import { test } from '@japa/runner' + +import { Connection } from '../../src/connection/index.js' +import { QueryClient } from '../../src/query_client/index.js' +import { TransactionClient } from '../../src/transaction_client/index.js' +import { + setup, + cleanup, + getConfig, + resetTables, + logger, + createEmitter, +} from '../../test-helpers/index.js' + +test.group('Transaction | query', (group) => { + group.setup(async () => { + await setup() + }) + + group.teardown(async () => { + await cleanup() + }) + + group.each.teardown(async () => { + await resetTables() + }) + + test('perform select query under a transaction', async ({ assert }) => { + const connection = new Connection('primary', getConfig(), logger) + connection.connect() + + const db = await new QueryClient('dual', connection, createEmitter()).transaction() + const results = await db.query().from('users') + await db.commit() + + assert.isArray(results) + assert.lengthOf(results, 0) + + await connection.disconnect() + }) + + test('commit insert', async ({ assert }) => { + const connection = new Connection('primary', getConfig(), logger) + connection.connect() + + const db = await new QueryClient('dual', connection, createEmitter()).transaction() + await db.insertQuery().table('users').insert({ username: 'virk' }) + await db.commit() + + const results = await new QueryClient('dual', connection, createEmitter()).query().from('users') + assert.isArray(results) + assert.lengthOf(results, 1) + assert.equal(results[0].username, 'virk') + + await connection.disconnect() + }) + + test('rollback insert', async ({ assert }) => { + const connection = new Connection('primary', getConfig(), logger) + connection.connect() + + const db = await new QueryClient('dual', connection, createEmitter()).transaction() + await db.insertQuery().table('users').insert({ username: 'virk' }) + await db.rollback() + + const results = await new QueryClient('dual', connection, createEmitter()).query().from('users') + assert.isArray(results) + assert.lengthOf(results, 0) + + await connection.disconnect() + }) + + test('perform nested transactions with save points', async ({ assert }) => { + const connection = new Connection('primary', getConfig(), logger) + connection.connect() + + /** + * Transaction 1 + */ + const db = await new QueryClient('dual', connection, createEmitter()).transaction() + await db.insertQuery().table('users').insert({ username: 'virk' }) + + /** + * Transaction 2: Save point + */ + const db1 = await db.transaction() + await db1.insertQuery().table('users').insert({ username: 'nikk' }) + + /** + * Rollback 2 + */ + await db1.rollback() + + /** + * Commit first + */ + await db.commit() + + const results = await new QueryClient('dual', connection, createEmitter()).query().from('users') + assert.isArray(results) + assert.lengthOf(results, 1) + assert.equal(results[0].username, 'virk') + + await connection.disconnect() + }) + + test('emit after commit event', async ({ assert }) => { + const stack: string[] = [] + const connection = new Connection('primary', getConfig(), logger) + connection.connect() + + const db = await new QueryClient('dual', connection, createEmitter()).transaction() + + db.on('commit', (trx) => { + stack.push('commit') + assert.instanceOf(trx, TransactionClient) + }) + + await db.insertQuery().table('users').insert({ username: 'virk' }) + await db.commit() + + assert.deepEqual(db.listenerCount('commit'), 0) + assert.deepEqual(db.listenerCount('rollback'), 0) + assert.deepEqual(stack, ['commit']) + + await connection.disconnect() + }) + + test('emit after rollback event', async ({ assert }) => { + const stack: string[] = [] + const connection = new Connection('primary', getConfig(), logger) + connection.connect() + + const db = await new QueryClient('dual', connection, createEmitter()).transaction() + + db.on('rollback', (trx) => { + stack.push('rollback') + assert.instanceOf(trx, TransactionClient) + }) + + await db.insertQuery().table('users').insert({ username: 'virk' }) + await db.rollback() + assert.deepEqual(db.listenerCount('commit'), 0) + assert.deepEqual(db.listenerCount('rollback'), 0) + assert.deepEqual(stack, ['rollback']) + + await connection.disconnect() + }) + + test('commit insert inside a self managed transaction', async ({ assert }) => { + const connection = new Connection('primary', getConfig(), logger) + connection.connect() + + await new QueryClient('dual', connection, createEmitter()).transaction(async (db) => { + await db.insertQuery().table('users').insert({ username: 'virk' }) + }) + + const results = await new QueryClient('dual', connection, createEmitter()).query().from('users') + assert.isArray(results) + assert.lengthOf(results, 1) + assert.equal(results[0].username, 'virk') + + await connection.disconnect() + }) + + test('rollback insert inside a self managed transaction', async ({ assert }) => { + assert.plan(3) + + const connection = new Connection('primary', getConfig(), logger) + connection.connect() + + try { + await new QueryClient('dual', connection, createEmitter()).transaction(async (db) => { + await db.insertQuery().table('users').insert({ username: 'virk' }) + throw new Error('should rollback') + }) + } catch (error) { + assert.equal(error.message, 'should rollback') + } + + const results = await new QueryClient('dual', connection, createEmitter()).query().from('users') + assert.isArray(results) + assert.lengthOf(results, 0) + + await connection.disconnect() + }) + + test('perform nested managed transactions', async ({ assert }) => { + const connection = new Connection('primary', getConfig(), logger) + connection.connect() + + /** + * Transaction 1 + */ + await new QueryClient('dual', connection, createEmitter()).transaction(async (db) => { + await db.insertQuery().table('users').insert({ username: 'virk' }) + + /** + * Transaction 2: Save point + */ + await db.transaction(async (db1) => { + await db1.insertQuery().table('users').insert({ username: 'nikk' }) + + /** + * Manual callback, should work fine + */ + await db1.rollback() + }) + }) + + const results = await new QueryClient('dual', connection, createEmitter()).query().from('users') + assert.isArray(results) + assert.lengthOf(results, 1) + assert.equal(results[0].username, 'virk') + + await connection.disconnect() + }) + + test('execute after commit hook', async ({ assert }) => { + const stack: string[] = [] + const connection = new Connection('primary', getConfig(), logger) + connection.connect() + + const db = await new QueryClient('dual', connection, createEmitter()).transaction() + + db.after('commit', async () => { + stack.push('commit') + }) + + await db.insertQuery().table('users').insert({ username: 'virk' }) + await db.commit() + assert.deepEqual(stack, ['commit']) + + await connection.disconnect() + }) + + test('execute after rollback hook', async ({ assert }) => { + const stack: string[] = [] + const connection = new Connection('primary', getConfig(), logger) + connection.connect() + + const db = await new QueryClient('dual', connection, createEmitter()).transaction() + + db.after('rollback', async () => { + stack.push('rollback') + }) + + await db.insertQuery().table('users').insert({ username: 'virk' }) + await db.rollback() + assert.deepEqual(db.listenerCount('commit'), 0) + assert.deepEqual(db.listenerCount('rollback'), 0) + assert.deepEqual(stack, ['rollback']) + + await connection.disconnect() + }) +}) diff --git a/test/database/transactions.spec.ts b/test/database/transactions.spec.ts deleted file mode 100644 index 9a1f4c96..00000000 --- a/test/database/transactions.spec.ts +++ /dev/null @@ -1,422 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -/// - -import { test } from '@japa/runner' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -import { Connection } from '../../src/Connection' -import { QueryClient } from '../../src/QueryClient' -import { TransactionClient } from '../../src/TransactionClient' -import { fs, setup, cleanup, getConfig, resetTables, setupApplication } from '../../test-helpers' - -let app: ApplicationContract - -test.group('Transaction | query', (group) => { - group.setup(async () => { - app = await setupApplication() - await setup() - }) - - group.teardown(async () => { - await cleanup() - await fs.cleanup() - }) - - group.each.teardown(async () => { - await resetTables() - }) - - test('perform select query under a transaction', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) - connection.connect() - - const db = await new QueryClient( - 'dual', - connection, - app.container.use('Adonis/Core/Event') - ).transaction() - const results = await db.query().from('users') - await db.commit() - - assert.isArray(results) - assert.lengthOf(results, 0) - - await connection.disconnect() - }) - - test('commit insert', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) - connection.connect() - - const db = await new QueryClient( - 'dual', - connection, - app.container.use('Adonis/Core/Event') - ).transaction() - await db.insertQuery().table('users').insert({ username: 'virk' }) - await db.commit() - - const results = await new QueryClient( - 'dual', - connection, - app.container.use('Adonis/Core/Event') - ) - .query() - .from('users') - assert.isArray(results) - assert.lengthOf(results, 1) - assert.equal(results[0].username, 'virk') - - await connection.disconnect() - }) - - test('rollback insert', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) - connection.connect() - - const db = await new QueryClient( - 'dual', - connection, - app.container.use('Adonis/Core/Event') - ).transaction() - await db.insertQuery().table('users').insert({ username: 'virk' }) - await db.rollback() - - const results = await new QueryClient( - 'dual', - connection, - app.container.use('Adonis/Core/Event') - ) - .query() - .from('users') - assert.isArray(results) - assert.lengthOf(results, 0) - - await connection.disconnect() - }) - - test('perform nested transactions with save points', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) - connection.connect() - - /** - * Transaction 1 - */ - const db = await new QueryClient( - 'dual', - connection, - app.container.use('Adonis/Core/Event') - ).transaction() - await db.insertQuery().table('users').insert({ username: 'virk' }) - - /** - * Transaction 2: Save point - */ - const db1 = await db.transaction() - await db1.insertQuery().table('users').insert({ username: 'nikk' }) - - /** - * Rollback 2 - */ - await db1.rollback() - - /** - * Commit first - */ - await db.commit() - - const results = await new QueryClient( - 'dual', - connection, - app.container.use('Adonis/Core/Event') - ) - .query() - .from('users') - assert.isArray(results) - assert.lengthOf(results, 1) - assert.equal(results[0].username, 'virk') - - await connection.disconnect() - }) - - test('emit after commit event', async ({ assert }) => { - const stack: string[] = [] - const connection = new Connection('primary', getConfig(), app.logger) - connection.connect() - - const db = await new QueryClient( - 'dual', - connection, - app.container.use('Adonis/Core/Event') - ).transaction() - - db.on('commit', (trx) => { - stack.push('commit') - assert.instanceOf(trx, TransactionClient) - }) - - await db.insertQuery().table('users').insert({ username: 'virk' }) - await db.commit() - - assert.deepEqual(db.listenerCount('commit'), 0) - assert.deepEqual(db.listenerCount('rollback'), 0) - assert.deepEqual(stack, ['commit']) - - await connection.disconnect() - }) - - test('emit after rollback event', async ({ assert }) => { - const stack: string[] = [] - const connection = new Connection('primary', getConfig(), app.logger) - connection.connect() - - const db = await new QueryClient( - 'dual', - connection, - app.container.use('Adonis/Core/Event') - ).transaction() - - db.on('rollback', (trx) => { - stack.push('rollback') - assert.instanceOf(trx, TransactionClient) - }) - - await db.insertQuery().table('users').insert({ username: 'virk' }) - await db.rollback() - assert.deepEqual(db.listenerCount('commit'), 0) - assert.deepEqual(db.listenerCount('rollback'), 0) - assert.deepEqual(stack, ['rollback']) - - await connection.disconnect() - }) - - test('commit insert inside a self managed transaction', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) - connection.connect() - - await new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')).transaction( - async (db) => { - await db.insertQuery().table('users').insert({ username: 'virk' }) - } - ) - - const results = await new QueryClient( - 'dual', - connection, - app.container.use('Adonis/Core/Event') - ) - .query() - .from('users') - assert.isArray(results) - assert.lengthOf(results, 1) - assert.equal(results[0].username, 'virk') - - await connection.disconnect() - }) - - test('rollback insert inside a self managed transaction', async ({ assert }) => { - assert.plan(3) - - const connection = new Connection('primary', getConfig(), app.logger) - connection.connect() - - try { - await new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')).transaction( - async (db) => { - await db.insertQuery().table('users').insert({ username: 'virk' }) - throw new Error('should rollback') - } - ) - } catch (error) { - assert.equal(error.message, 'should rollback') - } - - const results = await new QueryClient( - 'dual', - connection, - app.container.use('Adonis/Core/Event') - ) - .query() - .from('users') - assert.isArray(results) - assert.lengthOf(results, 0) - - await connection.disconnect() - }) - - test('perform nested managed transactions', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) - connection.connect() - - /** - * Transaction 1 - */ - await new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')).transaction( - async (db) => { - await db.insertQuery().table('users').insert({ username: 'virk' }) - - /** - * Transaction 2: Save point - */ - await db.transaction(async (db1) => { - await db1.insertQuery().table('users').insert({ username: 'nikk' }) - - /** - * Manual callback, should work fine - */ - await db1.rollback() - }) - } - ) - - const results = await new QueryClient( - 'dual', - connection, - app.container.use('Adonis/Core/Event') - ) - .query() - .from('users') - assert.isArray(results) - assert.lengthOf(results, 1) - assert.equal(results[0].username, 'virk') - - await connection.disconnect() - }) - - test('nest transaction queries inside profiler row', async ({ assert }) => { - const stack: { id: string; parentId: string | undefined; label: string; data: any }[] = [] - const connection = new Connection('primary', getConfig(), app.logger) - connection.connect() - - const profiler = app.profiler - const client = new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')) - client.profiler = profiler - - profiler.process((log) => { - stack.push({ id: log['id'], parentId: log.parent_id, label: log.label, data: log.data }) - }) - - const db = await client.transaction() - await db.insertQuery().table('users').insert({ username: 'virk' }) - await db.commit() - - assert.lengthOf(stack, 2) - assert.equal(stack[0].label, 'db:query') - assert.equal(stack[1].label, 'trx:begin') - assert.equal(stack[0].parentId, stack[1].id) - assert.deepEqual(stack[1].data, { state: 'commit' }) - - await connection.disconnect() - }) - - test('nest save points queries inside profiler row', async ({ assert }) => { - const stack: { id: string; parentId: string | undefined; label: string; data: any }[] = [] - const connection = new Connection('primary', getConfig(), app.logger) - connection.connect() - - const profiler = app.profiler - const client = new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')) - client.profiler = profiler - - profiler.process((log) => { - stack.push({ id: log['id'], parentId: log.parent_id, label: log.label, data: log.data }) - }) - - const db = await client.transaction() - const nested = await db.transaction() - await nested.insertQuery().table('users').insert({ username: 'virk' }) - await nested.rollback() - await db.commit() - - assert.lengthOf(stack, 3) - assert.equal(stack[0].label, 'db:query') - assert.equal(stack[1].label, 'trx:begin') - assert.equal(stack[2].label, 'trx:begin') - assert.equal(stack[0].parentId, stack[1].id) - assert.deepEqual(stack[1].data, { state: 'rollback' }) - assert.deepEqual(stack[2].data, { state: 'commit' }) - assert.equal(stack[1].parentId, stack[2].id) - - await connection.disconnect() - }) - - test('nest transaction queries inside managed transaction', async ({ assert }) => { - const stack: { id: string; parentId: string | undefined; label: string; data: any }[] = [] - const connection = new Connection('primary', getConfig(), app.logger) - connection.connect() - - const profiler = app.profiler - const client = new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')) - client.profiler = profiler - - profiler.process((log) => { - stack.push({ id: log['id'], parentId: log.parent_id, label: log.label, data: log.data }) - }) - - await client.transaction(async (db) => { - await db.insertQuery().table('users').insert({ username: 'virk' }) - }) - - assert.lengthOf(stack, 2) - assert.equal(stack[0].label, 'db:query') - assert.equal(stack[1].label, 'trx:begin') - assert.equal(stack[0].parentId, stack[1].id) - assert.deepEqual(stack[1].data, { state: 'commit' }) - - await connection.disconnect() - }) - - test('execute after commit hook', async ({ assert }) => { - const stack: string[] = [] - const connection = new Connection('primary', getConfig(), app.logger) - connection.connect() - - const db = await new QueryClient( - 'dual', - connection, - app.container.use('Adonis/Core/Event') - ).transaction() - - db.after('commit', async () => { - stack.push('commit') - }) - - await db.insertQuery().table('users').insert({ username: 'virk' }) - await db.commit() - assert.deepEqual(stack, ['commit']) - - await connection.disconnect() - }) - - test('execute after rollback hook', async ({ assert }) => { - const stack: string[] = [] - const connection = new Connection('primary', getConfig(), app.logger) - connection.connect() - - const db = await new QueryClient( - 'dual', - connection, - app.container.use('Adonis/Core/Event') - ).transaction() - - db.after('rollback', async () => { - stack.push('rollback') - }) - - await db.insertQuery().table('users').insert({ username: 'virk' }) - await db.rollback() - assert.deepEqual(db.listenerCount('commit'), 0) - assert.deepEqual(db.listenerCount('rollback'), 0) - assert.deepEqual(stack, ['rollback']) - - await connection.disconnect() - }) -}) diff --git a/test/database/views-types.spec.ts b/test/database/views_types.spec.ts similarity index 71% rename from test/database/views-types.spec.ts rename to test/database/views_types.spec.ts index 39d7a448..02309019 100644 --- a/test/database/views-types.spec.ts +++ b/test/database/views_types.spec.ts @@ -1,33 +1,33 @@ -/// +/* + * @adonisjs/lucid + * + * (c) Harminder Virk + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ import { test } from '@japa/runner' -import { join } from 'path' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' -import { Connection } from '../../src/Connection' -import { QueryClient } from '../../src/QueryClient' -import { fs, getConfig, setup, cleanup, setupApplication } from '../../test-helpers' - -let app: ApplicationContract +import { Connection } from '../../src/connection/index.js' +import { QueryClient } from '../../src/query_client/index.js' +import { getConfig, setup, cleanup, logger, createEmitter } from '../../test-helpers/index.js' test.group('Query client | Views and types', (group) => { group.setup(async () => { - app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup(['temp_posts', 'temp_users']) await cleanup() - await fs.cleanup() }) if (['sqlite', 'mysql', 'pg'].includes(process.env.DB!)) { test('Get all views', async ({ assert }) => { - await fs.fsExtra.ensureDir(join(fs.basePath, 'temp')) - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('dual', connection, createEmitter()) await connection.client!.schema.createView('users_view', async (view) => { view.columns(['username', 'email']) @@ -47,10 +47,9 @@ test.group('Query client | Views and types', (group) => { }) test('Drop all views', async ({ assert }) => { - await fs.fsExtra.ensureDir(join(fs.basePath, 'temp')) - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('dual', connection, createEmitter()) await connection.client!.schema.createView('users_view', async (view) => { view.columns(['username', 'email']) @@ -76,10 +75,9 @@ test.group('Query client | Views and types', (group) => { if (['pg'].includes(process.env.DB!)) { test('Get all types', async ({ assert }) => { - await fs.fsExtra.ensureDir(join(fs.basePath, 'temp')) - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('dual', connection, createEmitter()) await client.rawQuery(`CREATE TYPE "user_type" AS ENUM ('admin', 'user')`) const types = await client.getAllTypes(['public']) @@ -92,10 +90,9 @@ test.group('Query client | Views and types', (group) => { }) test('Drop all types', async ({ assert }) => { - await fs.fsExtra.ensureDir(join(fs.basePath, 'temp')) - const connection = new Connection('primary', getConfig(), app.logger) + const connection = new Connection('primary', getConfig(), logger) connection.connect() - const client = new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')) + const client = new QueryClient('dual', connection, createEmitter()) await client.rawQuery(`CREATE TYPE "user_type" AS ENUM ('admin', 'user')`) await client.dropAllTypes() diff --git a/test/orm/base-model.spec.ts b/test/orm/base-model.spec.ts index 4355d023..3f934f19 100644 --- a/test/orm/base-model.spec.ts +++ b/test/orm/base-model.spec.ts @@ -633,7 +633,10 @@ test.group('Base Model | dirty', (group) => { test('compute diff for properties represented as classes', async ({ assert }) => { class Location { public isDirty = false - constructor(public state: string, public country: string) {} + constructor( + public state: string, + public country: string + ) {} } const adapter = new FakeAdapter() @@ -4575,7 +4578,7 @@ test.group('Base Model | hooks', (group) => { @beforePaginate() public static beforePaginateHook([countQuery, query]: [ ModelQueryBuilder, - ModelQueryBuilder + ModelQueryBuilder, ]) { assert.instanceOf(query, ModelQueryBuilder) assert.instanceOf(countQuery, ModelQueryBuilder) diff --git a/tsconfig.json b/tsconfig.json index c5618183..ad0cc44a 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,13 +1,7 @@ { - "extends": "./node_modules/@adonisjs/mrm-preset/_tsconfig", + "extends": "@adonisjs/tsconfig/tsconfig.package.json", "compilerOptions": { - "experimentalDecorators": true, - "emitDecoratorMetadata": true, - "skipLibCheck": true, - "useDefineForClassFields": true - }, - "files": [ - "./node_modules/@adonisjs/core/build/adonis-typings/index.d.ts", - "./node_modules/@adonisjs/repl/build/adonis-typings/index.d.ts" - ] + "rootDir": "./", + "outDir": "./build" + } } From c523cc2ad39a00b8566a1a2545ba953f1ccf42eb Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Sat, 16 Sep 2023 16:05:31 +0530 Subject: [PATCH 02/70] refactor: migrate schema module --- bin/test.ts | 5 +- src/{Migrator => migrator}/index.ts | 123 +++++++++--------- .../migration_source.ts} | 17 ++- src/{Schema => schema}/index.ts | 47 +++---- src/utils/index.ts | 13 +- test-helpers/index.ts | 2 +- ...ource.spec.ts => migration_source.spec.ts} | 70 +++++----- 7 files changed, 147 insertions(+), 130 deletions(-) rename src/{Migrator => migrator}/index.ts (83%) rename src/{Migrator/MigrationSource.ts => migrator/migration_source.ts} (77%) rename src/{Schema => schema}/index.ts (79%) rename test/migrations/{migration-source.spec.ts => migration_source.spec.ts} (57%) diff --git a/bin/test.ts b/bin/test.ts index 55c5501d..89cef804 100644 --- a/bin/test.ts +++ b/bin/test.ts @@ -18,7 +18,10 @@ import { processCLIArgs, configure, run } from '@japa/runner' processCLIArgs(process.argv.slice(2)) configure({ files: ['test/**/*.spec.ts'], - plugins: [assert(), fileSystem()], + plugins: [ + assert(), + fileSystem({ basePath: new URL('../test-helpers/fs-plugin/', import.meta.url) }), + ], }) /* diff --git a/src/Migrator/index.ts b/src/migrator/index.ts similarity index 83% rename from src/Migrator/index.ts rename to src/migrator/index.ts index a28524de..04af3cec 100644 --- a/src/Migrator/index.ts +++ b/src/migrator/index.ts @@ -7,55 +7,47 @@ * file that was distributed with this source code. */ -/// - import slash from 'slash' -import { EventEmitter } from 'events' +import { EventEmitter } from 'node:events' import { Exception } from '@poppinss/utils' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' -import { SchemaConstructorContract } from '@ioc:Adonis/Lucid/Schema' - import { MigratorOptions, MigratedFileNode, - MigratorContract, MigrationListNode, -} from '@ioc:Adonis/Lucid/Migrator' +} from '../../adonis-typings/migrator.js' import { FileNode, - DatabaseContract, + MigratorConfig, QueryClientContract, + SharedConfigNode, TransactionClientContract, -} from '@ioc:Adonis/Lucid/Database' +} from '../../adonis-typings/database.js' -import { MigrationSource } from './MigrationSource' +import { MigrationSource } from './migration_source.js' +import { Database } from '../database/index.js' +import { Application } from '@adonisjs/core/app' +import { Schema } from '../schema/index.js' /** * Migrator exposes the API to execute migrations using the schema files * for a given connection at a time. */ -export class Migrator extends EventEmitter implements MigratorContract { - private client = this.db.connection(this.options.connectionName || this.db.primaryConnectionName) - private config = this.db.getRawConnection(this.client.connectionName)!.config +export class Migrator extends EventEmitter { + private client: QueryClientContract + private config: SharedConfigNode /** * Reference to the migrations config for the given connection */ - private migrationsConfig = Object.assign( - { - tableName: 'adonis_schema', - disableTransactions: false, - }, - this.config.migrations - ) + private migrationsConfig: MigratorConfig /** * Table names for storing schema files and schema versions */ - private schemaTableName = this.migrationsConfig.tableName - private schemaVersionsTableName = `${this.schemaTableName}_versions` + private schemaTableName: string + private schemaVersionsTableName: string /** * Whether or not the migrator has been booted @@ -65,7 +57,7 @@ export class Migrator extends EventEmitter implements MigratorContract { /** * Migration source to collect schema files from the disk */ - private migrationSource = new MigrationSource(this.config, this.app) + private migrationSource: MigrationSource /** * Mode decides in which mode the migrator is executing migrations. The migrator @@ -73,33 +65,33 @@ export class Migrator extends EventEmitter implements MigratorContract { * * The value is set when `migrate` or `rollback` method is invoked */ - public direction: 'up' | 'down' = this.options.direction + direction: 'up' | 'down' /** * Instead of executing migrations, just return the generated SQL queries */ - public dryRun: boolean = !!this.options.dryRun + dryRun: boolean /** * Disable advisory locks */ - public disableLocks: boolean = !!this.options.disableLocks + disableLocks: boolean /** * An array of files we have successfully migrated. The files are * collected regardless of `up` or `down` methods */ - public migratedFiles: { [file: string]: MigratedFileNode } = {} + migratedFiles: { [file: string]: MigratedFileNode } = {} /** * Last error occurred when executing migrations */ - public error: null | Error = null + error: null | Error = null /** * Current status of the migrator */ - public get status() { + get status() { return !this.booted ? 'pending' : this.error @@ -114,14 +106,29 @@ export class Migrator extends EventEmitter implements MigratorContract { * existing migrations if we are plan to make a breaking * change. */ - public version: number = 2 + version: number = 2 constructor( - private db: DatabaseContract, - private app: ApplicationContract, + private db: Database, + private app: Application, private options: MigratorOptions ) { super() + this.client = this.db.connection(this.options.connectionName || this.db.primaryConnectionName) + this.config = this.db.getRawConnection(this.client.connectionName)!.config + this.migrationsConfig = Object.assign( + { + tableName: 'adonis_schema', + disableTransactions: false, + }, + this.config.migrations + ) + this.schemaTableName = this.migrationsConfig.tableName! + this.schemaVersionsTableName = `${this.schemaTableName}_versions` + this.migrationSource = new MigrationSource(this.config, this.app) + this.direction = this.options.direction + this.dryRun = !!this.options.dryRun + this.disableLocks = !!this.options.disableLocks } /** @@ -202,12 +209,10 @@ export class Migrator extends EventEmitter implements MigratorContract { * Returns the migration source by ensuring value is a class constructor and * has disableTransactions property. */ - private async getMigrationSource( - migration: FileNode - ): Promise { + private async getMigrationSource(migration: FileNode): Promise { const source = await migration.getSource() if (typeof source === 'function' && 'disableTransactions' in source) { - return source + return source as typeof Schema } throw new Error(`Invalid schema class exported by "${migration.name}"`) @@ -218,11 +223,11 @@ export class Migrator extends EventEmitter implements MigratorContract { * in case of failure */ private async executeMigration(migration: FileNode) { - const Schema = await this.getMigrationSource(migration) + const SchemaClass = await this.getMigrationSource(migration) const client = await this.getClient(Schema.disableTransactions) try { - const schema = new Schema(client, migration.name, this.dryRun) + const schema = new SchemaClass(client, migration.name, this.dryRun) this.emit('migration:start', this.migratedFiles[migration.name]) if (this.direction === 'up') { @@ -482,11 +487,10 @@ export class Migrator extends EventEmitter implements MigratorContract { existing.forEach((file) => { const migration = collected.find(({ name }) => name === file.name) if (!migration) { - throw new Exception( - `Cannot perform rollback. Schema file {${file.name}} is missing`, - 500, - 'E_MISSING_SCHEMA_FILES' - ) + throw new Exception(`Cannot perform rollback. Schema file {${file.name}} is missing`, { + status: 500, + code: 'E_MISSING_SCHEMA_FILES', + }) } this.migratedFiles[migration.name] = { @@ -503,27 +507,24 @@ export class Migrator extends EventEmitter implements MigratorContract { } } - public on(event: 'start', callback: () => void): this - public on(event: 'end', callback: () => void): this - public on(event: 'acquire:lock', callback: () => void): this - public on(event: 'release:lock', callback: () => void): this - public on(event: 'create:schema:table', callback: () => void): this - public on(event: 'create:schema_versions:table', callback: () => void): this - public on( - event: 'upgrade:version', - callback: (payload: { from: number; to: number }) => void - ): this - public on(event: 'migration:start', callback: (file: MigratedFileNode) => void): this - public on(event: 'migration:completed', callback: (file: MigratedFileNode) => void): this - public on(event: 'migration:error', callback: (file: MigratedFileNode) => void): this - public on(event: string, callback: (...args: any[]) => void): this { + on(event: 'start', callback: () => void): this + on(event: 'end', callback: () => void): this + on(event: 'acquire:lock', callback: () => void): this + on(event: 'release:lock', callback: () => void): this + on(event: 'create:schema:table', callback: () => void): this + on(event: 'create:schema_versions:table', callback: () => void): this + on(event: 'upgrade:version', callback: (payload: { from: number; to: number }) => void): this + on(event: 'migration:start', callback: (file: MigratedFileNode) => void): this + on(event: 'migration:completed', callback: (file: MigratedFileNode) => void): this + on(event: 'migration:error', callback: (file: MigratedFileNode) => void): this + on(event: string, callback: (...args: any[]) => void): this { return super.on(event, callback) } /** * Returns a merged list of completed and pending migrations */ - public async getList(): Promise { + async getList(): Promise { const existingCollected: Set = new Set() await this.makeMigrationsTable() const existing = await this.getMigratedFilesTillBatch(0) @@ -568,7 +569,7 @@ export class Migrator extends EventEmitter implements MigratorContract { /** * Migrate the database by calling the up method */ - public async run() { + async run() { try { await this.boot() @@ -596,7 +597,7 @@ export class Migrator extends EventEmitter implements MigratorContract { /** * Close database connections */ - public async close() { + async close() { await this.db.manager.closeAll(true) } } diff --git a/src/Migrator/MigrationSource.ts b/src/migrator/migration_source.ts similarity index 77% rename from src/Migrator/MigrationSource.ts rename to src/migrator/migration_source.ts index d622e0d3..bf81b6f1 100644 --- a/src/Migrator/MigrationSource.ts +++ b/src/migrator/migration_source.ts @@ -7,11 +7,9 @@ * file that was distributed with this source code. */ -/// - -import { ApplicationContract } from '@ioc:Adonis/Core/Application' -import { ConnectionConfig, FileNode } from '@ioc:Adonis/Lucid/Database' -import { sourceFiles } from '../utils' +import type { Application } from '@adonisjs/core/app' +import { sourceFiles } from '../utils/index.js' +import { SharedConfigNode, FileNode } from '../../adonis-typings/database.js' /** * Migration source exposes the API to read the migration files @@ -19,8 +17,8 @@ import { sourceFiles } from '../utils' */ export class MigrationSource { constructor( - private config: ConnectionConfig, - private app: ApplicationContract + private config: SharedConfigNode, + private app: Application ) {} /** @@ -43,14 +41,15 @@ export class MigrationSource { */ private getMigrationsPath(): string[] { const directories = (this.config.migrations || {}).paths - const defaultDirectory = this.app.directoriesMap.get('migrations') || 'database/migrations' + const defaultDirectory = + this.app.relativePath(this.app.migrationsPath()) || 'database/migrations' return directories && directories.length ? directories : [`./${defaultDirectory}`] } /** * Returns an array of files for all defined directories */ - public async getMigrations() { + async getMigrations() { const migrationPaths = this.getMigrationsPath() const directories = await Promise.all( migrationPaths.map((directoryPath) => { diff --git a/src/Schema/index.ts b/src/schema/index.ts similarity index 79% rename from src/Schema/index.ts rename to src/schema/index.ts index b099433a..caf94a7f 100644 --- a/src/Schema/index.ts +++ b/src/schema/index.ts @@ -7,20 +7,19 @@ * file that was distributed with this source code. */ -/// - import { Knex } from 'knex' import { Exception } from '@poppinss/utils' -import { QueryReporter } from '../QueryReporter' -import { QueryClientContract } from '@ioc:Adonis/Lucid/Database' -import { SchemaContract, DeferCallback } from '@ioc:Adonis/Lucid/Schema' -import { getDDLMethod } from '../utils' +import { getDDLMethod } from '../utils/index.js' +import { QueryReporter } from '../query_reporter/index.js' +import { DeferCallback } from '../../adonis-typings/schema.js' +import { QueryClientContract } from '../../adonis-typings/database.js' +import { RawQueryBindings } from '../../adonis-typings/querybuilder.js' /** * Exposes the API to define table schema using deferred database * calls. */ -export class Schema implements SchemaContract { +export class Schema { /** * All calls to `schema` and `defer` are tracked to be * executed later @@ -35,12 +34,12 @@ export class Schema implements SchemaContract { /** * Enable/disable transactions for this schema */ - public static disableTransactions = false + static disableTransactions = false /** * Returns the schema to build database tables */ - public get schema() { + get schema() { const schema = this.db.schema this.trackedCalls.push(schema) return schema @@ -50,20 +49,22 @@ export class Schema implements SchemaContract { * Control whether to debug the query or not. The initial * value is inherited from the query client */ - public debug: boolean = this.db.debug + debug: boolean constructor( public db: QueryClientContract, public file: string, public dryRun: boolean = false - ) {} + ) { + this.debug = this.db.debug + } /** * Returns schema queries sql without executing them */ private getQueries(): string[] { return this.trackedCalls - .filter((schema) => typeof schema['toQuery'] === 'function') + .filter((schema: any) => typeof schema['toQuery'] === 'function') .map((schema) => (schema as Knex.SchemaBuilder).toQuery()) } @@ -98,7 +99,9 @@ export class Schema implements SchemaContract { const reporter = this.getReporter() try { - trackedCall['once']('query', (sql: Knex.Sql) => reporter.begin(this.getQueryData(sql))) + ;(trackedCall as any)['once']('query', (sql: Knex.Sql) => + reporter.begin(this.getQueryData(sql)) + ) await trackedCall reporter.end() } catch (error) { @@ -112,7 +115,7 @@ export class Schema implements SchemaContract { /** * Returns raw query for `now` */ - public now(precision?: number) { + now(precision?: number) { return precision ? this.db.knexRawQuery(`CURRENT_TIMESTAMP(${precision})`) : this.db.knexRawQuery('CURRENT_TIMESTAMP') @@ -121,14 +124,14 @@ export class Schema implements SchemaContract { /** * Instance of raw knex query builder */ - public raw(query: string, bindings?: any[]) { - return this.db.knexRawQuery(query, bindings) + raw(sql: string, bindings?: RawQueryBindings): Knex.Raw { + return this.db.knexRawQuery(sql, bindings) } /** * Get access to the underlying knex query builder */ - public knex() { + knex() { return this.db.knexQuery() } @@ -137,7 +140,7 @@ export class Schema implements SchemaContract { * in the right order and also they won't be executed when * schema is invoked to return the SQL queries */ - public defer(cb: DeferCallback): void { + defer(cb: DeferCallback): void { this.trackedCalls.push(cb) } @@ -145,7 +148,7 @@ export class Schema implements SchemaContract { * Invokes schema `up` method. Returns an array of queries * when `dryRun` is set to true */ - public async execUp() { + async execUp() { if (this.state === 'completed') { throw new Exception('Cannot execute a given schema twice') } @@ -165,7 +168,7 @@ export class Schema implements SchemaContract { * Invokes schema `down` method. Returns an array of queries * when `dryRun` is set to true */ - public async execDown() { + async execDown() { if (this.state === 'completed') { throw new Exception('Cannot execute a given schema twice') } @@ -181,6 +184,6 @@ export class Schema implements SchemaContract { return true } - public async up() {} - public async down() {} + async up() {} + async down() {} } diff --git a/src/utils/index.ts b/src/utils/index.ts index dd8af42f..ff0b2a69 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -9,7 +9,7 @@ import slash from 'slash' import { join, extname } from 'node:path' -import { Exception, fsImportAll } from '@poppinss/utils' +import { Exception, fsReadAll, isScriptFile } from '@poppinss/utils' import { RelationshipsContract } from '../../adonis-typings/relations.js' import { LucidRow, ModelObject, CherryPickFields } from '../../adonis-typings/model.js' import { @@ -17,6 +17,7 @@ import { QueryClientContract, TransactionClientContract, } from '../../adonis-typings/database.js' +import { fileURLToPath, pathToFileURL } from 'node:url' /** * Ensure that relation is defined @@ -205,12 +206,14 @@ export function normalizeCherryPickObject(fields: CherryPickFields) { * Sources files from a given directory */ export async function sourceFiles( - fromLocation: string, + fromLocation: URL, directory: string, naturalSort: boolean ): Promise<{ directory: string; files: FileNode[] }> { - const absDirectoryPath = join(fromLocation, directory) - let files = await fsImportAll(absDirectoryPath) + const absDirectoryPath = fileURLToPath(new URL(directory, fromLocation)) + let files = await fsReadAll(absDirectoryPath, { + filter: isScriptFile, + }) /** * Sort files @@ -243,7 +246,7 @@ export async function sourceFiles( * Import schema file */ getSource() { - return esmRequire(this.absPath) + return import(pathToFileURL(this.absPath).href) }, } }), diff --git a/test-helpers/index.ts b/test-helpers/index.ts index 7606f4cf..0368381b 100644 --- a/test-helpers/index.ts +++ b/test-helpers/index.ts @@ -55,7 +55,7 @@ dotenv.config() export const APP_ROOT = new URL('./tmp', import.meta.url) export const SQLITE_BASE_PATH = fileURLToPath(APP_ROOT) -export const app = new AppFactory().create(APP_ROOT, () => {}) +const app = new AppFactory().create(APP_ROOT, () => {}) export const emitter = new Emitter(app) export const logger = new Logger({}) export const createEmitter = () => new Emitter(app) diff --git a/test/migrations/migration-source.spec.ts b/test/migrations/migration_source.spec.ts similarity index 57% rename from test/migrations/migration-source.spec.ts rename to test/migrations/migration_source.spec.ts index cc3c59c7..fbc30731 100644 --- a/test/migrations/migration-source.spec.ts +++ b/test/migrations/migration_source.spec.ts @@ -7,36 +7,31 @@ * file that was distributed with this source code. */ -/// - -import { join } from 'path' import { test } from '@japa/runner' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -import { MigrationSource } from '../../src/Migrator/MigrationSource' -import { setup, getDb, resetTables, setupApplication, fs } from '../../test-helpers' -let app: ApplicationContract -let db: ReturnType +import { MigrationSource } from '../../src/migrator/migration_source.js' +import { setup, getDb, resetTables } from '../../test-helpers/index.js' +import { AppFactory } from '@adonisjs/core/factories/app' +import { join } from 'node:path' test.group('MigrationSource', (group) => { group.each.setup(async () => { - app = await setupApplication() - db = getDb(app) await setup() }) group.each.teardown(async () => { - await db.manager.closeAll() await resetTables() - await fs.cleanup() }) - test('get list of migration files from database/migrations.js', async ({ assert }) => { + test('get list of migration files from database/migrations directory', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + + const db = getDb() const migrationSource = new MigrationSource(db.getRawConnection('primary')!.config, app) - await fs.add('database/migrations/foo.js', 'module.exports = class Foo {}') - await fs.add('database/migrations/bar.js', 'module.exports = class Bar {}') + await fs.create('database/migrations/foo.js', 'module.exports = class Foo {}') + await fs.create('database/migrations/bar.js', 'module.exports = class Bar {}') const directories = await migrationSource.getMigrations() @@ -57,11 +52,15 @@ test.group('MigrationSource', (group) => { ) }) - test('only use javascript files for migration', async ({ assert }) => { + test('only collect javascript files for migration', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + + const db = getDb() const migrationSource = new MigrationSource(db.getRawConnection('primary')!.config, app) - await fs.add('database/migrations/foo.js', 'module.exports = class Foo {}') - await fs.add('database/migrations/foo.js.map', '{}') + await fs.create('database/migrations/foo.js', 'module.exports = class Foo {}') + await fs.create('database/migrations/foo.js.map', '{}') const directories = await migrationSource.getMigrations() @@ -78,7 +77,11 @@ test.group('MigrationSource', (group) => { ) }) - test('sort multiple migration directories seperately', async ({ assert }) => { + test('sort multiple migration directories seperately', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const config = Object.assign({}, db.getRawConnection('primary')!.config, { migrations: { paths: ['./database/secondary', './database/primary'], @@ -87,11 +90,11 @@ test.group('MigrationSource', (group) => { const migrationSource = new MigrationSource(config, app) - await fs.add('database/secondary/a.js', 'module.exports = class Foo {}') - await fs.add('database/secondary/c.js', 'module.exports = class Bar {}') + await fs.create('database/secondary/a.js', 'module.exports = class Foo {}') + await fs.create('database/secondary/c.js', 'module.exports = class Bar {}') - await fs.add('database/primary/b.js', 'module.exports = class Foo {}') - await fs.add('database/primary/d.js', 'module.exports = class Bar {}') + await fs.create('database/primary/b.js', 'module.exports = class Foo {}') + await fs.create('database/primary/d.js', 'module.exports = class Bar {}') const files = await migrationSource.getMigrations() @@ -120,16 +123,21 @@ test.group('MigrationSource', (group) => { ) }) - test('handle esm default exports properly', async ({ assert }) => { + test('handle esm default exports properly', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const migrationSource = new MigrationSource(db.getRawConnection('primary')!.config, app) - await fs.add('database/migrations/foo.ts', 'export default class Foo {}') - await fs.add('database/migrations/bar.ts', 'export default class Bar {}') - await fs.add('database/migrations/baz.ts', 'export default class Baz {}') + await fs.create('database/migrations/foo.ts', 'export default class Foo {}') + await fs.create('database/migrations/bar.ts', 'export default class Bar {}') + await fs.create('database/migrations/baz.ts', 'export default class Baz {}') const directories = await migrationSource.getMigrations() - assert.equal((directories[0].getSource() as any).name, 'Bar') - assert.equal((directories[1].getSource() as any).name, 'Baz') - assert.equal((directories[2].getSource() as any).name, 'Foo') + console.log(await directories[0].getSource()) + // assert.equal((await directories[0].getSource()).name, 'Bar') + // assert.equal(await directories[1].getSource().name, 'Baz') + // assert.equal(await directories[2].getSource().name, 'Foo') }) }) From 26c746669fa75f2e79b536bb8685b12995122c22 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Sat, 16 Sep 2023 16:35:48 +0530 Subject: [PATCH 03/70] refactor: migrate migrations module --- src/migrator/index.ts | 8 +- src/utils/index.ts | 10 +- test-helpers/index.ts | 17 +- test/migrations/migration_source.spec.ts | 12 +- test/migrations/migrator.spec.ts | 471 ++++++++++++++--------- test/migrations/schema.spec.ts | 154 ++++++-- 6 files changed, 428 insertions(+), 244 deletions(-) diff --git a/src/migrator/index.ts b/src/migrator/index.ts index 04af3cec..4ed4a092 100644 --- a/src/migrator/index.ts +++ b/src/migrator/index.ts @@ -59,6 +59,11 @@ export class Migrator extends EventEmitter { */ private migrationSource: MigrationSource + /** + * Flag to know if running the app in production + */ + isInProduction: boolean + /** * Mode decides in which mode the migrator is executing migrations. The migrator * instance can only run in one mode at a time. @@ -129,6 +134,7 @@ export class Migrator extends EventEmitter { this.direction = this.options.direction this.dryRun = !!this.options.dryRun this.disableLocks = !!this.options.disableLocks + this.isInProduction = app.inProduction } /** @@ -467,7 +473,7 @@ export class Migrator extends EventEmitter { * Migrate down (aka rollback) */ private async runDown(batch?: number) { - if (this.app.inProduction && this.migrationsConfig.disableRollbacksInProduction) { + if (this.isInProduction && this.migrationsConfig.disableRollbacksInProduction) { throw new Error( 'Rollback in production environment is disabled. Check "config/database" file for options.' ) diff --git a/src/utils/index.ts b/src/utils/index.ts index ff0b2a69..bda238eb 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -213,6 +213,7 @@ export async function sourceFiles( const absDirectoryPath = fileURLToPath(new URL(directory, fromLocation)) let files = await fsReadAll(absDirectoryPath, { filter: isScriptFile, + ignoreMissingRoot: true, }) /** @@ -245,8 +246,13 @@ export async function sourceFiles( /** * Import schema file */ - getSource() { - return import(pathToFileURL(this.absPath).href) + async getSource() { + const exports = await import(pathToFileURL(this.absPath).href) + if (!exports.default) { + throw new Error(`Missing default export from "${this.name}" schema file`) + } + + return exports.default }, } }), diff --git a/test-helpers/index.ts b/test-helpers/index.ts index 0368381b..4ff2ada3 100644 --- a/test-helpers/index.ts +++ b/test-helpers/index.ts @@ -39,6 +39,9 @@ import { Database } from '../src/database/index.js' import { DatabaseQueryBuilder } from '../src/database/query_builder/database.js' import { RawQueryBuilder } from '../src/database/query_builder/raw.js' import { InsertQueryBuilder } from '../src/database/query_builder/insert.js' +import { Migrator } from '../src/migrator/index.js' +import { Application } from '@adonisjs/core/app' +import { Schema } from '../src/schema/index.js' // import { Schema } from '../src/Schema' // import { Migrator } from '../src/Migrator' @@ -400,7 +403,7 @@ export function getInsertBuilder(client: QueryClientContract) { /** * Returns the database instance */ -export function getDb() { +export function getDb(eventEmitter?: Emitter) { const config = { connection: 'primary', connections: { @@ -409,7 +412,7 @@ export function getDb() { }, } - return new Database(config, logger, createEmitter()) + return new Database(config, logger, eventEmitter || createEmitter()) } /** @@ -549,18 +552,14 @@ export function mapToObj(collection: Map): T { * Returns the base schema class typed to it's interface */ export function getBaseSchema() { - return Schema as SchemaConstructorContract + return Schema } /** * Returns instance of migrator */ -export function getMigrator( - db: DatabaseContract, - app: ApplicationContract, - config: MigratorOptions -) { - return new Migrator(db, app, config) as MigratorContract +export function getMigrator(db: Database, application: Application, config: MigratorOptions) { + return new Migrator(db, application, config) } /** diff --git a/test/migrations/migration_source.spec.ts b/test/migrations/migration_source.spec.ts index fbc30731..ce17057c 100644 --- a/test/migrations/migration_source.spec.ts +++ b/test/migrations/migration_source.spec.ts @@ -7,12 +7,12 @@ * file that was distributed with this source code. */ +import { join } from 'node:path' import { test } from '@japa/runner' +import { AppFactory } from '@adonisjs/core/factories/app' import { MigrationSource } from '../../src/migrator/migration_source.js' import { setup, getDb, resetTables } from '../../test-helpers/index.js' -import { AppFactory } from '@adonisjs/core/factories/app' -import { join } from 'node:path' test.group('MigrationSource', (group) => { group.each.setup(async () => { @@ -135,9 +135,9 @@ test.group('MigrationSource', (group) => { await fs.create('database/migrations/baz.ts', 'export default class Baz {}') const directories = await migrationSource.getMigrations() - console.log(await directories[0].getSource()) - // assert.equal((await directories[0].getSource()).name, 'Bar') - // assert.equal(await directories[1].getSource().name, 'Baz') - // assert.equal(await directories[2].getSource().name, 'Foo') + + assert.equal(((await directories[0].getSource()) as any).name, 'Bar') + assert.equal(((await directories[1].getSource()) as any).name, 'Baz') + assert.equal(((await directories[2].getSource()) as any).name, 'Foo') }) }) diff --git a/test/migrations/migrator.spec.ts b/test/migrations/migrator.spec.ts index 43d91262..2d2718a7 100644 --- a/test/migrations/migrator.spec.ts +++ b/test/migrations/migrator.spec.ts @@ -7,42 +7,39 @@ * file that was distributed with this source code. */ -/// - +import { sep } from 'node:path' import { test } from '@japa/runner' -import { join, sep } from 'path' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' +import { AppFactory } from '@adonisjs/core/factories/app' import { setup, - cleanup, getDb, resetTables, getMigrator, - setupApplication, - fs, -} from '../../test-helpers' - -let db: ReturnType -let app: ApplicationContract + cleanup as cleanupTables, +} from '../../test-helpers/index.js' test.group('Migrator', (group) => { group.each.setup(async () => { - app = await setupApplication() - db = getDb(app) await setup() }) group.each.teardown(async () => { await resetTables() - await db.manager.closeAll() - await cleanup() - await cleanup(['adonis_schema', 'adonis_schema_versions', 'schema_users', 'schema_accounts']) - await fs.cleanup() + await cleanupTables() + await cleanupTables([ + 'adonis_schema', + 'adonis_schema_versions', + 'schema_users', + 'schema_accounts', + ]) }) - test('create the schema table when there are no migrations', async ({ assert }) => { - await fs.fsExtra.ensureDir(join(fs.basePath, 'database/migrations')) + test('create the schema table when there are no migrations', async ({ fs, assert, cleanup }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) const migrator = getMigrator(db, app, { direction: 'up', @@ -56,12 +53,17 @@ test.group('Migrator', (group) => { assert.equal(migrator.status, 'skipped') }) - test('migrate database using schema files', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', + test('migrate database using schema files', async ({ fs, assert, cleanup }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + + await fs.create( + 'database/migrations/users_v1.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -89,27 +91,32 @@ test.group('Migrator', (group) => { }) assert.lengthOf(migrated, 1) - assert.equal(migrated[0].name, 'database/migrations/users') + assert.equal(migrated[0].name, 'database/migrations/users_v1') assert.equal(migrated[0].batch, 1) assert.isTrue(hasUsersTable) assert.deepEqual(migratedFiles, [ { status: 'completed', - file: 'database/migrations/users', + file: 'database/migrations/users_v1', queries: [], }, ]) assert.equal(migrator.status, 'completed') }) - test('do not migrate when schema up action fails', async ({ assert }) => { + test('do not migrate when schema up action fails', async ({ fs, assert, cleanup }) => { assert.plan(8) - await fs.add( - 'database/migrations/users.ts', + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + + await fs.create( + 'database/migrations/users_v2.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -120,11 +127,11 @@ test.group('Migrator', (group) => { ` ) - await fs.add( - 'database/migrations/accounts.ts', + await fs.create( + 'database/migrations/accounts_v2.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class Accounts extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { table.increments() @@ -153,19 +160,19 @@ test.group('Migrator', (group) => { }) assert.lengthOf(migrated, 1) - assert.equal(migrated[0].name, 'database/migrations/accounts') + assert.equal(migrated[0].name, 'database/migrations/accounts_v2') assert.equal(migrated[0].batch, 1) assert.isFalse(hasUsersTable, 'Has users table') assert.isTrue(hasAccountsTable, 'Has accounts table') assert.deepEqual(migratedFiles, [ { status: 'completed', - file: 'database/migrations/accounts', + file: 'database/migrations/accounts_v2', queries: [], }, { status: 'error', - file: 'database/migrations/users', + file: 'database/migrations/users_v2', queries: [], }, ]) @@ -174,12 +181,17 @@ test.group('Migrator', (group) => { assert.equal(migrator.error!.message, 'table.badMethod is not a function') }) - test('do not migrate when dryRun is true', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', + test('do not migrate when dryRun is true', async ({ fs, assert, cleanup }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + + await fs.create( + 'database/migrations/users_v3.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -189,11 +201,11 @@ test.group('Migrator', (group) => { ` ) - await fs.add( - 'database/migrations/accounts.ts', + await fs.create( + 'database/migrations/accounts_v3.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class Accounts extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { table.increments() @@ -229,7 +241,7 @@ test.group('Migrator', (group) => { assert.deepEqual(migratedFiles, [ { status: 'completed', - file: 'database/migrations/accounts', + file: 'database/migrations/accounts_v3', queries: [ db .connection() @@ -241,7 +253,7 @@ test.group('Migrator', (group) => { }, { status: 'completed', - file: 'database/migrations/users', + file: 'database/migrations/users_v3', queries: [ db .connection() @@ -256,12 +268,17 @@ test.group('Migrator', (group) => { assert.equal(migrator.status, 'completed') }) - test('catch and report errors in dryRun', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', + test('catch and report errors in dryRun', async ({ fs, assert, cleanup }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + + await fs.create( + 'database/migrations/users_v4.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -271,11 +288,11 @@ test.group('Migrator', (group) => { ` ) - await fs.add( - 'database/migrations/accounts.ts', + await fs.create( + 'database/migrations/accounts_v4.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class Accounts extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { table.increments() @@ -312,12 +329,12 @@ test.group('Migrator', (group) => { assert.deepEqual(migratedFiles, [ { status: 'error', - file: 'database/migrations/accounts', + file: 'database/migrations/accounts_v4', queries: [], }, { status: 'pending', - file: 'database/migrations/users', + file: 'database/migrations/users_v4', queries: [], }, ]) @@ -325,12 +342,17 @@ test.group('Migrator', (group) => { assert.equal(migrator.status, 'error') }) - test('do not migrate a schema file twice', async ({ assert }) => { - await fs.add( - 'database/migrations/accounts.ts', + test('do not migrate a schema file twice', async ({ fs, assert, cleanup }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + + await fs.create( + 'database/migrations/accounts_v5.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class Accounts extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { table.increments() @@ -343,11 +365,11 @@ test.group('Migrator', (group) => { const migrator = getMigrator(db, app, { direction: 'up', connectionName: 'primary' }) await migrator.run() - await fs.add( - 'database/migrations/users.ts', + await fs.create( + 'database/migrations/users_v5.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -370,22 +392,27 @@ test.group('Migrator', (group) => { const hasAccountsTable = await db.connection().schema.hasTable('schema_accounts') assert.lengthOf(migrated, 2) - assert.equal(migrated[0].name, 'database/migrations/accounts') + assert.equal(migrated[0].name, 'database/migrations/accounts_v5') assert.equal(migrated[0].batch, 1) - assert.equal(migrated[1].name, 'database/migrations/users') + assert.equal(migrated[1].name, 'database/migrations/users_v5') assert.equal(migrated[1].batch, 2) assert.isTrue(hasAccountsTable, 'Has accounts table') assert.isTrue(hasUsersTable, 'Has users table') }) - test('rollback database using schema files to a given batch', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', + test('rollback database using schema files to a given batch', async ({ fs, assert, cleanup }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + + await fs.create( + 'database/migrations/users_v6.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -402,11 +429,11 @@ test.group('Migrator', (group) => { const migrator = getMigrator(db, app, { direction: 'up', connectionName: 'primary' }) await migrator.run() - await fs.add( - 'database/migrations/accounts.ts', + await fs.create( + 'database/migrations/accounts_v6.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { table.increments() @@ -447,18 +474,23 @@ test.group('Migrator', (group) => { assert.deepEqual(migratedFiles, [ { status: 'completed', - file: 'database/migrations/accounts', + file: 'database/migrations/accounts_v6', queries: [], }, ]) }) - test('rollback database to the latest batch', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', + test('rollback database to the latest batch', async ({ fs, assert, cleanup }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + + await fs.create( + 'database/migrations/users_v7.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -475,11 +507,11 @@ test.group('Migrator', (group) => { const migrator = getMigrator(db, app, { direction: 'up', connectionName: 'primary' }) await migrator.run() - await fs.add( - 'database/migrations/accounts.ts', + await fs.create( + 'database/migrations/accounts_v7.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { table.increments() @@ -516,18 +548,23 @@ test.group('Migrator', (group) => { assert.deepEqual(migratedFiles, [ { status: 'completed', - file: 'database/migrations/accounts', + file: 'database/migrations/accounts_v7', queries: [], }, ]) }) - test('rollback all down to batch 0', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', + test('rollback all down to batch 0', async ({ fs, assert, cleanup }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + + await fs.create( + 'database/migrations/users_v8.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -544,11 +581,11 @@ test.group('Migrator', (group) => { const migrator = getMigrator(db, app, { direction: 'up', connectionName: 'primary' }) await migrator.run() - await fs.add( - 'database/migrations/accounts.ts', + await fs.create( + 'database/migrations/accounts_v8.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { table.increments() @@ -591,23 +628,28 @@ test.group('Migrator', (group) => { assert.deepEqual(migratedFiles, [ { status: 'completed', - file: 'database/migrations/accounts', + file: 'database/migrations/accounts_v8', queries: [], }, { status: 'completed', - file: 'database/migrations/users', + file: 'database/migrations/users_v8', queries: [], }, ]) }) - test('rollback multiple times must be a noop', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', + test('rollback multiple times must be a noop', async ({ fs, assert, cleanup }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + + await fs.create( + 'database/migrations/users_v9.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -624,11 +666,11 @@ test.group('Migrator', (group) => { const migrator = getMigrator(db, app, { direction: 'up', connectionName: 'primary' }) await migrator.run() - await fs.add( - 'database/migrations/accounts.ts', + await fs.create( + 'database/migrations/accounts_v9.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { table.increments() @@ -688,24 +730,29 @@ test.group('Migrator', (group) => { assert.deepEqual(migrator2Files, [ { status: 'completed', - file: 'database/migrations/accounts', + file: 'database/migrations/accounts_v9', queries: [], }, { status: 'completed', - file: 'database/migrations/users', + file: 'database/migrations/users_v9', queries: [], }, ]) assert.deepEqual(migrator3Files, []) }) - test('do not rollback in dryRun', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', + test('do not rollback in dryRun', async ({ fs, assert, cleanup }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + + await fs.create( + 'database/migrations/users_v10.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -722,11 +769,11 @@ test.group('Migrator', (group) => { const migrator = getMigrator(db, app, { direction: 'up', connectionName: 'primary' }) await migrator.run() - await fs.add( - 'database/migrations/accounts.ts', + await fs.create( + 'database/migrations/accounts_v10.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { table.increments() @@ -770,25 +817,30 @@ test.group('Migrator', (group) => { assert.deepEqual(migrator2Files, [ { status: 'completed', - file: 'database/migrations/accounts', + file: 'database/migrations/accounts_v10', queries: [db.connection().schema.dropTable('schema_accounts').toQuery()], }, { status: 'completed', - file: 'database/migrations/users', + file: 'database/migrations/users_v10', queries: [db.connection().schema.dropTable('schema_users').toQuery()], }, ]) }) - test('do not rollback when a schema file goes missing', async ({ assert }) => { + test('do not rollback when a schema file goes missing', async ({ fs, assert, cleanup }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + assert.plan(4) - await fs.add( - 'database/migrations/users.ts', + await fs.create( + 'database/migrations/users_v11.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -802,11 +854,11 @@ test.group('Migrator', (group) => { ` ) - await fs.add( - 'database/migrations/accounts.ts', + await fs.create( + 'database/migrations/accounts_v11.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { table.increments() @@ -823,7 +875,7 @@ test.group('Migrator', (group) => { const migrator = getMigrator(db, app, { direction: 'up', connectionName: 'primary' }) await migrator.run() - await fs.remove('database/migrations/accounts.ts') + await fs.remove('database/migrations/accounts_v11.ts') const migrator1 = getMigrator(db, app, { batch: 0, @@ -842,16 +894,21 @@ test.group('Migrator', (group) => { assert.isTrue(hasAccountsTable) assert.equal( migrator1.error!.message, - 'E_MISSING_SCHEMA_FILES: Cannot perform rollback. Schema file {database/migrations/accounts} is missing' + 'Cannot perform rollback. Schema file {database/migrations/accounts_v11} is missing' ) }) - test('get list of migrated files', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', + test('get list of migrated files', async ({ fs, assert, cleanup }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + + await fs.create( + 'database/migrations/users_v12.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -865,11 +922,11 @@ test.group('Migrator', (group) => { ` ) - await fs.add( - 'database/migrations/accounts.ts', + await fs.create( + 'database/migrations/accounts_v12.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { table.increments() @@ -888,19 +945,24 @@ test.group('Migrator', (group) => { const files = await migrator.getList() assert.lengthOf(files, 2) - assert.equal(files[0].name, 'database/migrations/accounts') + assert.equal(files[0].name, 'database/migrations/accounts_v12') assert.equal(files[0].batch, 1) - assert.equal(files[1].name, 'database/migrations/users') + assert.equal(files[1].name, 'database/migrations/users_v12') assert.equal(files[1].batch, 1) }) - test('skip upcoming migrations after failure', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', + test('skip upcoming migrations after failure', async ({ fs, assert, cleanup }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + + await fs.create( + 'database/migrations/users_v13.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -910,11 +972,11 @@ test.group('Migrator', (group) => { ` ) - await fs.add( - 'database/migrations/accounts.ts', + await fs.create( + 'database/migrations/accounts_v13.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class Accounts extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { table.increments() @@ -953,12 +1015,12 @@ test.group('Migrator', (group) => { assert.deepEqual(migratedFiles, [ { status: 'error', - file: 'database/migrations/accounts', + file: 'database/migrations/accounts_v13', queries: [], }, { status: 'pending', - file: 'database/migrations/users', + file: 'database/migrations/users_v13', queries: [], }, ]) @@ -966,14 +1028,19 @@ test.group('Migrator', (group) => { assert.equal(migrator.status, 'error') }) - test('use a natural sort to order files when configured', async ({ assert }) => { + test('use a natural sort to order files when configured', async ({ fs, assert, cleanup }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + const originalConfig = Object.assign({}, db.getRawConnection('primary')!.config) db.getRawConnection('primary')!.config.migrations = { naturalSort: true, } - await fs.add( + await fs.create( 'database/migrations/12_users.ts', ` import { Schema } from '../../../../../src/Schema' @@ -990,7 +1057,7 @@ test.group('Migrator', (group) => { ` ) - await fs.add( + await fs.create( 'database/migrations/1_accounts.ts', ` import { Schema } from '../../../../../src/Schema' @@ -1018,14 +1085,23 @@ test.group('Migrator', (group) => { assert.equal(files[1].name, `database${sep}migrations${sep}12_users`) }) - test('use a natural sort to order nested files when configured', async ({ assert }) => { + test('use a natural sort to order nested files when configured', async ({ + fs, + assert, + cleanup, + }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + const originalConfig = Object.assign({}, db.getRawConnection('primary')!.config) db.getRawConnection('primary')!.config.migrations = { naturalSort: true, } - await fs.add( + await fs.create( 'database/migrations/1/12_users.ts', ` import { Schema } from '../../../../../src/Schema' @@ -1042,7 +1118,7 @@ test.group('Migrator', (group) => { ` ) - await fs.add( + await fs.create( 'database/migrations/12/1_accounts.ts', ` import { Schema } from '../../../../../src/Schema' @@ -1070,19 +1146,27 @@ test.group('Migrator', (group) => { assert.equal(files[1].name, `database${sep}migrations${sep}12${sep}1_accounts`) }) - test('raise exception when rollbacks in production are disabled', async ({ assert }) => { - app.nodeEnvironment = 'production' + test('raise exception when rollbacks in production are disabled', async ({ + fs, + assert, + cleanup, + }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + const originalConfig = Object.assign({}, db.getRawConnection('primary')!.config) db.getRawConnection('primary')!.config.migrations = { disableRollbacksInProduction: true, } - await fs.add( - 'database/migrations/users.ts', + await fs.create( + 'database/migrations/users_v14.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -1097,13 +1181,14 @@ test.group('Migrator', (group) => { ) const migrator = getMigrator(db, app, { direction: 'up', connectionName: 'primary' }) + migrator.isInProduction = true await migrator.run() - await fs.add( - 'database/migrations/accounts.ts', + await fs.create( + 'database/migrations/accounts_v14.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { table.increments() @@ -1118,9 +1203,11 @@ test.group('Migrator', (group) => { ) const migrator1 = getMigrator(db, app, { direction: 'up', connectionName: 'primary' }) + migrator1.isInProduction = true await migrator1.run() const migrator2 = getMigrator(db, app, { direction: 'down', connectionName: 'primary' }) + migrator2.isInProduction = true await migrator2.run() assert.equal( @@ -1140,12 +1227,17 @@ test.group('Migrator', (group) => { delete process.env.NODE_ENV }) - test('upgrade old migration file name to new', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', + test('upgrade old migration file name to new', async ({ fs, assert, cleanup }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + + await fs.create( + 'database/migrations/users_v15.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -1170,7 +1262,7 @@ test.group('Migrator', (group) => { } await db.connection().table('adonis_schema').insert({ - name: 'database\\migrations\\users', + name: 'database\\migrations\\users_v15', batch: 1, }) @@ -1191,19 +1283,24 @@ test.group('Migrator', (group) => { assert.lengthOf(migrated, 1) assert.deepEqual(latestVersion, [{ version: 2 }]) - assert.equal(migrated[0].name, 'database/migrations/users') + assert.equal(migrated[0].name, 'database/migrations/users_v15') assert.equal(migrated[0].batch, 1) assert.isFalse(hasUsersTable) assert.deepEqual(migratedFiles, []) assert.equal(migrator.status, 'skipped') }) - test('upgrade file names also in dryRun', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', + test('upgrade file names also in dryRun', async ({ fs, assert, cleanup }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + + await fs.create( + 'database/migrations/users_v16.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -1229,7 +1326,7 @@ test.group('Migrator', (group) => { } await db.connection().table('adonis_schema').insert({ - name: 'database\\migrations\\users', + name: 'database\\migrations\\users_v16', batch: 1, }) @@ -1250,7 +1347,7 @@ test.group('Migrator', (group) => { assert.lengthOf(migrated, 1) assert.deepEqual(latestVersion, [{ version: 2 }]) - assert.equal(migrated[0].name, 'database/migrations/users') + assert.equal(migrated[0].name, 'database/migrations/users_v16') assert.equal(migrated[0].batch, 1) assert.isFalse(hasUsersTable) assert.deepEqual(migratedFiles, []) diff --git a/test/migrations/schema.spec.ts b/test/migrations/schema.spec.ts index 3bd7d189..e4218ee7 100644 --- a/test/migrations/schema.spec.ts +++ b/test/migrations/schema.spec.ts @@ -8,28 +8,36 @@ */ import { test } from '@japa/runner' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' -import { setup, cleanup, getDb, getBaseSchema, setupApplication, fs } from '../../test-helpers' - -let db: ReturnType -let app: ApplicationContract +import { + setup, + getDb, + getBaseSchema, + createEmitter, + cleanup as cleanupTables, +} from '../../test-helpers/index.js' +import { AppFactory } from '@adonisjs/core/factories/app' test.group('Schema', (group) => { group.each.setup(async () => { - app = await setupApplication() - db = getDb(app) await setup() }) group.each.teardown(async () => { - await db.manager.closeAll() - await cleanup() - await fs.cleanup() + await cleanupTables() }) - test('get schema queries defined inside the up method in dry run', async ({ assert }) => { + test('get schema queries defined inside the up method in dry run', async ({ + fs, + cleanup, + assert, + }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + class UsersSchema extends getBaseSchema() { - public up() { + async up() { this.schema.createTable('users', (table) => { table.increments('id') table.string('username') @@ -51,9 +59,18 @@ test.group('Schema', (group) => { assert.deepEqual(queries, [knexSchema]) }) - test('get schema queries defined inside the down method in dry run', async ({ assert }) => { + test('get schema queries defined inside the down method in dry run', async ({ + fs, + cleanup, + assert, + }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + class UsersSchema extends getBaseSchema() { - public down() { + async down() { this.schema.dropTable('users') } } @@ -65,9 +82,14 @@ test.group('Schema', (group) => { assert.deepEqual(queries, [knexSchema]) }) - test('get knex raw query builder using now method', async ({ assert }) => { + test('get knex raw query builder using now method', async ({ fs, cleanup, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + class UsersSchema extends getBaseSchema() { - public up() { + async up() { this.schema.createTable('users', (table) => { table.increments('id') table.string('username') @@ -79,11 +101,15 @@ test.group('Schema', (group) => { assert.equal(schema.now().toQuery(), 'CURRENT_TIMESTAMP') }) - test('do not execute defer calls in dry run', async ({ assert }) => { + test('do not execute defer calls in dry run', async ({ fs, cleanup, assert }) => { assert.plan(1) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) class UsersSchema extends getBaseSchema() { - public up() { + async up() { assert.isTrue(true) this.defer(() => { throw new Error('Not expected to be invoked') @@ -95,9 +121,14 @@ test.group('Schema', (group) => { await schema.execUp() }) - test('execute up method queries on a given connection', async ({ assert }) => { + test('execute up method queries on a given connection', async ({ fs, cleanup, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + class UsersSchema extends getBaseSchema() { - public up() { + async up() { this.schema.createTable('schema_users', (table) => { table.increments('id') table.string('username') @@ -130,9 +161,18 @@ test.group('Schema', (group) => { assert.isTrue(hasAccounts) }) - test('execute up method deferred actions in correct sequence', async ({ assert }) => { + test('execute up method deferred actions in correct sequence', async ({ + fs, + cleanup, + assert, + }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + class UsersSchema extends getBaseSchema() { - public up() { + async up() { this.schema.createTable('schema_users', (table) => { table.increments('id') table.string('username') @@ -166,9 +206,14 @@ test.group('Schema', (group) => { await db.connection().schema.dropTable('schema_users') }) - test('execute down method queries on a given connection', async ({ assert }) => { + test('execute down method queries on a given connection', async ({ assert, fs, cleanup }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + class UsersSchema extends getBaseSchema() { - public up() { + async up() { this.schema.createTable('schema_users', (table) => { table.increments('id') table.string('username') @@ -180,7 +225,7 @@ test.group('Schema', (group) => { }) } - public down() { + async down() { if (this.db.dialect.name !== 'sqlite3') { this.schema.table('schema_accounts', (table) => { table.dropForeign(['user_id']) @@ -212,9 +257,14 @@ test.group('Schema', (group) => { assert.isFalse(hasAccounts) }) - test('use now helper to define default timestamp', async ({ assert }) => { + test('use now helper to define default timestamp', async ({ assert, fs, cleanup }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + class UsersSchema extends getBaseSchema() { - public up() { + async up() { this.schema.createTable('users', (table) => { table.increments('id') table.timestamp('created_at').defaultTo(this.now()) @@ -236,11 +286,21 @@ test.group('Schema', (group) => { assert.deepEqual(queries, [knexSchema]) }) - test('emit db:query event when schema instructions are executed', async ({ assert }) => { + test('emit db:query event when schema instructions are executed', async ({ + assert, + fs, + cleanup, + }) => { assert.plan(10) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + + const emitter = createEmitter() + const db = getDb(emitter) + cleanup(() => db.manager.closeAll()) class UsersSchema extends getBaseSchema() { - public up() { + async up() { this.schema.createTable('schema_users', (table) => { table.increments('id') table.string('username') @@ -257,7 +317,7 @@ test.group('Schema', (group) => { trx.debug = true const schema = new UsersSchema(trx, 'users.ts', false) - app.container.use('Adonis/Core/Event').on('db:query', (query) => { + emitter.on('db:query', (query) => { assert.property(query, 'sql') assert.isTrue(query.inTransaction) assert.equal(query.connection, 'primary') @@ -276,9 +336,15 @@ test.group('Schema', (group) => { await db.connection().schema.dropTable('schema_users') }) - test('do not emit db:query debugging is turned off', async () => { + test('do not emit db:query debugging is turned off', async ({ fs, cleanup }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const emitter = createEmitter() + const db = getDb(emitter) + cleanup(() => db.manager.closeAll()) + class UsersSchema extends getBaseSchema() { - public up() { + async up() { this.schema.createTable('schema_users', (table) => { table.increments('id') table.string('username') @@ -295,7 +361,7 @@ test.group('Schema', (group) => { trx.debug = false const schema = new UsersSchema(trx, 'users.ts', false) - app.container.use('Adonis/Core/Event').on('db:query', () => { + emitter.on('db:query', () => { throw new Error('Never expected to reach here') }) @@ -310,13 +376,18 @@ test.group('Schema', (group) => { await db.connection().schema.dropTable('schema_users') }) - test('emit db:query when enabled on the schema', async ({ assert }) => { + test('emit db:query when enabled on the schema', async ({ assert, fs, cleanup }) => { assert.plan(10) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const emitter = createEmitter() + const db = getDb(emitter) + cleanup(() => db.manager.closeAll()) class UsersSchema extends getBaseSchema() { - public debug = true + debug = true - public up() { + async up() { this.schema.createTable('schema_users', (table) => { table.increments('id') table.string('username') @@ -332,7 +403,7 @@ test.group('Schema', (group) => { const trx = await db.transaction() const schema = new UsersSchema(trx, 'users.ts', false) - app.container.use('Adonis/Core/Event').on('db:query', (query) => { + emitter.on('db:query', (query) => { assert.property(query, 'sql') assert.isTrue(query.inTransaction) assert.equal(query.connection, 'primary') @@ -351,9 +422,14 @@ test.group('Schema', (group) => { await db.connection().schema.dropTable('schema_users') }) - test('define index predicate as knex query', async ({ assert }) => { + test('define index predicate as knex query', async ({ assert, fs, cleanup }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + class UsersSchema extends getBaseSchema() { - public up() { + async up() { this.schema.createTable('users', (table) => { table.increments('id') table.index(['name', 'last_name'], 'idx_name_last_name', { From 887f5f17da1cce45142ef55d483cbfc8fb21e1b9 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Sat, 16 Sep 2023 16:54:47 +0530 Subject: [PATCH 04/70] refactor: migrate seeders module --- adonis-typings/seeder.ts | 10 +- src/{BaseSeeder => base_seeder}/index.ts | 10 +- src/{SeedsRunner => seeders_runner}/index.ts | 40 ++++---- .../seeders_source.ts} | 15 ++- .../seeders_runner.spec.ts} | 92 +++++++------------ .../seeders_source.spec.ts} | 66 ++++++------- 6 files changed, 109 insertions(+), 124 deletions(-) rename src/{BaseSeeder => base_seeder}/index.ts (59%) rename src/{SeedsRunner => seeders_runner}/index.ts (64%) rename src/{SeedsRunner/SeedersSource.ts => seeders_runner/seeders_source.ts} (76%) rename test/{seeds/seeds-runner.spec.ts => seeders/seeders_runner.spec.ts} (57%) rename test/{seeds/seeders-source.spec.ts => seeders/seeders_source.spec.ts} (60%) diff --git a/adonis-typings/seeder.ts b/adonis-typings/seeder.ts index ae5eb089..065cc348 100644 --- a/adonis-typings/seeder.ts +++ b/adonis-typings/seeder.ts @@ -7,7 +7,7 @@ * file that was distributed with this source code. */ -import { FileNode } from './database.js' +import { FileNode, QueryClientContract } from './database.js' /** * Shape of file node returned by the run method @@ -17,3 +17,11 @@ export type SeederFileNode = { error?: any file: FileNode } + +export type SeederConstructorContract = { + environment: string[] + new (client: QueryClientContract): { + client: QueryClientContract + run(): Promise + } +} diff --git a/src/BaseSeeder/index.ts b/src/base_seeder/index.ts similarity index 59% rename from src/BaseSeeder/index.ts rename to src/base_seeder/index.ts index 28371252..52b1cab9 100644 --- a/src/BaseSeeder/index.ts +++ b/src/base_seeder/index.ts @@ -7,15 +7,11 @@ * file that was distributed with this source code. */ -import { QueryClientContract } from '@ioc:Adonis/Lucid/Database' +import { QueryClientContract } from '../../adonis-typings/database.js' export class BaseSeeder { - /** - * @deprecated - */ - public static developmentOnly: boolean - public static environment: string[] + static environment: string[] constructor(public client: QueryClientContract) {} - public async run() {} + async run() {} } diff --git a/src/SeedsRunner/index.ts b/src/seeders_runner/index.ts similarity index 64% rename from src/SeedsRunner/index.ts rename to src/seeders_runner/index.ts index db2d640a..95a429a6 100644 --- a/src/SeedsRunner/index.ts +++ b/src/seeders_runner/index.ts @@ -7,25 +7,32 @@ * file that was distributed with this source code. */ -import { ApplicationContract } from '@ioc:Adonis/Core/Application' -import { FileNode, DatabaseContract } from '@ioc:Adonis/Lucid/Database' -import { SeederFileNode, SeederConstructorContract } from '@ioc:Adonis/Lucid/Seeder' +import { Application } from '@adonisjs/core/app' +import { FileNode, QueryClientContract, SharedConfigNode } from '../../adonis-typings/database.js' +import { SeederConstructorContract, SeederFileNode } from '../../adonis-typings/seeder.js' -import { SeedersSource } from './SeedersSource' +import { SeedersSource } from './seeders_source.js' +import { Database } from '../database/index.js' /** * Seeds Runner exposes the API to traverse seeders and execute them * in bulk */ export class SeedsRunner { - private client = this.db.connection(this.connectionName || this.db.primaryConnectionName) - private config = this.db.getRawConnection(this.client.connectionName)!.config + private client: QueryClientContract + private config: SharedConfigNode + + nodeEnvironment: string constructor( - private db: DatabaseContract, - private app: ApplicationContract, + private db: Database, + private app: Application, private connectionName?: string - ) {} + ) { + this.client = this.db.connection(this.connectionName || this.db.primaryConnectionName) + this.config = this.db.getRawConnection(this.client.connectionName)!.config + this.nodeEnvironment = this.app.nodeEnvironment + } /** * Returns the seeder source by ensuring value is a class constructor @@ -42,14 +49,14 @@ export class SeedsRunner { /** * Returns an array of seeders */ - public async getList() { + async getList() { return new SeedersSource(this.config, this.app).getSeeders() } /** * Executes the seeder */ - public async run(file: FileNode): Promise { + async run(file: FileNode): Promise { const Source = await this.getSeederSource(file) const seeder: SeederFileNode = { @@ -57,17 +64,10 @@ export class SeedsRunner { file: file, } - if ('developmentOnly' in Source) { - this.app.logger.warn(`Seeder "${file.name}" is using the deprecated flag "developmentOnly".`) - } - /** * Ignore when when the node environement is not the same as the seeder configuration. */ - if ( - (Source.developmentOnly && !this.app.inDev) || - (Source.environment && !Source.environment.includes(this.app.nodeEnvironment)) - ) { + if (Source.environment && !Source.environment.includes(this.nodeEnvironment)) { seeder.status = 'ignored' return seeder } @@ -91,7 +91,7 @@ export class SeedsRunner { /** * Close database connections */ - public async close() { + async close() { await this.db.manager.closeAll(true) } } diff --git a/src/SeedsRunner/SeedersSource.ts b/src/seeders_runner/seeders_source.ts similarity index 76% rename from src/SeedsRunner/SeedersSource.ts rename to src/seeders_runner/seeders_source.ts index 46aadbea..be2c0c05 100644 --- a/src/SeedsRunner/SeedersSource.ts +++ b/src/seeders_runner/seeders_source.ts @@ -7,19 +7,18 @@ * file that was distributed with this source code. */ -/// +import { Application } from '@adonisjs/core/app' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' -import { ConnectionConfig, FileNode } from '@ioc:Adonis/Lucid/Database' -import { sourceFiles } from '../utils' +import { FileNode, SharedConfigNode } from '../../adonis-typings/database.js' +import { sourceFiles } from '../utils/index.js' /** * Seeders source exposes the API to read the seeders from disk for a given connection. */ export class SeedersSource { constructor( - private config: ConnectionConfig, - private app: ApplicationContract + private config: SharedConfigNode, + private app: Application ) {} /** @@ -37,14 +36,14 @@ export class SeedersSource { */ private getSeedersPaths(): string[] { const directories = (this.config.seeders || {}).paths - const defaultDirectory = this.app.directoriesMap.get('seeds') || 'database/seeders' + const defaultDirectory = this.app.relativePath(this.app.seedersPath()) || 'database/seeders' return directories && directories.length ? directories : [`./${defaultDirectory}`] } /** * Returns an array of files for the defined seed directories */ - public async getSeeders() { + async getSeeders() { const seedersPaths = this.getSeedersPaths() const directories = await Promise.all( seedersPaths.map((directoryPath) => { diff --git a/test/seeds/seeds-runner.spec.ts b/test/seeders/seeders_runner.spec.ts similarity index 57% rename from test/seeds/seeds-runner.spec.ts rename to test/seeders/seeders_runner.spec.ts index 31c3d105..13f969d4 100644 --- a/test/seeds/seeds-runner.spec.ts +++ b/test/seeders/seeders_runner.spec.ts @@ -8,9 +8,10 @@ */ import { test } from '@japa/runner' +import { AppFactory } from '@adonisjs/core/factories/app' -import { SeedsRunner } from '../../src/SeedsRunner' -import { getDb, setup, cleanup, setupApplication, fs } from '../../test-helpers' +import { SeedsRunner } from '../../src/seeders_runner/index.js' +import { getDb, setup, cleanup as cleanupTables } from '../../test-helpers/index.js' test.group('Seeds Runner', (group) => { group.each.setup(async () => { @@ -18,19 +19,21 @@ test.group('Seeds Runner', (group) => { }) group.each.teardown(async () => { - await cleanup() - await fs.cleanup() + await cleanupTables() }) - test('run a seeder file', async ({ assert }) => { - const app = await setupApplication() - const db = getDb(app) + test('run a seeder file', async ({ fs, assert, cleanup }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + cleanup(() => db.manager.closeAll()) + const runner = new SeedsRunner(db, app) - await fs.add( + await fs.create( 'database/seeders/User.ts', `export default class FooSeeder { - public static invoked = false + static invoked = false run () { (this.constructor as any).invoked = true @@ -40,19 +43,20 @@ test.group('Seeds Runner', (group) => { const files = await runner.getList() const report = await runner.run(files[0]) - assert.equal((report.file.getSource() as any)['invoked'], true) - assert.equal(report.status, 'completed') + const fileSource = await report.file.getSource() - await db.manager.closeAll() + assert.equal((fileSource as any)['invoked'], true) + assert.equal(report.status, 'completed') }) - test('catch and return seeder errors', async ({ assert }) => { - const app = await setupApplication() - const db = getDb(app) + test('catch and return seeder errors', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() const runner = new SeedsRunner(db, app) - await fs.add( - 'database/seeders/User.ts', + await fs.create( + 'database/seeders/User_v1.ts', `export default class FooSeeder { run () { throw new Error('Failed') @@ -67,47 +71,19 @@ test.group('Seeds Runner', (group) => { await db.manager.closeAll() }) - - test('mark file as ignored when "developmentOnly = true" and not running in development mode', async ({ - assert, - }) => { - process.env.NODE_ENV = 'production' - - const app = await setupApplication() - const db = getDb(app) - const runner = new SeedsRunner(db, app) - - await fs.add( - 'database/seeders/User.ts', - `export default class FooSeeder { - public static invoked = false - public static developmentOnly = true - - run () { - (this.constructor as any).invoked = true - } - }` - ) - - const files = await runner.getList() - const report = await runner.run(files[0]) - assert.equal(report.status, 'ignored') - - delete process.env.NODE_ENV - await db.manager.closeAll() - }) - test('mark file as ignored when "environment = production" and not running in production mode', async ({ assert, + fs, }) => { - process.env.NODE_ENV = 'development' + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() - const app = await setupApplication() - const db = getDb(app) const runner = new SeedsRunner(db, app) + runner.nodeEnvironment = 'development' - await fs.add( - 'database/seeders/User.ts', + await fs.create( + 'database/seeders/User_v2.ts', `export default class FooSeeder { public static invoked = false public static environment = ['production'] @@ -128,15 +104,17 @@ test.group('Seeds Runner', (group) => { test('mark file as ignored when "environment = development" and not running in development mode', async ({ assert, + fs, }) => { - process.env.NODE_ENV = 'production' + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() - const app = await setupApplication() - const db = getDb(app) const runner = new SeedsRunner(db, app) + runner.nodeEnvironment = 'production' - await fs.add( - 'database/seeders/User.ts', + await fs.create( + 'database/seeders/User_v3.ts', `export default class FooSeeder { public static invoked = false public static environment = ['development'] diff --git a/test/seeds/seeders-source.spec.ts b/test/seeders/seeders_source.spec.ts similarity index 60% rename from test/seeds/seeders-source.spec.ts rename to test/seeders/seeders_source.spec.ts index 5fe58442..f2f66891 100644 --- a/test/seeds/seeders-source.spec.ts +++ b/test/seeders/seeders_source.spec.ts @@ -7,11 +7,12 @@ * file that was distributed with this source code. */ +import { join } from 'node:path' import { test } from '@japa/runner' -import { join } from 'path' +import { AppFactory } from '@adonisjs/core/factories/app' -import { SeedersSource } from '../../src/SeedsRunner/SeedersSource' -import { getDb, setup, setupApplication, fs, cleanup } from '../../test-helpers' +import { SeedersSource } from '../../src/seeders_runner/seeders_source.js' +import { getDb, setup, cleanup } from '../../test-helpers/index.js' test.group('Seeds Source', (group) => { group.each.setup(async () => { @@ -20,22 +21,22 @@ test.group('Seeds Source', (group) => { group.each.teardown(async () => { await cleanup() - await fs.cleanup() }) - test('get list of seed files recursively', async ({ assert }) => { - const app = await setupApplication() - const db = getDb(app) + test('get list of seed files recursively', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() - const seedsSource = new SeedersSource(db.getRawConnection('primary')!.config, app) + const seedersSource = new SeedersSource(db.getRawConnection('primary')!.config, app) - await fs.add('database/seeders/User.ts', '') - await fs.add('database/seeders/Tenant/User.ts', '') - await fs.add('database/seeders/Country/Post.ts', '') + await fs.create('database/seeders/User.ts', '') + await fs.create('database/seeders/Tenant/User.ts', '') + await fs.create('database/seeders/Country/Post.ts', '') await db.manager.closeAll() - const files = await seedsSource.getSeeders() + const files = await seedersSource.getSeeders() assert.deepEqual( files.map((file) => { return { absPath: file.absPath, name: file.name } @@ -57,20 +58,22 @@ test.group('Seeds Source', (group) => { ) }) - test('only pick .ts/.js files', async ({ assert }) => { - const app = await setupApplication() - const db = getDb(app) - const seedsSource = new SeedersSource(db.getRawConnection('primary')!.config, app) + test('only pick .ts/.js files', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() - await fs.add('database/seeders/User.ts', '') - await fs.add('database/seeders/Tenant/User.ts', '') - await fs.add('database/seeders/Country/Post.ts', '') - await fs.add('database/seeders/foo.bar', '') - await fs.add('database/seeders/foo.js', '') + const seedersSource = new SeedersSource(db.getRawConnection('primary')!.config, app) + + await fs.create('database/seeders/User.ts', '') + await fs.create('database/seeders/Tenant/User.ts', '') + await fs.create('database/seeders/Country/Post.ts', '') + await fs.create('database/seeders/foo.bar', '') + await fs.create('database/seeders/foo.js', '') await db.manager.closeAll() - const files = await seedsSource.getSeeders() + const files = await seedersSource.getSeeders() assert.deepEqual( files.map((file) => { return { absPath: file.absPath, name: file.name } @@ -96,9 +99,10 @@ test.group('Seeds Source', (group) => { ) }) - test('sort multiple seeders directories seperately', async ({ assert }) => { - const app = await setupApplication() - const db = getDb(app) + test('sort multiple seeders directories seperately', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() const config = Object.assign({}, db.getRawConnection('primary')!.config, { seeders: { @@ -106,15 +110,15 @@ test.group('Seeds Source', (group) => { }, }) - const seedsSource = new SeedersSource(config, app) - await fs.add('database/secondary/User.ts', '') - await fs.add('database/secondary/Tenant/User.ts', '') + const seedersSource = new SeedersSource(config, app) + await fs.create('database/secondary/User.ts', '') + await fs.create('database/secondary/Tenant/User.ts', '') - await fs.add('database/primary/Account.ts', '') - await fs.add('database/primary/Team.ts', '') + await fs.create('database/primary/Account.ts', '') + await fs.create('database/primary/Team.ts', '') await db.manager.closeAll() - const files = await seedsSource.getSeeders() + const files = await seedersSource.getSeeders() assert.deepEqual( files.map((file) => { From 532b9cb85a290b5dc0a7c7cdd29ee4707cd71a35 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Mon, 18 Sep 2023 14:52:47 +0530 Subject: [PATCH 05/70] feat: migrate orm BaseModel --- adonis-typings/model.ts | 27 +- adonis-typings/relations.ts | 63 +- example/index.ts | 75 +- src/database/index.ts | 4 +- src/{Orm/Adapter => orm/adapter}/index.ts | 32 +- .../BaseModel => orm/base_model}/index.ts | 410 +- .../base_model/proxy_handler.ts} | 4 +- .../Decorators => orm/decorators}/date.ts | 20 +- .../decorators/date_time.ts} | 20 +- .../Decorators => orm/decorators}/index.ts | 48 +- .../ModelKeys => orm/model_keys}/index.ts | 12 +- .../naming_strategies/snake_case.ts | 4 +- src/{Orm/Paginator => orm/paginator}/index.ts | 8 +- src/{Orm/Preloader => orm/preloader}/index.ts | 29 +- .../query_builder}/index.ts | 212 +- .../relations/aggregates_loader/lazy_load.ts} | 16 +- .../relations/base/query_builder.ts} | 36 +- .../relations/base/sub_query_builder.ts} | 44 +- .../relations/belongs_to}/index.ts | 69 +- .../relations/belongs_to/query_builder.ts} | 27 +- .../relations/belongs_to/query_client.ts} | 33 +- .../belongs_to/sub_query_builder.ts} | 11 +- .../relations/has_many}/index.ts | 66 +- .../relations/has_many/query_builder.ts} | 17 +- .../relations/has_many/query_client.ts} | 46 +- .../relations/has_many/sub_query_builder.ts} | 11 +- .../relations/has_many_through}/index.ts | 82 +- .../has_many_through/query_builder.ts} | 25 +- .../has_many_through/query_client.ts} | 24 +- .../has_many_through/sub_query_builder.ts} | 22 +- .../HasOne => orm/relations/has_one}/index.ts | 65 +- .../relations/has_one/query_builder.ts} | 16 +- .../relations/has_one/query_client.ts} | 35 +- .../relations/has_one/sub_query_builder.ts} | 11 +- .../relations/keys_extractor.ts} | 10 +- .../relations/many_to_many}/index.ts | 82 +- .../relations/many_to_many/pivot_helpers.ts} | 33 +- .../relations/many_to_many/query_builder.ts} | 69 +- .../relations/many_to_many/query_client.ts} | 54 +- .../many_to_many/sub_query_builder.ts} | 66 +- src/query_client/index.ts | 9 +- src/transaction_client/index.ts | 11 +- test-helpers/index.ts | 19 +- ...{base-model.spec.ts => base_model.spec.ts} | 3397 ++++++++++++----- 44 files changed, 3379 insertions(+), 1995 deletions(-) rename src/{Orm/Adapter => orm/adapter}/index.ts (77%) rename src/{Orm/BaseModel => orm/base_model}/index.ts (82%) rename src/{Orm/BaseModel/proxyHandler.ts => orm/base_model/proxy_handler.ts} (95%) rename src/{Orm/Decorators => orm/decorators}/date.ts (89%) rename src/{Orm/Decorators/datetime.ts => orm/decorators/date_time.ts} (89%) rename src/{Orm/Decorators => orm/decorators}/index.ts (82%) rename src/{Orm/ModelKeys => orm/model_keys}/index.ts (70%) rename src/{Orm => orm}/naming_strategies/snake_case.ts (95%) rename src/{Orm/Paginator => orm/paginator}/index.ts (68%) rename src/{Orm/Preloader => orm/preloader}/index.ts (85%) rename src/{Orm/QueryBuilder => orm/query_builder}/index.ts (76%) rename src/{Orm/Relations/AggregatesLoader/LazyLoad.ts => orm/relations/aggregates_loader/lazy_load.ts} (84%) rename src/{Orm/Relations/Base/QueryBuilder.ts => orm/relations/base/query_builder.ts} (86%) rename src/{Orm/Relations/Base/SubQueryBuilder.ts => orm/relations/base/sub_query_builder.ts} (78%) rename src/{Orm/Relations/BelongsTo => orm/relations/belongs_to}/index.ts (68%) rename src/{Orm/Relations/BelongsTo/QueryBuilder.ts => orm/relations/belongs_to/query_builder.ts} (85%) rename src/{Orm/Relations/BelongsTo/QueryClient.ts => orm/relations/belongs_to/query_client.ts} (65%) rename src/{Orm/Relations/BelongsTo/SubQueryBuilder.ts => orm/relations/belongs_to/sub_query_builder.ts} (85%) rename src/{Orm/Relations/HasMany => orm/relations/has_many}/index.ts (71%) rename src/{Orm/Relations/HasMany/QueryBuilder.ts => orm/relations/has_many/query_builder.ts} (89%) rename src/{Orm/Relations/HasMany/QueryClient.ts => orm/relations/has_many/query_client.ts} (83%) rename src/{Orm/Relations/HasMany/SubQueryBuilder.ts => orm/relations/has_many/sub_query_builder.ts} (85%) rename src/{Orm/Relations/HasManyThrough => orm/relations/has_many_through}/index.ts (73%) rename src/{Orm/Relations/HasManyThrough/QueryBuilder.ts => orm/relations/has_many_through/query_builder.ts} (90%) rename src/{Orm/Relations/HasManyThrough/QueryClient.ts => orm/relations/has_many_through/query_client.ts} (68%) rename src/{Orm/Relations/HasManyThrough/SubQueryBuilder.ts => orm/relations/has_many_through/sub_query_builder.ts} (84%) rename src/{Orm/Relations/HasOne => orm/relations/has_one}/index.ts (69%) rename src/{Orm/Relations/HasOne/QueryBuilder.ts => orm/relations/has_one/query_builder.ts} (89%) rename src/{Orm/Relations/HasOne/QueryClient.ts => orm/relations/has_one/query_client.ts} (78%) rename src/{Orm/Relations/HasOne/SubQueryBuilder.ts => orm/relations/has_one/sub_query_builder.ts} (85%) rename src/{Orm/Relations/KeysExtractor.ts => orm/relations/keys_extractor.ts} (83%) rename src/{Orm/Relations/ManyToMany => orm/relations/many_to_many}/index.ts (77%) rename src/{Orm/Relations/ManyToMany/PivotHelpers.ts => orm/relations/many_to_many/pivot_helpers.ts} (76%) rename src/{Orm/Relations/ManyToMany/QueryBuilder.ts => orm/relations/many_to_many/query_builder.ts} (85%) rename src/{Orm/Relations/ManyToMany/QueryClient.ts => orm/relations/many_to_many/query_client.ts} (91%) rename src/{Orm/Relations/ManyToMany/SubQueryBuilder.ts => orm/relations/many_to_many/sub_query_builder.ts} (77%) rename test/orm/{base-model.spec.ts => base_model.spec.ts} (63%) diff --git a/adonis-typings/model.ts b/adonis-typings/model.ts index 8a5510b1..2c1726e0 100644 --- a/adonis-typings/model.ts +++ b/adonis-typings/model.ts @@ -37,6 +37,7 @@ import { WithAggregate, WithCount, } from './relations.js' +import { Container } from '@adonisjs/core/container' /** * ------------------------------------------------------ @@ -106,7 +107,7 @@ export type ModelAttributes = Model['$columns'] extends */ export type ExtractScopes = { [Scope in keyof PickProperties>>]: ( - ...args: Model[Scope] extends QueryScopeCallback ? OmitFirst : never + ...args: Model[Scope] extends QueryScopeCallback ? OmitFirst : never ) => ExtractScopes } @@ -237,9 +238,9 @@ export type ComputedOptions = { * Options accepted by the Model.$addRelation method */ export type ModelRelationOptions = - | RelationOptions - | ManyToManyRelationOptions - | ThroughRelationOptions + | RelationOptions> + | ManyToManyRelationOptions> + | ThroughRelationOptions> /** * Signature for column decorator function @@ -638,7 +639,9 @@ export interface LucidRow { loadAggregate: < Self extends this, Name extends ExtractModelRelations, - RelatedBuilder = Self[Name] extends ModelRelations ? Self[Name]['subQuery'] : never, + RelatedBuilder = Self[Name] extends ModelRelations + ? Self[Name]['subQuery'] + : never, >( name: Name, callback: (builder: RelatedBuilder) => void @@ -650,7 +653,9 @@ export interface LucidRow { loadCount: < Self extends this, Name extends ExtractModelRelations, - RelatedBuilder = Self[Name] extends ModelRelations ? Self[Name]['subQuery'] : never, + RelatedBuilder = Self[Name] extends ModelRelations + ? Self[Name]['subQuery'] + : never, >( name: Name, callback?: (builder: RelatedBuilder) => void @@ -703,7 +708,7 @@ export interface LucidRow { */ related>( relation: Name - ): this[Name] extends ModelRelations ? this[Name]['client'] : never + ): this[Name] extends ModelRelations ? this[Name]['client'] : never } /** @@ -726,6 +731,8 @@ export interface LucidModel { */ readonly booted: boolean + $container: Container + /** * A map of defined columns */ @@ -847,7 +854,7 @@ export interface LucidModel { $getRelation>>( this: Model, name: Name - ): InstanceType[Name] extends ModelRelations + ): InstanceType[Name] extends ModelRelations ? InstanceType[Name]['client']['relation'] : RelationshipsContract $getRelation(this: Model, name: string): RelationshipsContract @@ -1153,7 +1160,7 @@ export interface NamingStrategyContract { * The local key for a given model relationship */ relationLocalKey( - relation: ModelRelations['__opaque_type'], + relation: ModelRelations['__opaque_type'], model: LucidModel, relatedModel: LucidModel, relationName: string @@ -1163,7 +1170,7 @@ export interface NamingStrategyContract { * The foreign key for a given model relationship */ relationForeignKey( - relation: ModelRelations['__opaque_type'], + relation: ModelRelations['__opaque_type'], model: LucidModel, relatedModel: LucidModel, relationName: string diff --git a/adonis-typings/relations.ts b/adonis-typings/relations.ts index b3ee5e0a..65540327 100644 --- a/adonis-typings/relations.ts +++ b/adonis-typings/relations.ts @@ -11,7 +11,6 @@ import { RawQuery, OneOrMany, StrictValues, - QueryCallback, ChainableContract, RawBuilderContract, } from './querybuilder.js' @@ -37,14 +36,14 @@ import { * Extracts relationship attributes from the model */ export type ExtractModelRelations = { - [Key in keyof Model]: Model[Key] extends ModelRelations ? Key : never + [Key in keyof Model]: Model[Key] extends ModelRelations ? Key : never }[keyof Model] /** * Returns relationship model instance or array of instances based * upon the relationship type */ -export type GetRelationModelInstance = +export type GetRelationModelInstance> = Relation['__opaque_type'] extends 'hasOne' | 'belongsTo' ? Relation['instance'] : Relation['instance'][] @@ -59,7 +58,11 @@ export type GetRelationModelInstance = * Options accepted when defining a new relationship. Certain * relationships like `manyToMany` have their own options */ -export type RelationOptions = { +export type RelationOptions< + RelatedModel extends LucidModel, + ParentModel extends LucidModel, + Related extends ModelRelations, +> = { localKey?: string foreignKey?: string serializeAs?: string | null @@ -69,7 +72,7 @@ export type RelationOptions = { /** * Options accepted by many to many relationship */ -export type ManyToManyRelationOptions = { +export type ManyToManyRelationOptions> = { pivotTable?: string localKey?: string pivotForeignKey?: string @@ -89,7 +92,11 @@ export type ManyToManyRelationOptions = { /** * Options accepted by through relationships */ -export type ThroughRelationOptions = RelationOptions & { +export type ThroughRelationOptions< + RelatedModel extends LucidModel, + ParentModel extends LucidModel, + Related extends ModelRelations, +> = RelationOptions & { throughLocalKey?: string throughForeignKey?: string throughModel: () => LucidModel @@ -106,7 +113,7 @@ export type ThroughRelationOptions = RelationOpt */ export type HasOneDecorator = ( model: () => RelatedModel, - options?: RelationOptions> + options?: RelationOptions> ) => TypedDecorator> /** @@ -114,7 +121,7 @@ export type HasOneDecorator = ( */ export type HasManyDecorator = ( model: () => RelatedModel, - options?: RelationOptions> + options?: RelationOptions> ) => TypedDecorator> /** @@ -122,7 +129,7 @@ export type HasManyDecorator = ( */ export type BelongsToDecorator = ( model: () => RelatedModel, - options?: RelationOptions> + options?: RelationOptions> ) => TypedDecorator> /** @@ -138,7 +145,10 @@ export type ManyToManyDecorator = ( */ export type HasManyThroughDecorator = ( model: [() => RelatedModel, () => LucidModel], - column?: Omit>, 'throughModel'> + column?: Omit< + ThroughRelationOptions>, + 'throughModel' + > ) => TypedDecorator> /** @@ -243,12 +253,15 @@ export type HasManyThrough< * is to distinguish relationship properties from other model * properties. */ -export type ModelRelations = - | HasOne - | HasMany - | BelongsTo - | ManyToMany - | HasManyThrough +export type ModelRelations< + RelatedModel extends LucidModel, + ParentModel extends LucidModel = LucidModel, +> = + | HasOne + | HasMany + | BelongsTo + | ManyToMany + | HasManyThrough /** * ------------------------------------------------------ @@ -877,7 +890,7 @@ interface WhereInPivot { (K: string[], value: StrictValues[][]): Builder ( k: string, - subquery: ChainableContract | QueryCallback | RawBuilderContract | RawQuery + subquery: ChainableContract | ((builder: Builder) => void) | RawBuilderContract | RawQuery ): Builder (k: string[], subquery: ChainableContract | RawBuilderContract | RawQuery): Builder } @@ -961,7 +974,9 @@ export interface ManyToManySubQueryBuilderContract export interface WithCount { < Name extends ExtractModelRelations, - RelatedBuilder = Model[Name] extends ModelRelations ? Model[Name]['subQuery'] : never, + RelatedBuilder = Model[Name] extends ModelRelations + ? Model[Name]['subQuery'] + : never, >( relation: Name, callback?: (builder: RelatedBuilder) => void @@ -974,7 +989,9 @@ export interface WithCount { export interface WithAggregate { < Name extends ExtractModelRelations, - RelatedBuilder = Model[Name] extends ModelRelations ? Model[Name]['subQuery'] : never, + RelatedBuilder = Model[Name] extends ModelRelations + ? Model[Name]['subQuery'] + : never, >( relation: Name, callback: (builder: RelatedBuilder) => void @@ -998,7 +1015,9 @@ export interface Has { export interface WhereHas { < Name extends ExtractModelRelations, - RelatedBuilder = Model[Name] extends ModelRelations ? Model[Name]['subQuery'] : never, + RelatedBuilder = Model[Name] extends ModelRelations + ? Model[Name]['subQuery'] + : never, >( relation: Name, callback: (builder: RelatedBuilder) => void, @@ -1019,7 +1038,9 @@ export interface WhereHas { export interface Preload { < Name extends ExtractModelRelations, - RelatedBuilder = Model[Name] extends ModelRelations ? Model[Name]['builder'] : never, + RelatedBuilder = Model[Name] extends ModelRelations + ? Model[Name]['builder'] + : never, >( relation: Name, callback?: (builder: RelatedBuilder) => void diff --git a/example/index.ts b/example/index.ts index c8de03f9..5270c4c6 100644 --- a/example/index.ts +++ b/example/index.ts @@ -1,13 +1,10 @@ import { DateTime } from 'luxon' -import { - BaseModel, - HasOne, - hasOne, - scope, - column, - ModelQueryBuilderContract, -} from '@ioc:Adonis/Lucid/Orm' -import Factory from '@ioc:Adonis/Lucid/Factory' +import { BaseModel } from '../src/orm/base_model/index.js' +import { column, hasOne } from '../src/orm/decorators/index.js' +import { HasOne } from '../adonis-typings/relations.js' +import { scope } from '../src/helpers/scope.js' +import { ModelQueryBuilderContract } from '../adonis-typings/model.js' +// import Factory from '@ioc:Adonis/Lucid/Factory' enum ProfileTypes { TWITTER = 'TWITTER', @@ -16,19 +13,19 @@ enum ProfileTypes { type Builder = ModelQueryBuilderContract class Profile extends BaseModel { - public id: string - public userId: string - public user: HasOne + declare id: string + declare userId: string + declare user: HasOne - public type: ProfileTypes + declare type: ProfileTypes @column.dateTime() - public createdAt?: DateTime + declare createdAt?: DateTime } export class User extends BaseModel { - public id: string - public username: string + declare id: string + declare username: string @hasOne(() => Profile, { onQuery: (builder) => { @@ -37,12 +34,12 @@ export class User extends BaseModel { } }, }) - public profile: HasOne + declare profile: HasOne - public static active = scope((builder: Builder) => { + static active = scope((builder: Builder) => { builder.apply((scopes) => scopes.country('India')) }) - public static country = scope((builder, _country: string) => { + static country = scope((builder, _country: string) => { builder.whereIn('', []) }) } @@ -54,36 +51,36 @@ User.create({ id: '1', username: 'virk' }) User.create({ id: '1', username: 'virk' }) User.create({ id: '1' }) -const F = Factory.define(User, ({ faker }) => { - return { - username: faker.internet.userName(), - } -}) +// const F = Factory.define(User, ({ faker }) => { +// return { +// username: faker.internet.userName(), +// } +// }) -const P = Factory.define(Profile, () => { - return {} -}) +// const P = Factory.define(Profile, () => { +// return {} +// }) -const ProfileF = P.state('social', () => {}).build() +// const ProfileF = P.state('social', () => {}).build() -const UserF = F.state('active', (user) => { - user.username = 'virk' -}) - .relation('profile', () => ProfileF) - .build() +// const UserF = F.state('active', (user) => { +// user.username = 'virk' +// }) +// .relation('profile', () => ProfileF) +// .build() -UserF.with('profile', 1).merge({}) +// UserF.with('profile', 1).merge({}) User.query().withCount('profile', (query) => { query.where('isActive', true).has('user', '>', 1) }) User.query().withCount('profile') -User.query() - .paginate(1, 1) - .then((users) => { - users.forEach((user) => user.username) - }) +// User.query() +// .paginate(1, 1) +// .then((users) => { +// users.forEach((user) => user.username) +// }) const user = new User() user.loadCount('profile') diff --git a/src/database/index.ts b/src/database/index.ts index 612d1be1..895a1073 100644 --- a/src/database/index.ts +++ b/src/database/index.ts @@ -29,7 +29,7 @@ import { InsertQueryBuilder } from './query_builder/insert.js' import { ReferenceBuilder } from './static_builder/reference.js' import { SimplePaginator } from './paginator/simple_paginator.js' import { DatabaseQueryBuilder } from './query_builder/database.js' -// import { ModelQueryBuilder } from '../Orm/QueryBuilder/index.js' +import { ModelQueryBuilder } from '../orm/query_builder/index.js' /** * Database class exposes the API to manage multiple connections and obtain an instance @@ -58,7 +58,7 @@ export class Database extends Macroable { */ DatabaseQueryBuilder = DatabaseQueryBuilder InsertQueryBuilder = InsertQueryBuilder - // ModelQueryBuilder = ModelQueryBuilder + ModelQueryBuilder = ModelQueryBuilder SimplePaginator = SimplePaginator /** diff --git a/src/Orm/Adapter/index.ts b/src/orm/adapter/index.ts similarity index 77% rename from src/Orm/Adapter/index.ts rename to src/orm/adapter/index.ts index f1b21535..0a543659 100644 --- a/src/Orm/Adapter/index.ts +++ b/src/orm/adapter/index.ts @@ -7,19 +7,22 @@ * file that was distributed with this source code. */ -/// - import { Exception } from '@poppinss/utils' -import { DatabaseContract } from '@ioc:Adonis/Lucid/Database' -import { LucidRow, LucidModel, AdapterContract, ModelAdapterOptions } from '@ioc:Adonis/Lucid/Orm' -import { isObject } from '../../utils' +import { + LucidRow, + LucidModel, + AdapterContract, + ModelAdapterOptions, +} from '../../../adonis-typings/model.js' +import { isObject } from '../../utils/index.js' +import type { Database } from '../../database/index.js' /** * Adapter exposes the API to make database queries and constructor * model instances from it. */ export class Adapter implements AdapterContract { - constructor(private db: DatabaseContract) {} + constructor(private db: Database) {} private getPrimaryKeyColumnName(Model: LucidModel) { return Model.$keys.attributesToColumns.get(Model.primaryKey, Model.primaryKey) @@ -28,20 +31,19 @@ export class Adapter implements AdapterContract { /** * Returns the query client based upon the model instance */ - public modelConstructorClient(modelConstructor: LucidModel, options?: ModelAdapterOptions) { + modelConstructorClient(modelConstructor: LucidModel, options?: ModelAdapterOptions) { if (options && options.client) { return options.client } const connection = (options && options.connection) || modelConstructor.connection - const profiler = options && options.profiler - return this.db.connection(connection, { profiler }) + return this.db.connection(connection) } /** * Returns the model query builder instance for a given model */ - public query(modelConstructor: LucidModel, options?: ModelAdapterOptions): any { + query(modelConstructor: LucidModel, options?: ModelAdapterOptions): any { const client = this.modelConstructorClient(modelConstructor, options) return client.modelQuery(modelConstructor) } @@ -49,7 +51,7 @@ export class Adapter implements AdapterContract { /** * Returns query client for a model instance by inspecting it's options */ - public modelClient(instance: LucidRow): any { + modelClient(instance: LucidRow): any { const modelConstructor = instance.constructor as unknown as LucidModel return instance.$trx ? instance.$trx @@ -59,7 +61,7 @@ export class Adapter implements AdapterContract { /** * Perform insert query on a given model instance */ - public async insert(instance: LucidRow, attributes: any) { + async insert(instance: LucidRow, attributes: any) { const query = instance.$getQueryFor('insert', this.modelClient(instance)) const Model = instance.constructor as LucidModel @@ -78,21 +80,21 @@ export class Adapter implements AdapterContract { /** * Perform update query on a given model instance */ - public async update(instance: LucidRow, dirty: any) { + async update(instance: LucidRow, dirty: any) { await instance.$getQueryFor('update', this.modelClient(instance)).update(dirty) } /** * Perform delete query on a given model instance */ - public async delete(instance: LucidRow) { + async delete(instance: LucidRow) { await instance.$getQueryFor('delete', this.modelClient(instance)).del() } /** * Refresh the model instance attributes */ - public async refresh(instance: LucidRow) { + async refresh(instance: LucidRow) { const Model = instance.constructor as LucidModel const primaryKeyColumnName = this.getPrimaryKeyColumnName(Model) diff --git a/src/Orm/BaseModel/index.ts b/src/orm/base_model/index.ts similarity index 82% rename from src/Orm/BaseModel/index.ts rename to src/orm/base_model/index.ts index 234159e4..c6c0e80a 100644 --- a/src/Orm/BaseModel/index.ts +++ b/src/orm/base_model/index.ts @@ -7,14 +7,13 @@ * file that was distributed with this source code. */ -/// - import { DateTime } from 'luxon' import equal from 'fast-deep-equal' -import { Hooks } from '@poppinss/hooks' -import { IocContract } from '@ioc:Adonis/Core/Application' -import { Exception, lodash, defineStaticProperty } from '@poppinss/utils' -import { QueryClientContract, TransactionClientContract } from '@ioc:Adonis/Lucid/Database' +import Hooks from '@poppinss/hooks' +import lodash from '@poppinss/utils/lodash' +import type { Container } from '@adonisjs/core/container' +import { Exception, defineStaticProperty } from '@poppinss/utils' +import { QueryClientContract, TransactionClientContract } from '../../../adonis-typings/database.js' import { LucidRow, @@ -34,30 +33,33 @@ import { ModelAssignOptions, ModelAdapterOptions, ModelRelationOptions, +} from '../../../adonis-typings/model.js' + +import { ModelRelations, RelationOptions, RelationshipsContract, ThroughRelationOptions, ManyToManyRelationOptions, -} from '@ioc:Adonis/Lucid/Orm' - -import { ModelKeys } from '../ModelKeys' -import { Preloader } from '../Preloader' -import { HasOne } from '../Relations/HasOne' -import { proxyHandler } from './proxyHandler' -import { HasMany } from '../Relations/HasMany' -import { BelongsTo } from '../Relations/BelongsTo' -import { ManyToMany } from '../Relations/ManyToMany' -import { HasManyThrough } from '../Relations/HasManyThrough' +} from '../../../adonis-typings/relations.js' + +import { ModelKeys } from '../model_keys/index.js' +import { Preloader } from '../preloader/index.js' +import { HasOne } from '../relations/has_one/index.js' +import { proxyHandler } from './proxy_handler.js' +import { HasMany } from '../relations/has_many/index.js' +import { BelongsTo } from '../relations/belongs_to/index.js' +import { ManyToMany } from '../relations/many_to_many/index.js' +import { HasManyThrough } from '../relations/has_many_through/index.js' import { isObject, collectValues, ensureRelation, managedTransaction, normalizeCherryPickObject, -} from '../../utils' -import { SnakeCaseNamingStrategy } from '../NamingStrategies/SnakeCase' -import { LazyLoadAggregates } from '../Relations/AggregatesLoader/LazyLoad' +} from '../../utils/index.js' +import { SnakeCaseNamingStrategy } from '../naming_strategies/snake_case.js' +import { LazyLoadAggregates } from '../relations/aggregates_loader/lazy_load.js' const MANY_RELATIONS = ['hasMany', 'manyToMany', 'hasManyThrough'] const DATE_TIME_TYPES = { @@ -73,19 +75,19 @@ function StaticImplements() { * Abstract class to define fully fledged data models */ @StaticImplements() -export class BaseModel implements LucidRow { +class BaseModelImpl implements LucidRow { /** * The adapter to be used for persisting and fetching data. * * NOTE: Adapter is a singleton and share among all the models, unless * a user wants to swap the adapter for a given model */ - public static $adapter: AdapterContract + static $adapter: AdapterContract /** * Naming strategy for model properties */ - public static namingStrategy = new SnakeCaseNamingStrategy() + static namingStrategy = new SnakeCaseNamingStrategy() /** * The container required to resolve hooks @@ -93,70 +95,70 @@ export class BaseModel implements LucidRow { * NOTE: Container is a singleton and share among all the models, unless * a user wants to swap the container for a given model */ - public static $container: IocContract + static $container: Container /** * Primary key is required to build relationships across models */ - public static primaryKey: string + static primaryKey: string /** * Whether or not the model has been booted. Booting the model initializes it's * static properties. Base models must not be initialized. */ - public static booted: boolean + static booted: boolean /** * Query scopes defined on the model */ - public static $queryScopes: any = {} + static $queryScopes: any = {} /** * A set of properties marked as computed. Computed properties are included in * the `toJSON` result, else they behave the same way as any other instance * property. */ - public static $computedDefinitions: Map + static $computedDefinitions: Map /** * Columns makes it easier to define extra props on the model * and distinguish them with the attributes to be sent * over to the adapter */ - public static $columnsDefinitions: Map + static $columnsDefinitions: Map /** * Registered relationships for the given model */ - public static $relationsDefinitions: Map + static $relationsDefinitions: Map /** * The name of database table. It is auto generated from the model name, unless * specified */ - public static table: string + static table: string /** * Self assign the primary instead of relying on the database to * return it back */ - public static selfAssignPrimaryKey: boolean + static selfAssignPrimaryKey: boolean /** * A custom connection to use for queries. The connection defined on * query builder is preferred over the model connection */ - public static connection?: string + static connection?: string /** * Storing model hooks */ - public static $hooks: Hooks + static $hooks: Hooks /** * Keys mappings to make the lookups easy */ - public static $keys: { + static $keys: { attributesToColumns: ModelKeysContract attributesToSerialized: ModelKeysContract columnsToAttributes: ModelKeysContract @@ -190,7 +192,7 @@ export class BaseModel implements LucidRow { */ private static newUpIfMissing( rowObjects: ModelObject[], - existingRows: BaseModel[], + existingRows: BaseModelImpl[], keys: string[], mergeAttribute: boolean, options?: ModelAdapterOptions, @@ -226,7 +228,7 @@ export class BaseModel implements LucidRow { /** * Returns the model query instance for the given model */ - public static query(options?: ModelAdapterOptions): any { + static query(options?: ModelAdapterOptions): any { return this.$adapter.query(this, options) } @@ -234,7 +236,7 @@ export class BaseModel implements LucidRow { * Create a model instance from the adapter result. The result value must * be a valid object, otherwise `null` is returned. */ - public static $createFromAdapterResult( + static $createFromAdapterResult( adapterResult: ModelObject, sideloadAttributes?: ModelObject, options?: ModelAdapterOptions @@ -261,7 +263,7 @@ export class BaseModel implements LucidRow { * 1. If top level value is not an array, then an empty array is returned. * 2. If row is not an object, then it will be ignored. */ - public static $createMultipleFromAdapterResult( + static $createMultipleFromAdapterResult( this: T, adapterResults: ModelObject[], sideloadAttributes?: ModelObject, @@ -283,7 +285,7 @@ export class BaseModel implements LucidRow { * Define a new column on the model. This is required, so that * we differentiate between plain properties vs model attributes. */ - public static $addColumn(name: string, options: Partial) { + static $addColumn(name: string, options: Partial) { const descriptor = Object.getOwnPropertyDescriptor(this.prototype, name) const column: ModelColumnOptions = { @@ -325,21 +327,21 @@ export class BaseModel implements LucidRow { /** * Returns a boolean telling if column exists on the model */ - public static $hasColumn(name: string): boolean { + static $hasColumn(name: string): boolean { return this.$columnsDefinitions.has(name) } /** * Returns the column for a given name */ - public static $getColumn(name: string): ModelColumnOptions | undefined { + static $getColumn(name: string): ModelColumnOptions | undefined { return this.$columnsDefinitions.get(name) } /** * Adds a computed node */ - public static $addComputed(name: string, options: Partial) { + static $addComputed(name: string, options: Partial) { const computed: ComputedOptions = { serializeAs: options.serializeAs || name, meta: options.meta, @@ -351,14 +353,14 @@ export class BaseModel implements LucidRow { /** * Find if some property is marked as computed */ - public static $hasComputed(name: string): boolean { + static $hasComputed(name: string): boolean { return this.$computedDefinitions.has(name) } /** * Get computed node */ - public static $getComputed(name: string): ComputedOptions | undefined { + static $getComputed(name: string): ComputedOptions | undefined { return this.$computedDefinitions.get(name) } @@ -368,7 +370,7 @@ export class BaseModel implements LucidRow { protected static $addHasOne( name: string, relatedModel: () => LucidModel, - options: RelationOptions + options: RelationOptions> ) { this.$relationsDefinitions.set(name, new HasOne(name, relatedModel, options, this)) } @@ -379,7 +381,7 @@ export class BaseModel implements LucidRow { protected static $addHasMany( name: string, relatedModel: () => LucidModel, - options: RelationOptions + options: RelationOptions> ) { this.$relationsDefinitions.set(name, new HasMany(name, relatedModel, options, this)) } @@ -390,7 +392,7 @@ export class BaseModel implements LucidRow { protected static $addBelongsTo( name: string, relatedModel: () => LucidModel, - options: RelationOptions + options: RelationOptions> ) { this.$relationsDefinitions.set(name, new BelongsTo(name, relatedModel, options, this)) } @@ -401,7 +403,7 @@ export class BaseModel implements LucidRow { protected static $addManyToMany( name: string, relatedModel: () => LucidModel, - options: ManyToManyRelationOptions + options: ManyToManyRelationOptions> ) { this.$relationsDefinitions.set(name, new ManyToMany(name, relatedModel, options, this)) } @@ -412,7 +414,7 @@ export class BaseModel implements LucidRow { protected static $addHasManyThrough( name: string, relatedModel: () => LucidModel, - options: ThroughRelationOptions + options: ThroughRelationOptions> ) { this.$relationsDefinitions.set(name, new HasManyThrough(name, relatedModel, options, this)) } @@ -420,9 +422,9 @@ export class BaseModel implements LucidRow { /** * Adds a relationship */ - public static $addRelation( + static $addRelation( name: string, - type: ModelRelations['__opaque_type'], + type: ModelRelations['__opaque_type'], relatedModel: () => LucidModel, options: ModelRelationOptions ) { @@ -440,14 +442,18 @@ export class BaseModel implements LucidRow { this.$addManyToMany( name, relatedModel, - options as ManyToManyRelationOptions + options as ManyToManyRelationOptions> ) break case 'hasManyThrough': this.$addHasManyThrough( name, relatedModel, - options as ThroughRelationOptions + options as ThroughRelationOptions< + LucidModel, + LucidModel, + ModelRelations + > ) break default: @@ -458,14 +464,14 @@ export class BaseModel implements LucidRow { /** * Find if some property is marked as a relation or not */ - public static $hasRelation(name: any): boolean { + static $hasRelation(name: any): boolean { return this.$relationsDefinitions.has(name) } /** * Returns relationship node for a given relation */ - public static $getRelation(name: any): any { + static $getRelation(name: any): any { return this.$relationsDefinitions.get(name)! } @@ -476,15 +482,14 @@ export class BaseModel implements LucidRow { * Inherit strategy will clone the property from the parent model * and will set it on the current model */ - public static $defineProperty( + static $defineProperty( this: Model, propertyName: Prop, defaultValue: Model[Prop], strategy: 'inherit' | 'define' | ((value: Model[Prop]) => Model[Prop]) ) { - defineStaticProperty(this, BaseModel, { - propertyName: propertyName, - defaultValue: defaultValue, + defineStaticProperty(this, propertyName, { + initialValue: defaultValue, strategy: strategy, }) } @@ -492,7 +497,7 @@ export class BaseModel implements LucidRow { /** * Boot the model */ - public static boot() { + static boot() { /** * Define the property when not defined on self */ @@ -580,30 +585,26 @@ export class BaseModel implements LucidRow { /** * Define hooks. */ - this.$defineProperty( - '$hooks', - new Hooks(this.$container.getResolver(undefined, 'modelHooks', 'App/Models/Hooks')), - (value: Hooks) => { - const hooks = new Hooks() - hooks.merge(value) - return hooks - } - ) + this.$defineProperty('$hooks', new Hooks(), (value: Hooks) => { + const hooks = new Hooks() + hooks.merge(value) + return hooks + }) } /** * Register before hooks */ - public static before(event: EventsList, handler: HooksHandler) { - this.$hooks.add('before', event, handler) + static before(event: EventsList, handler: HooksHandler) { + this.$hooks.add(`before:${event}`, handler) return this } /** * Register after hooks */ - public static after(event: EventsList, handler: HooksHandler) { - this.$hooks.add('after', event, handler) + static after(event: EventsList, handler: HooksHandler) { + this.$hooks.add(`after:${event}`, handler) return this } @@ -611,7 +612,7 @@ export class BaseModel implements LucidRow { * Returns a fresh persisted instance of model by applying * attributes to the model instance */ - public static async create(values: any, options?: ModelAssignOptions): Promise { + static async create(values: any, options?: ModelAssignOptions): Promise { const instance = this.newUpWithOptions(values, options, options?.allowExtraProperties) await instance.save() return instance @@ -623,7 +624,7 @@ export class BaseModel implements LucidRow { * If required, you can also pass a transaction client and the method * will use that instead of create a new one. */ - public static async createMany(values: any, options?: ModelAssignOptions): Promise { + static async createMany(values: any, options?: ModelAssignOptions): Promise { const client = this.$adapter.modelConstructorClient(this, options) return managedTransaction(client, async (trx) => { @@ -645,7 +646,7 @@ export class BaseModel implements LucidRow { /** * Find model instance using the primary key */ - public static async find(value: any, options?: ModelAdapterOptions) { + static async find(value: any, options?: ModelAdapterOptions) { if (value === undefined) { throw new Exception('"find" expects a value. Received undefined') } @@ -656,7 +657,7 @@ export class BaseModel implements LucidRow { /** * Find model instance using the primary key */ - public static async findOrFail(value: any, options?: ModelAdapterOptions) { + static async findOrFail(value: any, options?: ModelAdapterOptions) { if (value === undefined) { throw new Exception('"findOrFail" expects a value. Received undefined') } @@ -667,7 +668,7 @@ export class BaseModel implements LucidRow { /** * Find model instance using a key/value pair */ - public static async findBy(key: string, value: any, options?: ModelAdapterOptions) { + static async findBy(key: string, value: any, options?: ModelAdapterOptions) { if (value === undefined) { throw new Exception('"findBy" expects a value. Received undefined') } @@ -678,7 +679,7 @@ export class BaseModel implements LucidRow { /** * Find model instance using a key/value pair */ - public static async findByOrFail(key: string, value: any, options?: ModelAdapterOptions) { + static async findByOrFail(key: string, value: any, options?: ModelAdapterOptions) { if (value === undefined) { throw new Exception('"findByOrFail" expects a value. Received undefined') } @@ -688,21 +689,21 @@ export class BaseModel implements LucidRow { /** * Same as `query().first()` */ - public static async first(options?: ModelAdapterOptions) { + static async first(options?: ModelAdapterOptions) { return this.query(options).first() } /** * Same as `query().firstOrFail()` */ - public static async firstOrFail(options?: ModelAdapterOptions) { + static async firstOrFail(options?: ModelAdapterOptions) { return this.query(options).firstOrFail() } /** * Find model instance using a key/value pair */ - public static async findMany(value: any[], options?: ModelAdapterOptions) { + static async findMany(value: any[], options?: ModelAdapterOptions) { if (value === undefined) { throw new Exception('"findMany" expects a value. Received undefined') } @@ -717,7 +718,7 @@ export class BaseModel implements LucidRow { * Find model instance using a key/value pair or create a * new one without persisting it. */ - public static async firstOrNew( + static async firstOrNew( searchPayload: any, savePayload?: any, options?: ModelAssignOptions @@ -745,7 +746,7 @@ export class BaseModel implements LucidRow { /** * Same as `firstOrNew`, but also persists the newly created model instance. */ - public static async firstOrCreate( + static async firstOrCreate( searchPayload: any, savePayload?: any, options?: ModelAssignOptions @@ -774,7 +775,7 @@ export class BaseModel implements LucidRow { /** * Updates or creates a new row inside the database */ - public static async updateOrCreate( + static async updateOrCreate( searchPayload: any, updatedPayload: any, options?: ModelAssignOptions @@ -811,22 +812,24 @@ export class BaseModel implements LucidRow { /** * Find existing rows or create an in-memory instances of the missing ones. */ - public static async fetchOrNewUpMany( + static async fetchOrNewUpMany( uniqueKeys: any, payload: any, options?: ModelAssignOptions ): Promise { uniqueKeys = Array.isArray(uniqueKeys) ? uniqueKeys : [uniqueKeys] - const uniquenessPair = uniqueKeys.map((uniqueKey: string) => { - return { - key: uniqueKey, - value: collectValues(payload, uniqueKey, () => { - throw new Exception( - `Value for the "${uniqueKey}" is null or undefined inside "fetchOrNewUpMany" payload` - ) - }), + const uniquenessPair: { key: string; value: string[] }[] = uniqueKeys.map( + (uniqueKey: string) => { + return { + key: uniqueKey, + value: collectValues(payload, uniqueKey, () => { + throw new Exception( + `Value for the "${uniqueKey}" is null or undefined inside "fetchOrNewUpMany" payload` + ) + }), + } } - }) + ) /** * Find existing rows @@ -853,22 +856,24 @@ export class BaseModel implements LucidRow { * is invoked, so that each insert goes through the lifecycle of model * hooks. */ - public static async fetchOrCreateMany( + static async fetchOrCreateMany( uniqueKeys: any, payload: any, options?: ModelAssignOptions ): Promise { uniqueKeys = Array.isArray(uniqueKeys) ? uniqueKeys : [uniqueKeys] - const uniquenessPair = uniqueKeys.map((uniqueKey: string) => { - return { - key: uniqueKey, - value: collectValues(payload, uniqueKey, () => { - throw new Exception( - `Value for the "${uniqueKey}" is null or undefined inside "fetchOrCreateMany" payload` - ) - }), + const uniquenessPair: { key: string; value: string[] }[] = uniqueKeys.map( + (uniqueKey: string) => { + return { + key: uniqueKey, + value: collectValues(payload, uniqueKey, () => { + throw new Exception( + `Value for the "${uniqueKey}" is null or undefined inside "fetchOrCreateMany" payload` + ) + }), + } } - }) + ) /** * Find existing rows @@ -915,22 +920,24 @@ export class BaseModel implements LucidRow { * is invoked, so that each insert and update goes through the lifecycle * of model hooks. */ - public static async updateOrCreateMany( + static async updateOrCreateMany( uniqueKeys: any, payload: any, options?: ModelAssignOptions ): Promise { uniqueKeys = Array.isArray(uniqueKeys) ? uniqueKeys : [uniqueKeys] - const uniquenessPair = uniqueKeys.map((uniqueKey: string) => { - return { - key: uniqueKey, - value: collectValues(payload, uniqueKey, () => { - throw new Exception( - `Value for the "${uniqueKey}" is null or undefined inside "updateOrCreateMany" payload` - ) - }), + const uniquenessPair: { key: string; value: string[] }[] = uniqueKeys.map( + (uniqueKey: string) => { + return { + key: uniqueKey, + value: collectValues(payload, uniqueKey, () => { + throw new Exception( + `Value for the "${uniqueKey}" is null or undefined inside "updateOrCreateMany" payload` + ) + }), + } } - }) + ) const client = this.$adapter.modelConstructorClient(this as LucidModel, options) @@ -965,14 +972,14 @@ export class BaseModel implements LucidRow { /** * Returns all rows from the model table */ - public static async all(options?: ModelAdapterOptions) { + static async all(options?: ModelAdapterOptions) { return this.query(options).orderBy(this.primaryKey, 'desc') } /** * Truncate model table */ - public static truncate(cascade: boolean = false) { + static truncate(cascade: boolean = false) { return this.query().client.truncate(this.table, cascade) } @@ -996,7 +1003,7 @@ export class BaseModel implements LucidRow { * The transaction listener listens for the `commit` and `rollback` events and * cleansup the `$trx` reference */ - private transactionListener = function listener() { + private transactionListener = function listener(this: BaseModelImpl) { this.modelTrx = undefined }.bind(this) @@ -1022,7 +1029,10 @@ export class BaseModel implements LucidRow { */ private ensureIsntDeleted() { if (this.$isDeleted) { - throw new Exception('Cannot mutate delete model instance', 500, 'E_MODEL_DELETED') + throw new Exception('Cannot mutate delete model instance', { + status: 500, + code: 'E_MODEL_DELETED', + }) } } @@ -1040,7 +1050,7 @@ export class BaseModel implements LucidRow { /** * Return early when not dealing with date time columns */ - if (!columnType || !DATE_TIME_TYPES[columnType]) { + if (!columnType || !(columnType in DATE_TIME_TYPES)) { return } @@ -1048,9 +1058,9 @@ export class BaseModel implements LucidRow { * Set the value when its missing and `autoCreate` or `autoUpdate` * flags are defined. */ - const attributeValue = this[attributeName] + const attributeValue = (this as any)[attributeName] if (!attributeValue && (column.meta.autoCreate || column.meta.autoUpdate)) { - this[attributeName] = DateTime.local() + ;(this as any)[attributeName] = DateTime.local() return } }) @@ -1071,11 +1081,11 @@ export class BaseModel implements LucidRow { * Return early when not dealing with date time columns or auto update * is not set to true */ - if (!columnType || !DATE_TIME_TYPES[columnType] || !column.meta.autoUpdate) { + if (!columnType || !(columnType in DATE_TIME_TYPES) || !column.meta.autoUpdate) { return } - this[attributeName] = DateTime.local() + ;(this as any)[attributeName] = DateTime.local() }) } @@ -1087,7 +1097,7 @@ export class BaseModel implements LucidRow { protected prepareForAdapter(attributes: ModelObject) { const Model = this.constructor as typeof BaseModel - return Object.keys(attributes).reduce((result, key) => { + return Object.keys(attributes).reduce((result: any, key) => { const column = Model.$getColumn(key)! const value = @@ -1141,23 +1151,23 @@ export class BaseModel implements LucidRow { /** * A type only reference to the columns */ - public $columns: any = {} + $columns: any = {} /** * A copy of attributes that will be sent over to adapter */ - public $attributes: ModelObject = {} + $attributes: ModelObject = {} /** * Original represents the properties that already has been * persisted or loaded by the adapter. */ - public $original: ModelObject = {} + $original: ModelObject = {} /** * Preloaded relationships on the model instance */ - public $preloaded: { [relation: string]: LucidRow | LucidRow[] } = {} + $preloaded: { [relation: string]: LucidRow | LucidRow[] } = {} /** * Extras are dynamic properties set on the model instance, which @@ -1166,7 +1176,7 @@ export class BaseModel implements LucidRow { * This is helpful when adapter wants to load some extra data conditionally * and that data must not be persisted back the adapter. */ - public $extras: ModelObject = {} + $extras: ModelObject = {} /** * Sideloaded are dynamic properties set on the model instance, which @@ -1182,36 +1192,38 @@ export class BaseModel implements LucidRow { * - Sideloaded are shared across multiple model instances created via `$createMultipleFromAdapterResult`. * - Sideloaded are passed to the relationships as well. */ - public $sideloaded: ModelObject = {} + $sideloaded: ModelObject = {} /** * Persisted means the model has been persisted with the adapter. This will * also be true, when model instance is created as a result of fetch * call from the adapter. */ - public $isPersisted: boolean = false + $isPersisted: boolean = false /** * Once deleted the model instance cannot make calls to the adapter */ - public $isDeleted: boolean = false + $isDeleted: boolean = false /** * `$isLocal` tells if the model instance was created locally vs * one generated as a result of fetch call from the adapter. */ - public $isLocal: boolean = true + $isLocal: boolean = true + + declare serializeExtras: boolean | (() => Record) /** * Returns the value of primary key. The value must be * set inside attributes object */ - public get $primaryKeyValue(): any | undefined { + get $primaryKeyValue(): any | undefined { const model = this.constructor as typeof BaseModel const column = model.$getColumn(model.primaryKey) if (column && column.hasGetter) { - return this[model.primaryKey] + return (this as any)[model.primaryKey] } return this.$getAttribute(model.primaryKey) @@ -1220,7 +1232,7 @@ export class BaseModel implements LucidRow { /** * Opposite of [[this.isPersisted]] */ - public get $isNew(): boolean { + get $isNew(): boolean { return !this.$isPersisted } @@ -1228,7 +1240,7 @@ export class BaseModel implements LucidRow { * Returns dirty properties of a model by doing a diff * between original values and current attributes */ - public get $dirty(): any { + get $dirty(): any { const processedKeys: string[] = [] /** @@ -1238,7 +1250,7 @@ export class BaseModel implements LucidRow { return this.$attributes } - const dirty = Object.keys(this.$attributes).reduce((result, key) => { + const dirty = Object.keys(this.$attributes).reduce((result: any, key) => { const value = this.$attributes[key] const originalValue = this.$original[key] let isEqual = true @@ -1280,21 +1292,21 @@ export class BaseModel implements LucidRow { /** * Finding if model is dirty with changes or not */ - public get $isDirty() { + get $isDirty() { return Object.keys(this.$dirty).length > 0 } /** * Returns the transaction */ - public get $trx(): TransactionClientContract | undefined { + get $trx(): TransactionClientContract | undefined { return this.modelTrx } /** * Set the trx to be used by the model to executing queries */ - public set $trx(trx: TransactionClientContract | undefined) { + set $trx(trx: TransactionClientContract | undefined) { if (!trx) { this.modelTrx = undefined return @@ -1319,14 +1331,14 @@ export class BaseModel implements LucidRow { /** * Get options */ - public get $options(): ModelOptions | undefined { + get $options(): ModelOptions | undefined { return this.modelOptions } /** * Set options */ - public set $options(options: ModelOptions | undefined) { + set $options(options: ModelOptions | undefined) { if (!options) { this.modelOptions = undefined return @@ -1336,16 +1348,12 @@ export class BaseModel implements LucidRow { if (options.connection) { this.modelOptions.connection = options.connection } - - if (options.profiler) { - this.modelOptions.profiler = options.profiler - } } /** * Set options on the model instance along with transaction */ - public $setOptionsAndTrx(options?: ModelAdapterOptions): void { + $setOptionsAndTrx(options?: ModelAdapterOptions): void { if (!options) { return } @@ -1359,7 +1367,7 @@ export class BaseModel implements LucidRow { /** * A chainable method to set transaction on the model */ - public useTransaction(trx: TransactionClientContract): this { + useTransaction(trx: TransactionClientContract): this { this.$trx = trx return this } @@ -1367,7 +1375,7 @@ export class BaseModel implements LucidRow { /** * A chainable method to set transaction on the model */ - public useConnection(connection: string): this { + useConnection(connection: string): this { this.$options = { connection } return this } @@ -1375,7 +1383,7 @@ export class BaseModel implements LucidRow { /** * Set attribute */ - public $setAttribute(key: string, value: any) { + $setAttribute(key: string, value: any) { this.ensureIsntDeleted() this.$attributes[key] = value } @@ -1383,7 +1391,7 @@ export class BaseModel implements LucidRow { /** * Get value of attribute */ - public $getAttribute(key: string): any { + $getAttribute(key: string): any { return this.$attributes[key] } @@ -1392,7 +1400,7 @@ export class BaseModel implements LucidRow { * the mutated by a getter. This is done to avoid re-mutating * the same attribute value over and over again. */ - public $getAttributeFromCache(key: string, callback: CacheNode['getter']): any { + $getAttributeFromCache(key: string, callback: CacheNode['getter']): any { const original = this.$getAttribute(key) const cached = this.cachedGetters[key] @@ -1428,14 +1436,14 @@ export class BaseModel implements LucidRow { /** * Returns the related model or default value when model is missing */ - public $getRelated(key: any): any { + $getRelated(key: any): any { return this.$preloaded[key] } /** * A boolean to know if relationship has been preloaded or not */ - public $hasRelated(key: any): boolean { + $hasRelated(key: any): boolean { return this.$preloaded[key] !== undefined } @@ -1443,7 +1451,7 @@ export class BaseModel implements LucidRow { * Sets the related data on the model instance. The method internally handles * `one to one` or `many` relations */ - public $setRelated(key: any, models: LucidRow | LucidRow[]) { + $setRelated(key: any, models: LucidRow | LucidRow[]) { const Model = this.constructor as typeof BaseModel const relation = Model.$relationsDefinitions.get(key as string) @@ -1472,7 +1480,7 @@ export class BaseModel implements LucidRow { /** * Push related adds to the existing related collection */ - public $pushRelated(key: any, models: LucidRow | LucidRow[]) { + $pushRelated(key: any, models: LucidRow | LucidRow[]) { const Model = this.constructor as typeof BaseModel const relation = Model.$relationsDefinitions.get(key as string) @@ -1512,7 +1520,7 @@ export class BaseModel implements LucidRow { * 1. If key is unknown, it will be added to the `extras` object. * 2. If key is defined as a relationship, it will be ignored and one must call `$setRelated`. */ - public $consumeAdapterResult(adapterResult: ModelObject, sideloadedAttributes?: ModelObject) { + $consumeAdapterResult(adapterResult: ModelObject, sideloadedAttributes?: ModelObject) { const Model = this.constructor as typeof BaseModel /** @@ -1567,7 +1575,7 @@ export class BaseModel implements LucidRow { * Set directly on the model */ if (this.hasOwnProperty(key)) { - this[key] = adapterResult[key] + ;(this as any)[key] = adapterResult[key] return } @@ -1580,7 +1588,7 @@ export class BaseModel implements LucidRow { * Sync originals with the attributes. After this `isDirty` will * return false */ - public $hydrateOriginals() { + $hydrateOriginals() { this.$original = {} lodash.merge(this.$original, this.$attributes) } @@ -1590,7 +1598,7 @@ export class BaseModel implements LucidRow { * fill isn't allowed, since we disallow setting relationships * locally */ - public fill(values: any, allowExtraProperties: boolean = false): this { + fill(values: any, allowExtraProperties: boolean = false): this { this.$attributes = {} this.merge(values, allowExtraProperties) this.fillInvoked = true @@ -1603,7 +1611,7 @@ export class BaseModel implements LucidRow { * 1. If key is unknown, it will be added to the `extras` object. * 2. If key is defined as a relationship, it will be ignored and one must call `$setRelated`. */ - public merge(values: any, allowExtraProperties: boolean = false): this { + merge(values: any, allowExtraProperties: boolean = false): this { const Model = this.constructor as typeof BaseModel /** @@ -1617,7 +1625,7 @@ export class BaseModel implements LucidRow { * Set as column */ if (Model.$hasColumn(key)) { - this[key] = value + ;(this as any)[key] = value return } @@ -1628,7 +1636,7 @@ export class BaseModel implements LucidRow { */ const attributeName = Model.$keys.columnsToAttributes.get(key) if (attributeName) { - this[attributeName] = value + ;(this as any)[attributeName] = value return } @@ -1645,7 +1653,7 @@ export class BaseModel implements LucidRow { * as it is vs defining it as an extra property */ if (this.hasOwnProperty(key)) { - this[key] = value + ;(this as any)[key] = value return } @@ -1669,7 +1677,7 @@ export class BaseModel implements LucidRow { * Enable force update even when no attributes * are dirty */ - public enableForceUpdate(): this { + enableForceUpdate(): this { this.forceUpdate = true return this } @@ -1677,7 +1685,7 @@ export class BaseModel implements LucidRow { /** * Preloads one or more relationships for the current model */ - public async load(relationName: any, callback?: any) { + async load(relationName: any, callback?: any) { this.ensureIsntDeleted() if (!this.$isPersisted) { @@ -1701,7 +1709,7 @@ export class BaseModel implements LucidRow { /** * @deprecated */ - public async preload(relationName: any, callback?: any) { + async preload(relationName: any, callback?: any) { process.emitWarning( 'DeprecationWarning', '"Model.preload()" is deprecated. Use "Model.load()" instead' @@ -1713,7 +1721,7 @@ export class BaseModel implements LucidRow { /** * Lazy load the relationship aggregate value */ - public loadAggregate(relationName: any, callback?: any) { + loadAggregate(relationName: any, callback?: any) { this.ensureIsntDeleted() if (!this.$isPersisted) { @@ -1728,7 +1736,7 @@ export class BaseModel implements LucidRow { /** * Lazy load the relationship count value */ - public loadCount(relationName: any, callback?: any) { + loadCount(relationName: any, callback?: any) { this.ensureIsntDeleted() if (!this.$isPersisted) { @@ -1743,7 +1751,7 @@ export class BaseModel implements LucidRow { /** * Perform save on the model instance to commit mutations. */ - public async save(): Promise { + async save(): Promise { this.ensureIsntDeleted() const Model = this.constructor as typeof BaseModel @@ -1751,8 +1759,8 @@ export class BaseModel implements LucidRow { * Persit the model when it's not persisted already */ if (!this.$isPersisted) { - await Model.$hooks.exec('before', 'create', this) - await Model.$hooks.exec('before', 'save', this) + await Model.$hooks.runner('before:create').run(this) + await Model.$hooks.runner('before:save').run(this) this.initiateAutoCreateColumns() await Model.$adapter.insert(this, this.prepareForAdapter(this.$attributes)) @@ -1760,8 +1768,8 @@ export class BaseModel implements LucidRow { this.$hydrateOriginals() this.$isPersisted = true - await Model.$hooks.exec('after', 'create', this) - await Model.$hooks.exec('after', 'save', this) + await Model.$hooks.runner('after:create').run(this) + await Model.$hooks.runner('after:save').run(this) return this } @@ -1770,8 +1778,8 @@ export class BaseModel implements LucidRow { * to make mutations that produces one or more `$dirty` * fields. */ - await Model.$hooks.exec('before', 'update', this) - await Model.$hooks.exec('before', 'save', this) + await Model.$hooks.runner('before:update').run(this) + await Model.$hooks.runner('before:save').run(this) const forceUpdate = this.forceUpdate this.forceUpdate = false @@ -1794,30 +1802,30 @@ export class BaseModel implements LucidRow { } this.$hydrateOriginals() - await Model.$hooks.exec('after', 'update', this) - await Model.$hooks.exec('after', 'save', this) + await Model.$hooks.runner('after:update').run(this) + await Model.$hooks.runner('after:save').run(this) return this } /** * Perform delete by issuing a delete request on the adapter */ - public async delete() { + async delete() { this.ensureIsntDeleted() const Model = this.constructor as typeof BaseModel - await Model.$hooks.exec('before', 'delete', this) + await Model.$hooks.runner('before:delete').run(this) await Model.$adapter.delete(this) this.$isDeleted = true - await Model.$hooks.exec('after', 'delete', this) + await Model.$hooks.runner('after:delete').run(this) } /** * Serializes model attributes to a plain object */ - public serializeAttributes(fields?: CherryPickFields, raw: boolean = false): ModelObject { + serializeAttributes(fields?: CherryPickFields, raw: boolean = false): ModelObject { const Model = this.constructor as LucidModel return Object.keys(this.$attributes).reduce((result, key) => { @@ -1826,7 +1834,7 @@ export class BaseModel implements LucidRow { return result } - const value = this[key] + const value = (this as any)[key] result[column.serializeAs] = typeof column.serialize === 'function' && !raw ? column.serialize(value, key, this) : value @@ -1837,12 +1845,12 @@ export class BaseModel implements LucidRow { /** * Serializes model compute properties to an object. */ - public serializeComputed(fields?: CherryPickFields): ModelObject { + serializeComputed(fields?: CherryPickFields): ModelObject { const Model = this.constructor as LucidModel const result: ModelObject = {} Model.$computedDefinitions.forEach((value, key) => { - const computedValue = this[key] + const computedValue = (this as any)[key] if (computedValue !== undefined && this.shouldSerializeField(value.serializeAs, fields)) { result[value.serializeAs] = computedValue } @@ -1855,13 +1863,13 @@ export class BaseModel implements LucidRow { * Serializes relationships to a plain object. When `raw=true`, it will * recurisvely serialize the relationships as well. */ - public serializeRelations( + serializeRelations( cherryPick?: CherryPick['relations'], raw: boolean = false ): ModelObject | { [key: string]: LucidRow | LucidRow[] } { const Model = this.constructor as LucidModel - return Object.keys(this.$preloaded).reduce((result, key) => { + return Object.keys(this.$preloaded).reduce((result: any, key) => { const relation = Model.$getRelation(key as any)! as RelationshipsContract /** @@ -1899,12 +1907,12 @@ export class BaseModel implements LucidRow { /** * Converting model to it's JSON representation */ - public serialize(cherryPick?: CherryPick) { + serialize(cherryPick?: CherryPick) { let extras: any = null - if (this['serializeExtras'] === true) { + if (this.serializeExtras === true) { extras = { meta: this.$extras } - } else if (typeof this['serializeExtras'] === 'function') { - extras = this['serializeExtras']() + } else if (typeof this.serializeExtras === 'function') { + extras = this.serializeExtras() } return { @@ -1918,14 +1926,14 @@ export class BaseModel implements LucidRow { /** * Convert model to a plain Javascript object */ - public toObject() { + toObject() { const Model = this.constructor as LucidModel const computed: ModelObject = {} /** * Relationships toObject */ - const preloaded = Object.keys(this.$preloaded).reduce((result, key) => { + const preloaded = Object.keys(this.$preloaded).reduce((result: any, key) => { const value = this.$preloaded[key] result[key] = Array.isArray(value) ? value.map((one) => one.toObject()) : value.toObject() @@ -1936,7 +1944,7 @@ export class BaseModel implements LucidRow { * Update computed object with computed definitions */ Model.$computedDefinitions.forEach((_, key) => { - const computedValue = this[key] + const computedValue = (this as any)[key] if (computedValue !== undefined) { computed[key] = computedValue } @@ -1954,7 +1962,7 @@ export class BaseModel implements LucidRow { * Returns the serialize method output. However, any model can overwrite * it to define it's custom serialize output */ - public toJSON() { + toJSON() { return this.serialize() } @@ -1963,7 +1971,7 @@ export class BaseModel implements LucidRow { * Since the query builder for these actions are not exposed to * the end user, this method gives a way to compose queries. */ - public $getQueryFor( + $getQueryFor( action: 'insert' | 'update' | 'delete' | 'refresh', client: QueryClientContract ): any { @@ -2000,7 +2008,7 @@ export class BaseModel implements LucidRow { /** * Returns an instance of relationship on the given model */ - public related(relationName: any): any { + related(relationName: any): any { const Model = this.constructor as typeof BaseModel const relation = Model.$getRelation(relationName as string) ensureRelation(relationName, relation) @@ -2012,7 +2020,7 @@ export class BaseModel implements LucidRow { /** * Reload/Refresh the model instance */ - public async refresh() { + async refresh() { this.ensureIsntDeleted() /** @@ -2028,3 +2036,5 @@ export class BaseModel implements LucidRow { return this } } + +export const BaseModel: LucidModel = BaseModelImpl diff --git a/src/Orm/BaseModel/proxyHandler.ts b/src/orm/base_model/proxy_handler.ts similarity index 95% rename from src/Orm/BaseModel/proxyHandler.ts rename to src/orm/base_model/proxy_handler.ts index e1334b98..eb71f671 100644 --- a/src/Orm/BaseModel/proxyHandler.ts +++ b/src/orm/base_model/proxy_handler.ts @@ -7,9 +7,7 @@ * file that was distributed with this source code. */ -/// - -import { LucidModel } from '@ioc:Adonis/Lucid/Orm' +import { LucidModel } from '../../../adonis-typings/model.js' /** * A proxy trap to add support for custom getters and setters diff --git a/src/Orm/Decorators/date.ts b/src/orm/decorators/date.ts similarity index 89% rename from src/Orm/Decorators/date.ts rename to src/orm/decorators/date.ts index 478d350e..08fc6a32 100644 --- a/src/Orm/Decorators/date.ts +++ b/src/orm/decorators/date.ts @@ -9,7 +9,7 @@ import { DateTime } from 'luxon' import { Exception } from '@poppinss/utils' -import { LucidRow, LucidModel, DateColumnDecorator } from '@ioc:Adonis/Lucid/Orm' +import { LucidRow, LucidModel, DateColumnDecorator } from '../../../adonis-typings/model.js' /** * The method to prepare the date column before persisting it's @@ -33,8 +33,10 @@ function prepareDateColumn(value: any, attributeName: string, modelInstance: Luc if (!value.isValid) { throw new Exception( `Invalid value for "${modelName}.${attributeName}". ${value.invalidReason}`, - 500, - 'E_INVALID_DATE_COLUMN_VALUE' + { + status: 500, + code: 'E_INVALID_DATE_COLUMN_VALUE', + } ) } @@ -46,8 +48,10 @@ function prepareDateColumn(value: any, attributeName: string, modelInstance: Luc */ throw new Exception( `The value for "${modelName}.${attributeName}" must be an instance of "luxon.DateTime"`, - 500, - 'E_INVALID_DATE_COLUMN_VALUE' + { + status: 500, + code: 'E_INVALID_DATE_COLUMN_VALUE', + } ) } @@ -82,8 +86,10 @@ function consumeDateColumn(value: any, attributeName: string, modelInstance: Luc const modelName = modelInstance.constructor.name throw new Exception( `Cannot format "${modelName}.${attributeName}" ${typeof value} value to an instance of "luxon.DateTime"`, - 500, - 'E_INVALID_DATE_COLUMN_VALUE' + { + status: 500, + code: 'E_INVALID_DATE_COLUMN_VALUE', + } ) } diff --git a/src/Orm/Decorators/datetime.ts b/src/orm/decorators/date_time.ts similarity index 89% rename from src/Orm/Decorators/datetime.ts rename to src/orm/decorators/date_time.ts index 1f4384c0..2feabce4 100644 --- a/src/Orm/Decorators/datetime.ts +++ b/src/orm/decorators/date_time.ts @@ -9,7 +9,7 @@ import { DateTime } from 'luxon' import { Exception } from '@poppinss/utils' -import { LucidRow, LucidModel, DateTimeColumnDecorator } from '@ioc:Adonis/Lucid/Orm' +import { LucidRow, LucidModel, DateTimeColumnDecorator } from '../../../adonis-typings/model.js' /** * The method to prepare the datetime column before persisting it's @@ -34,8 +34,10 @@ function prepareDateTimeColumn(value: any, attributeName: string, modelInstance: if (!value.isValid) { throw new Exception( `Invalid value for "${modelName}.${attributeName}". ${value.invalidReason}`, - 500, - 'E_INVALID_DATETIME_COLUMN_VALUE' + { + status: 500, + code: 'E_INVALID_DATETIME_COLUMN_VALUE', + } ) } @@ -48,8 +50,10 @@ function prepareDateTimeColumn(value: any, attributeName: string, modelInstance: */ throw new Exception( `The value for "${modelName}.${attributeName}" must be an instance of "luxon.DateTime"`, - 500, - 'E_INVALID_DATETIME_COLUMN_VALUE' + { + status: 500, + code: 'E_INVALID_DATETIME_COLUMN_VALUE', + } ) } @@ -84,8 +88,10 @@ function consumeDateTimeColumn(value: any, attributeName: string, modelInstance: const modelName = modelInstance.constructor.name throw new Exception( `Cannot format "${modelName}.${attributeName}" ${typeof value} value to an instance of "luxon.DateTime"`, - 500, - 'E_INVALID_DATETIME_COLUMN_VALUE' + { + status: 500, + code: 'E_INVALID_DATETIME_COLUMN_VALUE', + } ) } diff --git a/src/Orm/Decorators/index.ts b/src/orm/decorators/index.ts similarity index 82% rename from src/Orm/Decorators/index.ts rename to src/orm/decorators/index.ts index 2d6f955b..fb55847d 100644 --- a/src/Orm/Decorators/index.ts +++ b/src/orm/decorators/index.ts @@ -7,25 +7,25 @@ * file that was distributed with this source code. */ -/// - -import 'reflect-metadata' import { LucidModel, - HasOneDecorator, - HasManyDecorator, HooksDecorator, ColumnDecorator, ComputedDecorator, - BelongsToDecorator, DateColumnDecorator, - ManyToManyDecorator, DateTimeColumnDecorator, +} from '../../../adonis-typings/model.js' + +import { + HasOneDecorator, + HasManyDecorator, + BelongsToDecorator, + ManyToManyDecorator, HasManyThroughDecorator, -} from '@ioc:Adonis/Lucid/Orm' +} from '../../../adonis-typings/relations.js' -import { dateColumn } from './date' -import { dateTimeColumn } from './datetime' +import { dateColumn } from './date.js' +import { dateTimeColumn } from './date_time.js' /** * Define property on a model as a column. The decorator needs a @@ -134,13 +134,13 @@ export const hasManyThrough: HasManyThroughDecorator = ([relatedModel, throughMo export const beforeSave: HooksDecorator = () => { return function decorateAsHook(target, property) { target.boot() - target.before('save', target[property].bind(target)) + target.before('save', (target as any)[property].bind(target)) } } export const afterSave: HooksDecorator = () => { return function decorateAsColumn(target, property) { target.boot() - target.after('save', target[property].bind(target)) + target.after('save', (target as any)[property].bind(target)) } } @@ -150,13 +150,13 @@ export const afterSave: HooksDecorator = () => { export const beforeCreate: HooksDecorator = () => { return function decorateAsColumn(target, property) { target.boot() - target.before('create', target[property].bind(target)) + target.before('create', (target as any)[property].bind(target)) } } export const afterCreate: HooksDecorator = () => { return function decorateAsColumn(target, property) { target.boot() - target.after('create', target[property].bind(target)) + target.after('create', (target as any)[property].bind(target)) } } @@ -166,13 +166,13 @@ export const afterCreate: HooksDecorator = () => { export const beforeUpdate: HooksDecorator = () => { return function decorateAsColumn(target, property) { target.boot() - target.before('update', target[property].bind(target)) + target.before('update', (target as any)[property].bind(target)) } } export const afterUpdate: HooksDecorator = () => { return function decorateAsColumn(target, property) { target.boot() - target.after('update', target[property].bind(target)) + target.after('update', (target as any)[property].bind(target)) } } @@ -182,13 +182,13 @@ export const afterUpdate: HooksDecorator = () => { export const beforeDelete: HooksDecorator = () => { return function decorateAsColumn(target, property) { target.boot() - target.before('delete', target[property].bind(target)) + target.before('delete', (target as any)[property].bind(target)) } } export const afterDelete: HooksDecorator = () => { return function decorateAsColumn(target, property) { target.boot() - target.after('delete', target[property].bind(target)) + target.after('delete', (target as any)[property].bind(target)) } } @@ -198,13 +198,13 @@ export const afterDelete: HooksDecorator = () => { export const beforeFind: HooksDecorator = () => { return function decorateAsColumn(target, property) { target.boot() - target.before('find', target[property].bind(target)) + target.before('find', (target as any)[property].bind(target)) } } export const afterFind: HooksDecorator = () => { return function decorateAsColumn(target, property) { target.boot() - target.after('find', target[property].bind(target)) + target.after('find', (target as any)[property].bind(target)) } } @@ -214,13 +214,13 @@ export const afterFind: HooksDecorator = () => { export const beforeFetch: HooksDecorator = () => { return function decorateAsColumn(target, property) { target.boot() - target.before('fetch', target[property].bind(target)) + target.before('fetch', (target as any)[property].bind(target)) } } export const afterFetch: HooksDecorator = () => { return function decorateAsColumn(target, property) { target.boot() - target.after('fetch', target[property].bind(target)) + target.after('fetch', (target as any)[property].bind(target)) } } @@ -230,12 +230,12 @@ export const afterFetch: HooksDecorator = () => { export const beforePaginate: HooksDecorator = () => { return function decorateAsColumn(target, property) { target.boot() - target.before('paginate', target[property].bind(target)) + target.before('paginate', (target as any)[property].bind(target)) } } export const afterPaginate: HooksDecorator = () => { return function decorateAsColumn(target, property) { target.boot() - target.after('paginate', target[property].bind(target)) + target.after('paginate', (target as any)[property].bind(target)) } } diff --git a/src/Orm/ModelKeys/index.ts b/src/orm/model_keys/index.ts similarity index 70% rename from src/Orm/ModelKeys/index.ts rename to src/orm/model_keys/index.ts index 207a9844..94dcb20b 100644 --- a/src/Orm/ModelKeys/index.ts +++ b/src/orm/model_keys/index.ts @@ -7,7 +7,7 @@ * file that was distributed with this source code. */ -import { ModelKeysContract, ModelObject } from '@ioc:Adonis/Lucid/Orm' +import { ModelKeysContract, ModelObject } from '../../../adonis-typings/model.js' /** * Exposes the API to collect, get and resolve model keys @@ -18,15 +18,15 @@ export class ModelKeys implements ModelKeysContract { /** * Add a new key */ - public add(key: string, value: string) { + add(key: string, value: string) { this.keys[key] = value } /** * Get value for a given key */ - public get(key: string, defaultValue: string): string - public get(key: string, defaultValue?: string): string | undefined { + get(key: string, defaultValue: string): string + get(key: string, defaultValue?: string): string | undefined { return this.keys[key] || defaultValue } @@ -34,14 +34,14 @@ export class ModelKeys implements ModelKeysContract { * Resolve key, if unable to resolve, the key will be * returned as it is. */ - public resolve(key: string): string { + resolve(key: string): string { return this.get(key, key) } /** * Return all keys */ - public all() { + all() { return this.keys } } diff --git a/src/Orm/naming_strategies/snake_case.ts b/src/orm/naming_strategies/snake_case.ts similarity index 95% rename from src/Orm/naming_strategies/snake_case.ts rename to src/orm/naming_strategies/snake_case.ts index 4f671d6a..f5536636 100644 --- a/src/Orm/naming_strategies/snake_case.ts +++ b/src/orm/naming_strategies/snake_case.ts @@ -40,7 +40,7 @@ export class SnakeCaseNamingStrategy implements NamingStrategyContract { * The local key for a given model relationship */ relationLocalKey( - relation: ModelRelations['__opaque_type'], + relation: ModelRelations['__opaque_type'], model: LucidModel, relatedModel: LucidModel ): string { @@ -55,7 +55,7 @@ export class SnakeCaseNamingStrategy implements NamingStrategyContract { * The foreign key for a given model relationship */ relationForeignKey( - relation: ModelRelations['__opaque_type'], + relation: ModelRelations['__opaque_type'], model: LucidModel, relatedModel: LucidModel ): string { diff --git a/src/Orm/Paginator/index.ts b/src/orm/paginator/index.ts similarity index 68% rename from src/Orm/Paginator/index.ts rename to src/orm/paginator/index.ts index 49033056..e3f2e68f 100644 --- a/src/Orm/Paginator/index.ts +++ b/src/orm/paginator/index.ts @@ -7,10 +7,8 @@ * file that was distributed with this source code. */ -/// - -import { ModelPaginatorContract, CherryPick } from '@ioc:Adonis/Lucid/Orm' -import { SimplePaginator } from '../../Database/Paginator/SimplePaginator' +import { ModelPaginatorContract, CherryPick } from '../../../adonis-typings/model.js' +import { SimplePaginator } from '../../database/paginator/simple_paginator.js' /** * Model paginator extends the simple paginator and adds support for @@ -20,7 +18,7 @@ export class ModelPaginator extends SimplePaginator implements ModelPaginatorCon /** * Serialize models */ - public serialize(cherryPick?: CherryPick) { + serialize(cherryPick?: CherryPick) { return { meta: this.getMeta(), data: this.all().map((row) => row.serialize(cherryPick)), diff --git a/src/Orm/Preloader/index.ts b/src/orm/preloader/index.ts similarity index 85% rename from src/Orm/Preloader/index.ts rename to src/orm/preloader/index.ts index 7bfc69a2..e386635e 100644 --- a/src/Orm/Preloader/index.ts +++ b/src/orm/preloader/index.ts @@ -9,16 +9,15 @@ import { Exception } from '@poppinss/utils' +import { LucidRow, LucidModel, ModelObject } from '../../../adonis-typings/model.js' + import { - LucidRow, - LucidModel, - ModelObject, PreloaderContract, RelationshipsContract, RelationQueryBuilderContract, -} from '@ioc:Adonis/Lucid/Orm' +} from '../../../adonis-typings/relations.js' -import { QueryClientContract } from '@ioc:Adonis/Lucid/Database' +import { QueryClientContract } from '../../../adonis-typings/database.js' /** * Exposes the API to define and preload relationships in reference to @@ -38,7 +37,7 @@ export class Preloader implements PreloaderContract { */ private sideloaded: ModelObject = {} - private debugQueries: boolean + private debugQueries: boolean = false constructor(private model: LucidModel) {} @@ -108,13 +107,15 @@ export class Preloader implements PreloaderContract { /** * Define a relationship to preload */ - public load(name: any, callback?: any): this { + load(name: any, callback?: any): this { const relation = this.model.$getRelation(name) as RelationshipsContract if (!relation) { throw new Exception( `"${name}" is not defined as a relationship on "${this.model.name}" model`, - 500, - 'E_UNDEFINED_RELATIONSHIP' + { + status: 500, + code: 'E_UNDEFINED_RELATIONSHIP', + } ) } @@ -130,14 +131,14 @@ export class Preloader implements PreloaderContract { /** * Alias for "this.load" */ - public preload(name: any, callback?: any): this { + preload(name: any, callback?: any): this { return this.load(name, callback) } /** * Toggle query debugging */ - public debug(debug: boolean) { + debug(debug: boolean) { this.debugQueries = debug return this } @@ -146,7 +147,7 @@ export class Preloader implements PreloaderContract { * Define attributes to be passed to all the model instance as * sideloaded attributes */ - public sideload(values: ModelObject): this { + sideload(values: ModelObject): this { this.sideloaded = values return this } @@ -154,7 +155,7 @@ export class Preloader implements PreloaderContract { /** * Process of all the preloaded relationships for a single parent */ - public async processAllForOne(parent: LucidRow, client: QueryClientContract) { + async processAllForOne(parent: LucidRow, client: QueryClientContract) { await Promise.all( Object.keys(this.preloads).map((relationName) => { return this.processRelation(relationName, parent, client) @@ -165,7 +166,7 @@ export class Preloader implements PreloaderContract { /** * Process of all the preloaded relationships for many parents */ - public async processAllForMany(parent: LucidRow[], client: QueryClientContract) { + async processAllForMany(parent: LucidRow[], client: QueryClientContract) { if (!parent.length) { return } diff --git a/src/Orm/QueryBuilder/index.ts b/src/orm/query_builder/index.ts similarity index 76% rename from src/Orm/QueryBuilder/index.ts rename to src/orm/query_builder/index.ts index dc58d625..04d120ad 100644 --- a/src/Orm/QueryBuilder/index.ts +++ b/src/orm/query_builder/index.ts @@ -7,8 +7,6 @@ * file that was distributed with this source code. */ -/// - import { Knex } from 'knex' import { Exception } from '@poppinss/utils' @@ -16,26 +14,30 @@ import { LucidRow, LucidModel, ModelObject, - PreloaderContract, ModelAdapterOptions, - RelationshipsContract, ModelQueryBuilderContract, +} from '../../../adonis-typings/model.js' + +import { + PreloaderContract, + RelationshipsContract, RelationQueryBuilderContract, -} from '@ioc:Adonis/Lucid/Orm' +} from '../../../adonis-typings/relations.js' import { DialectContract, - DBQueryCallback, QueryClientContract, TransactionClientContract, -} from '@ioc:Adonis/Lucid/Database' +} from '../../../adonis-typings/database.js' -import { isObject } from '../../utils' -import { Preloader } from '../Preloader' -import { ModelPaginator } from '../Paginator' -import { QueryRunner } from '../../QueryRunner' -import { Chainable } from '../../Database/QueryBuilder/Chainable' -import { SimplePaginator } from '../../Database/Paginator/SimplePaginator' +import { DBQueryCallback, Dictionary, OneOrMany } from '../../../adonis-typings/querybuilder.js' + +import { isObject } from '../../utils/index.js' +import { Preloader } from '../preloader/index.js' +import { ModelPaginator } from '../paginator/index.js' +import { QueryRunner } from '../../query_runner/index.js' +import { Chainable } from '../../database/query_builder/chainable.js' +import { SimplePaginator } from '../../database/paginator/simple_paginator.js' /** * A wrapper to invoke scope methods on the query builder @@ -45,9 +47,9 @@ class ModelScopes { constructor(protected builder: ModelQueryBuilder) { return new Proxy(this, { get(target, key) { - if (typeof target.builder.model[key] === 'function') { + if (typeof (target.builder.model as any)[key] === 'function') { return (...args: any[]) => { - return target.builder.model[key](target.builder, ...args) + return (target.builder.model as any)[key](target.builder, ...args) } } @@ -66,7 +68,10 @@ class ModelScopes { * Database query builder exposes the API to construct and run queries for selecting, * updating and deleting records. */ -export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderContract { +export class ModelQueryBuilder + extends Chainable + implements ModelQueryBuilderContract +{ /** * Sideloaded attributes that will be passed to the model instances */ @@ -75,12 +80,12 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon /** * A copy of defined preloads on the model instance */ - protected preloader: PreloaderContract = new Preloader(this.model) + protected preloader: PreloaderContract /** * A custom callback to transform each model row */ - protected rowTransformerCallback: (row: LucidRow) => void + protected rowTransformerCallback?: (row: LucidRow) => void /** * Required by macroable @@ -110,7 +115,7 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon * Control whether to debug the query or not. The initial * value is inherited from the query client */ - protected debugQueries: boolean = this.client.debug + protected debugQueries: boolean /** * Self join counter, increments with every "withCount" @@ -121,16 +126,12 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon /** * Options that must be passed to all new model instances */ - public clientOptions: ModelAdapterOptions = { - client: this.client, - connection: this.client.connectionName, - profiler: this.client.profiler, - } + clientOptions: ModelAdapterOptions /** * Whether or not query is a subquery for `.where` callback */ - public isChildQuery = false + isChildQuery = false constructor( builder: Knex.QueryBuilder, @@ -151,10 +152,17 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon model.$keys.attributesToColumns.resolve.bind(model.$keys.attributesToColumns) ) + this.preloader = new Preloader(this.model) + this.debugQueries = this.client.debug + this.clientOptions = { + client: this.client, + connection: this.client.connectionName, + } + /** * Assign table when not already assigned */ - if (!builder['_single'] || !builder['_single'].table) { + if (!(builder as any)['_single'] || !(builder as any)['_single'].table) { builder.table(model.table) } } @@ -165,7 +173,7 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon private async execQuery() { this.applyWhere() - const isWriteQuery = ['update', 'del', 'insert'].includes(this.knexQuery['_method']) + const isWriteQuery = ['update', 'del', 'insert'].includes((this.knexQuery as any)['_method']) const queryData = Object.assign(this.getQueryData(), this.customReporterData) const rows = await new QueryRunner(this.client, this.debugQueries, queryData).run( this.knexQuery @@ -281,8 +289,8 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon * and hence we need to prepend the `NOT` keyword manually */ boolean === 'orNot' || boolean === 'not' - ? this[rawMethod](`not (${sql}) ${operator} (?)`, bindings.concat([value])) - : this[rawMethod](`(${sql}) ${operator} (?)`, bindings.concat([value])) + ? (this as any)[rawMethod](`not (${sql}) ${operator} (?)`, bindings.concat([value])) + : (this as any)[rawMethod](`(${sql}) ${operator} (?)`, bindings.concat([value])) return this } @@ -290,8 +298,7 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon /** * Use where exists when no operator and value is defined */ - this[existsMethod](subQuery.prepare()) - + ;(this as any)[existsMethod](subQuery.prepare()) return this } @@ -320,8 +327,10 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon if (!relation) { throw new Exception( `"${name}" is not defined as a relationship on "${this.model.name}" model`, - 500, - 'E_UNDEFINED_RELATIONSHIP' + { + status: 500, + code: 'E_UNDEFINED_RELATIONSHIP', + } ) } @@ -333,7 +342,7 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon * Define custom reporter data. It will be merged with * the existing data */ - public reporterData(data: any) { + reporterData(data: any) { this.customReporterData = data return this } @@ -341,7 +350,7 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon /** * Define a custom callback to transform rows */ - public rowTransformer(callback: (row: LucidRow) => void): this { + rowTransformer(callback: (row: LucidRow) => void): this { this.rowTransformerCallback = callback return this } @@ -349,7 +358,7 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon /** * Clone the current query builder */ - public clone(): ModelQueryBuilder { + clone(): ModelQueryBuilderContract { const clonedQuery = new ModelQueryBuilder(this.knexQuery.clone(), this.model, this.client) this.applyQueryFlags(clonedQuery) @@ -358,13 +367,13 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon clonedQuery.reporterData(this.customReporterData) this.rowTransformerCallback && this.rowTransformer(this.rowTransformerCallback) - return clonedQuery + return clonedQuery as ModelQueryBuilderContract } /** * Define returning columns */ - public returning(columns: any): this { + returning(columns: any): this { if (this.client.dialect.supportsReturningStatement) { columns = Array.isArray(columns) ? columns.map((column) => this.resolveKey(column)) @@ -379,7 +388,7 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon /** * Define a query to constraint to be defined when condition is truthy */ - public ifDialect( + ifDialect( dialects: DialectContract['name'] | DialectContract['name'][], matchCallback: (query: this) => any, noMatchCallback?: (query: this) => any @@ -398,7 +407,7 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon /** * Define a query to constraint to be defined when condition is falsy */ - public unlessDialect( + unlessDialect( dialects: DialectContract['name'] | DialectContract['name'][], matchCallback: (query: this) => any, noMatchCallback?: (query: this) => any @@ -418,7 +427,7 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon * Applies the query scopes on the current query builder * instance */ - public withScopes(callback: (scopes: any) => void): this { + withScopes(callback: (scopes: any) => void): this { this.scopesWrapper = this.scopesWrapper || new ModelScopes(this) callback(this.scopesWrapper) return this @@ -428,14 +437,14 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon * Applies the query scopes on the current query builder * instance */ - public apply(callback: (scopes: any) => void): this { + apply(callback: (scopes: any) => void): this { return this.withScopes(callback) } /** * Define a custom preloader instance for preloading relationships */ - public usePreloader(preloader: PreloaderContract) { + usePreloader(preloader: PreloaderContract) { this.preloader = preloader return this } @@ -443,7 +452,7 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon /** * Set sideloaded properties to be passed to the model instance */ - public sideload(value: ModelObject) { + sideload(value: ModelObject) { this.sideloaded = value return this } @@ -452,17 +461,18 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon * Fetch and return first results from the results set. This method * will implicitly set a `limit` on the query */ - public async first(): Promise { - const isFetchCall = this.wrapResultsToModelInstances && this.knexQuery['_method'] === 'select' + async first(): Promise { + const isFetchCall = + this.wrapResultsToModelInstances && (this.knexQuery as any)['_method'] === 'select' if (isFetchCall) { - await this.model.$hooks.exec('before', 'find', this) + await this.model.$hooks.runner('before:find').run(this) } const result = await this.limit(1).execQuery() if (result[0] && isFetchCall) { - await this.model.$hooks.exec('after', 'find', result[0]) + await this.model.$hooks.runner('after:find').run(result[0]) } return result[0] || null @@ -472,10 +482,10 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon * Fetch and return first results from the results set. This method * will implicitly set a `limit` on the query */ - public async firstOrFail(): Promise { + async firstOrFail(): Promise { const row = await this.first() if (!row) { - throw new Exception('Row not found', 404, 'E_ROW_NOT_FOUND') + throw new Exception('Row not found', { status: 404, code: 'E_ROW_NOT_FOUND' }) } return row @@ -484,7 +494,7 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon /** * Load aggregate value as a subquery for a relationship */ - public withAggregate(relationName: any, userCallback: any): this { + withAggregate(relationName: any, userCallback: any): this { const subQuery = this.getRelationship(relationName).subQuery(this.client) subQuery.selfJoinCounter = this.joinCounter @@ -530,7 +540,7 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon /** * Get count of a relationship along side the main query results */ - public withCount(relationName: any, userCallback?: any): this { + withCount(relationName: any, userCallback?: any): this { this.withAggregate(relationName, (subQuery: RelationQueryBuilderContract) => { if (typeof userCallback === 'function') { userCallback(subQuery) @@ -557,96 +567,91 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon /** * Add where constraint using the relationship */ - public whereHas(relationName: any, callback: any, operator?: string, value?: any): this { + whereHas(relationName: any, callback: any, operator?: string, value?: any): this { return this.addWhereHas(relationName, 'and', operator, value, callback) } /** * Add or where constraint using the relationship */ - public orWhereHas(relationName: any, callback: any, operator?: string, value?: any): this { + orWhereHas(relationName: any, callback: any, operator?: string, value?: any): this { return this.addWhereHas(relationName, 'or', operator, value, callback) } /** * Alias of [[whereHas]] */ - public andWhereHas(relationName: any, callback: any, operator?: string, value?: any): this { + andWhereHas(relationName: any, callback: any, operator?: string, value?: any): this { return this.addWhereHas(relationName, 'and', operator, value, callback) } /** * Add where not constraint using the relationship */ - public whereDoesntHave(relationName: any, callback: any, operator?: string, value?: any): this { + whereDoesntHave(relationName: any, callback: any, operator?: string, value?: any): this { return this.addWhereHas(relationName, 'not', operator, value, callback) } /** * Add or where not constraint using the relationship */ - public orWhereDoesntHave(relationName: any, callback: any, operator?: string, value?: any): this { + orWhereDoesntHave(relationName: any, callback: any, operator?: string, value?: any): this { return this.addWhereHas(relationName, 'orNot', operator, value, callback) } /** * Alias of [[whereDoesntHave]] */ - public andWhereDoesntHave( - relationName: any, - callback: any, - operator?: string, - value?: any - ): this { + andWhereDoesntHave(relationName: any, callback: any, operator?: string, value?: any): this { return this.addWhereHas(relationName, 'not', operator, value, callback) } /** * Add where constraint using the relationship */ - public has(relationName: any, operator?: string, value?: any): this { + has(relationName: any, operator?: string, value?: any): this { return this.addWhereHas(relationName, 'and', operator, value) } /** * Add or where constraint using the relationship */ - public orHas(relationName: any, operator?: string, value?: any): this { + orHas(relationName: any, operator?: string, value?: any): this { return this.addWhereHas(relationName, 'or', operator, value) } /** * Alias of [[has]] */ - public andHas(relationName: any, operator?: string, value?: any): this { + andHas(relationName: any, operator?: string, value?: any): this { return this.addWhereHas(relationName, 'and', operator, value) } /** * Add where not constraint using the relationship */ - public doesntHave(relationName: any, operator?: string, value?: any): this { + doesntHave(relationName: any, operator?: string, value?: any): this { return this.addWhereHas(relationName, 'not', operator, value) } /** * Add or where not constraint using the relationship */ - public orDoesntHave(relationName: any, operator?: string, value?: any): this { + orDoesntHave(relationName: any, operator?: string, value?: any): this { return this.addWhereHas(relationName, 'orNot', operator, value) } /** * Alias of [[doesntHave]] */ - public andDoesntHave(relationName: any, operator?: string, value?: any): this { + andDoesntHave(relationName: any, operator?: string, value?: any): this { return this.addWhereHas(relationName, 'not', operator, value) } /** * Define a relationship to be preloaded */ - public preload(relationName: any, userCallback?: any): this { + preload(relationName: any, userCallback?: any): this { this.preloader.load(relationName, userCallback) return this } @@ -655,7 +660,7 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon * Perform update by incrementing value for a given column. Increments * can be clubbed with `update` as well */ - public increment(column: any, counter?: any): any { + increment(column: any, counter?: any): any { this.ensureCanPerformWrites() this.knexQuery.increment(this.resolveKey(column, true), counter) return this @@ -665,7 +670,7 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon * Perform update by decrementing value for a given column. Decrements * can be clubbed with `update` as well */ - public decrement(column: any, counter?: any): any { + decrement(column: any, counter?: any): any { this.ensureCanPerformWrites() this.knexQuery.decrement(this.resolveKey(column, true), counter) return this @@ -674,7 +679,20 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon /** * Perform update */ - public update(column: any, value?: any, returning?: string[]): any { + update( + values: Dictionary, + returning?: OneOrMany + ): ModelQueryBuilderContract + update( + column: string, + value: any, + returning?: OneOrMany + ): ModelQueryBuilderContract + update( + column: string | Dictionary, + value?: any | OneOrMany, + returning?: OneOrMany + ): ModelQueryBuilderContract { this.ensureCanPerformWrites() if (value === undefined && returning === undefined) { @@ -691,7 +709,7 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon /** * Delete rows under the current query */ - public del(): any { + del(): any { this.ensureCanPerformWrites() this.knexQuery.del() return this @@ -700,14 +718,14 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon /** * Alias for [[del]] */ - public delete(): any { + delete(): any { return this.del() } /** * Turn on/off debugging for this query */ - public debug(debug: boolean): this { + debug(debug: boolean): this { this.debugQueries = debug return this } @@ -715,7 +733,7 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon /** * Define query timeout */ - public timeout(time: number, options?: { cancel: boolean }): this { + timeout(time: number, options?: { cancel: boolean }): this { this.knexQuery['timeout'](time, options) return this } @@ -723,7 +741,7 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon /** * Returns SQL query as a string */ - public toQuery(): string { + toQuery(): string { this.applyWhere() return this.knexQuery.toQuery() } @@ -731,7 +749,7 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon /** * Run query inside the given transaction */ - public useTransaction(transaction: TransactionClientContract) { + useTransaction(transaction: TransactionClientContract) { this.knexQuery.transacting(transaction.knexClient) return this } @@ -739,17 +757,18 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon /** * Executes the query */ - public async exec(): Promise { - const isFetchCall = this.wrapResultsToModelInstances && this.knexQuery['_method'] === 'select' + async exec(): Promise { + const isFetchCall = + this.wrapResultsToModelInstances && (this.knexQuery as any)['_method'] === 'select' if (isFetchCall) { - await this.model.$hooks.exec('before', 'fetch', this) + await this.model.$hooks.runner('before:fetch').run(this) } const result = await this.execQuery() if (isFetchCall) { - await this.model.$hooks.exec('after', 'fetch', result) + await this.model.$hooks.runner('after:fetch').run(result) } return result @@ -758,8 +777,9 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon /** * Paginate through rows inside a given table */ - public async paginate(page: number, perPage: number = 20): Promise { - const isFetchCall = this.wrapResultsToModelInstances && this.knexQuery['_method'] === 'select' + async paginate(page: number, perPage: number = 20): Promise { + const isFetchCall = + this.wrapResultsToModelInstances && (this.knexQuery as any)['_method'] === 'select' /** * Cast to number @@ -773,15 +793,15 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon .clearOffset() .clearSelect() .count('* as total') - .pojo() + .pojo<{ total: number }>() /** * We pass both the counts query and the main query to the * paginate hook */ if (isFetchCall) { - await this.model.$hooks.exec('before', 'paginate', [countQuery, this]) - await this.model.$hooks.exec('before', 'fetch', this) + await this.model.$hooks.runner('before:paginate').run([countQuery, this]) + await this.model.$hooks.runner('before:fetch').run(this) } const aggregateResult = await countQuery.exec() @@ -799,8 +819,8 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon paginator.namingStrategy = this.model.namingStrategy if (isFetchCall) { - await this.model.$hooks.exec('after', 'paginate', paginator) - await this.model.$hooks.exec('after', 'fetch', results) + await this.model.$hooks.runner('after:paginate').run(paginator) + await this.model.$hooks.runner('after:fetch').run(results) } return paginator @@ -809,7 +829,7 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon /** * Get sql representation of the query */ - public toSQL(): Knex.Sql { + toSQL(): Knex.Sql { this.applyWhere() return this.knexQuery.toSQL() } @@ -818,7 +838,7 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon * Get rows back as a plain javascript object and not an array * of model instances */ - public pojo(): this { + pojo(): this { this.wrapResultsToModelInstances = false return this } @@ -826,28 +846,28 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon /** * Implementation of `then` for the promise API */ - public then(resolve: any, reject?: any): any { + then(resolve: any, reject?: any): any { return this.exec().then(resolve, reject) } /** * Implementation of `catch` for the promise API */ - public catch(reject: any): any { + catch(reject: any): any { return this.exec().catch(reject) } /** * Implementation of `finally` for the promise API */ - public finally(fullfilled: any) { + finally(fullfilled: any) { return this.exec().finally(fullfilled) } /** * Required when Promises are extended */ - public get [Symbol.toStringTag]() { + get [Symbol.toStringTag]() { return this.constructor.name } } diff --git a/src/Orm/Relations/AggregatesLoader/LazyLoad.ts b/src/orm/relations/aggregates_loader/lazy_load.ts similarity index 84% rename from src/Orm/Relations/AggregatesLoader/LazyLoad.ts rename to src/orm/relations/aggregates_loader/lazy_load.ts index 01901e0a..46b2b49e 100644 --- a/src/Orm/Relations/AggregatesLoader/LazyLoad.ts +++ b/src/orm/relations/aggregates_loader/lazy_load.ts @@ -12,7 +12,7 @@ import { LucidModel, ModelQueryBuilderContract, LazyLoadAggregatesContract, -} from '@ioc:Adonis/Lucid/Orm' +} from '../../../../adonis-typings/model.js' /** * An implementation for lazy loading model relationship aggregates @@ -42,7 +42,7 @@ export class LazyLoadAggregates /** * Load aggregate of relationship */ - public loadAggregate(relationName: any, userCallback?: any) { + loadAggregate(relationName: any, userCallback?: any) { this.query.withAggregate(relationName, userCallback) return this } @@ -50,7 +50,7 @@ export class LazyLoadAggregates /** * Load count of relationship */ - public loadCount(relationName: any, userCallback?: any) { + loadCount(relationName: any, userCallback?: any) { this.query.withCount(relationName, userCallback) return this } @@ -58,7 +58,7 @@ export class LazyLoadAggregates /** * Execute query */ - public async exec() { + async exec() { const result = await this.query.pojo().first() if (!result) { return @@ -73,28 +73,28 @@ export class LazyLoadAggregates /** * Implementation of `then` for the promise API */ - public then(resolve: any, reject?: any): any { + then(resolve: any, reject?: any): any { return this.exec().then(resolve, reject) } /** * Implementation of `catch` for the promise API */ - public catch(reject: any): any { + catch(reject: any): any { return this.exec().catch(reject) } /** * Implementation of `finally` for the promise API */ - public finally(fullfilled: any) { + finally(fullfilled: any) { return this.exec().finally(fullfilled) } /** * Required when Promises are extended */ - public get [Symbol.toStringTag]() { + get [Symbol.toStringTag]() { return this.constructor.name } } diff --git a/src/Orm/Relations/Base/QueryBuilder.ts b/src/orm/relations/base/query_builder.ts similarity index 86% rename from src/Orm/Relations/Base/QueryBuilder.ts rename to src/orm/relations/base/query_builder.ts index aa67b68f..dc6fa834 100644 --- a/src/Orm/Relations/Base/QueryBuilder.ts +++ b/src/orm/relations/base/query_builder.ts @@ -8,16 +8,18 @@ */ import { Knex } from 'knex' -import { DBQueryCallback, QueryClientContract } from '@ioc:Adonis/Lucid/Database' +import { DBQueryCallback } from '../../../../adonis-typings/querybuilder.js' +import { QueryClientContract } from '../../../../adonis-typings/database.js' import { LucidRow, LucidModel, - RelationshipsContract, ModelQueryBuilderContract, +} from '../../../../adonis-typings/model.js' +import { + RelationshipsContract, RelationQueryBuilderContract, -} from '@ioc:Adonis/Lucid/Orm' - -import { ModelQueryBuilder } from '../../QueryBuilder' +} from '../../../../adonis-typings/relations.js' +import { ModelQueryBuilder } from '../../query_builder/index.js' /** * Base query builder for ORM Relationships @@ -40,21 +42,21 @@ export abstract class BaseQueryBuilder /** * Is query a relationship query obtained using `related('relation').query()` */ - public get isRelatedQuery(): true { + get isRelatedQuery(): true { return true } /** * Is query a relationship query obtained using `related('relation').subQuery()` */ - public get isRelatedSubQuery(): false { + get isRelatedSubQuery(): false { return false } /** * Is query a relationship query obtained using one of the preload methods. */ - public isRelatedPreloadQuery: boolean = false + isRelatedPreloadQuery: boolean = false constructor( builder: Knex.QueryBuilder, @@ -69,7 +71,9 @@ export abstract class BaseQueryBuilder * Returns the selected columns */ protected getSelectedColumns(): undefined | { grouping: 'columns'; value: any[] } { - return this.knexQuery['_statements'].find(({ grouping }) => grouping === 'columns') + return (this.knexQuery as any)['_statements'].find( + ({ grouping }: any) => grouping === 'columns' + ) } /** @@ -113,7 +117,7 @@ export abstract class BaseQueryBuilder * raising descriptive errors */ protected queryAction(): string { - let action = this.knexQuery['_method'] + let action = (this.knexQuery as any)['_method'] if (action === 'del') { action = 'delete' } @@ -128,7 +132,7 @@ export abstract class BaseQueryBuilder /** * Selects the relation keys. Invoked by the preloader */ - public selectRelationKeys(): this { + selectRelationKeys(): this { const columns = this.getSelectedColumns() /** @@ -155,7 +159,7 @@ export abstract class BaseQueryBuilder /** * Define the group limit */ - public groupLimit(limit: number): this { + groupLimit(limit: number): this { this.groupConstraints.limit = limit return this } @@ -163,7 +167,7 @@ export abstract class BaseQueryBuilder /** * Define the group limit */ - public groupOrderBy(column: string, direction?: 'asc' | 'desc'): this { + groupOrderBy(column: string, direction?: 'asc' | 'desc'): this { this.groupConstraints.orderBy = { column, direction } return this } @@ -171,7 +175,7 @@ export abstract class BaseQueryBuilder /** * Get query sql */ - public toSQL() { + toSQL() { this.applyConstraints() if (this.isRelatedPreloadQuery) { return this.groupConstraints.limit ? this.getGroupLimitQuery().toSQL() : super.toSQL() @@ -195,7 +199,7 @@ export abstract class BaseQueryBuilder * Apply constraints before fetching the first * row */ - public first() { + first() { this.applyConstraints() return super.first() } @@ -203,7 +207,7 @@ export abstract class BaseQueryBuilder /** * Execute query */ - public exec() { + exec() { this.applyConstraints() if (this.isRelatedPreloadQuery) { return this.groupConstraints.limit ? this.getGroupLimitQuery().exec() : super.exec() diff --git a/src/Orm/Relations/Base/SubQueryBuilder.ts b/src/orm/relations/base/sub_query_builder.ts similarity index 78% rename from src/Orm/Relations/Base/SubQueryBuilder.ts rename to src/orm/relations/base/sub_query_builder.ts index 90f5d8fb..1ba1a4b7 100644 --- a/src/Orm/Relations/Base/SubQueryBuilder.ts +++ b/src/orm/relations/base/sub_query_builder.ts @@ -8,14 +8,14 @@ */ import { Knex } from 'knex' -import { QueryClientContract, DBQueryCallback } from '@ioc:Adonis/Lucid/Database' +import { DBQueryCallback } from '../../../../adonis-typings/querybuilder.js' +import { QueryClientContract } from '../../../../adonis-typings/database.js' +import { LucidModel } from '../../../../adonis-typings/model.js' import { - LucidModel, - RelationshipsContract, RelationSubQueryBuilderContract, -} from '@ioc:Adonis/Lucid/Orm' - -import { ModelQueryBuilder } from '../../QueryBuilder' + RelationshipsContract, +} from '../../../../adonis-typings/relations.js' +import { ModelQueryBuilder } from '../../query_builder/index.js' /** * Base query builder for ORM Relationships @@ -28,33 +28,33 @@ export abstract class BaseSubQueryBuilder * The counter for the self join alias. Usually will be set by * the consumer */ - public selfJoinCounter: number = 0 + selfJoinCounter: number = 0 /** * Alias for the self join table */ - public get selfJoinAlias(): string { + get selfJoinAlias(): string { return `adonis_temp_${this.selfJoinCounter}` } /** * Is query a relationship query obtained using `related('relation').query()` */ - public get isRelatedQuery(): false { + get isRelatedQuery(): false { return false } /** * Is query a relationship query obtained using `related('relation').subQuery()` */ - public get isRelatedSubQuery(): true { + get isRelatedSubQuery(): true { return true } /** * Is query a relationship query obtained using one of the preload methods. */ - public get isRelatedPreloadQuery(): false { + get isRelatedPreloadQuery(): false { return false } @@ -71,7 +71,9 @@ export abstract class BaseSubQueryBuilder * Returns the selected columns */ protected getSelectedColumns(): undefined | { grouping: 'columns'; value: any[] } { - return this.knexQuery['_statements'].find(({ grouping }) => grouping === 'columns') + return (this.knexQuery as any)['_statements'].find( + ({ grouping }: any) => grouping === 'columns' + ) } /** @@ -88,7 +90,7 @@ export abstract class BaseSubQueryBuilder /** * Selects the relation keys. Invoked by the preloader */ - public selectRelationKeys(): this { + selectRelationKeys(): this { const columns = this.getSelectedColumns() /** @@ -115,7 +117,7 @@ export abstract class BaseSubQueryBuilder /** * Get query sql */ - public toSQL() { + toSQL() { this.prepare() return super.toSQL() } @@ -123,7 +125,7 @@ export abstract class BaseSubQueryBuilder /** * prepare */ - public prepare() { + prepare() { this.applyConstraints() return this } @@ -132,27 +134,27 @@ export abstract class BaseSubQueryBuilder * Executing subqueries is not allowed. It is disabled in static types, but * in case someone by-pass typescript checks to invoke it */ - public exec(): any { + exec(): any { throw new Error('Cannot execute relationship subqueries') } - public paginate(): any { + paginate(): any { throw new Error('Cannot execute relationship subqueries') } - public update(): any { + update(): any { throw new Error('Cannot execute relationship subqueries') } - public del(): any { + del(): any { throw new Error('Cannot execute relationship subqueries') } - public first(): any { + first(): any { throw new Error('Cannot execute relationship subqueries') } - public firstOrFail(): any { + firstOrFail(): any { throw new Error('Cannot execute relationship subqueries') } } diff --git a/src/Orm/Relations/BelongsTo/index.ts b/src/orm/relations/belongs_to/index.ts similarity index 68% rename from src/Orm/Relations/BelongsTo/index.ts rename to src/orm/relations/belongs_to/index.ts index 3a673fba..aa259142 100644 --- a/src/Orm/Relations/BelongsTo/index.ts +++ b/src/orm/relations/belongs_to/index.ts @@ -7,20 +7,19 @@ * file that was distributed with this source code. */ -import { QueryClientContract, OneOrMany } from '@ioc:Adonis/Lucid/Database' +import { QueryClientContract } from '../../../../adonis-typings/database.js' +import { OneOrMany } from '../../../../adonis-typings/querybuilder.js' +import { LucidRow, LucidModel, ModelObject } from '../../../../adonis-typings/model.js' import { - LucidRow, - LucidModel, - ModelObject, RelationOptions, BelongsToRelationContract, BelongsTo as ModelBelongsTo, -} from '@ioc:Adonis/Lucid/Orm' +} from '../../../../adonis-typings/relations.js' -import { KeysExtractor } from '../KeysExtractor' -import { BelongsToQueryClient } from './QueryClient' -import { ensureRelationIsBooted, getValue } from '../../../utils' +import { KeysExtractor } from '../keys_extractor.js' +import { BelongsToQueryClient } from './query_client.js' +import { ensureRelationIsBooted, getValue } from '../../../utils/index.js' /** * Manages loading and persisting belongs to relationship @@ -29,49 +28,52 @@ export class BelongsTo implements BelongsToRelationContract LucidModel, - private options: RelationOptions>, + private options: RelationOptions>, public model: LucidModel - ) {} + ) { + this.onQueryHook = this.options.onQuery + this.serializeAs = + this.options.serializeAs === undefined ? this.relationName : this.options.serializeAs + } /** * Clone relationship instance */ - public clone(parent: LucidModel): any { + clone(parent: LucidModel): any { return new BelongsTo(this.relationName, this.relatedModel, { ...this.options }, parent) } @@ -81,7 +83,8 @@ export class BelongsTo implements BelongsToRelationContract { @@ -184,7 +187,7 @@ export class BelongsTo implements BelongsToRelationContract, client: QueryClientContract): any { + eagerQuery(parent: OneOrMany, client: QueryClientContract): any { ensureRelationIsBooted(this) return BelongsToQueryClient.eagerQuery(client, this, parent) } @@ -200,15 +203,19 @@ export class BelongsTo implements BelongsToRelationContract['subQuery']> { ensureRelationIsBooted(this) - return BelongsToQueryClient.subQuery(client, this) + return BelongsToQueryClient.subQuery(client, this) as unknown as ReturnType< + BelongsToRelationContract['subQuery'] + > } /** * Hydrates values object for persistance. */ - public hydrateForPersistance(parent: LucidRow, related: ModelObject | LucidRow) { - parent[this.foreignKey] = getValue(related, this.localKey, this, 'associate') + hydrateForPersistance(parent: LucidRow, related: ModelObject | LucidRow) { + ;(parent as any)[this.foreignKey] = getValue(related, this.localKey, this, 'associate') } } diff --git a/src/Orm/Relations/BelongsTo/QueryBuilder.ts b/src/orm/relations/belongs_to/query_builder.ts similarity index 85% rename from src/Orm/Relations/BelongsTo/QueryBuilder.ts rename to src/orm/relations/belongs_to/query_builder.ts index e4e90e64..1e489782 100644 --- a/src/Orm/Relations/BelongsTo/QueryBuilder.ts +++ b/src/orm/relations/belongs_to/query_builder.ts @@ -9,12 +9,12 @@ import { Knex } from 'knex' import { Exception } from '@poppinss/utils' -import { LucidRow } from '@ioc:Adonis/Lucid/Orm' -import { QueryClientContract } from '@ioc:Adonis/Lucid/Database' +import { LucidRow } from '../../../../adonis-typings/model.js' +import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { BelongsTo } from './index' -import { unique } from '../../../utils' -import { BaseQueryBuilder } from '../Base/QueryBuilder' +import { BelongsTo } from './index.js' +import { unique } from '../../../utils/index.js' +import { BaseQueryBuilder } from '../base/query_builder.js' /** * Extends the model query builder for executing queries in scope @@ -57,7 +57,7 @@ export class BelongsToQueryBuilder extends BaseQueryBuilder { `Cannot preload "${relationName}", value of "${modelName}.${foreignKey}" is undefined.`, 'Make sure to set "null" as the default value for foreign keys', ].join(' '), - 500 + { status: 500 } ) } @@ -96,7 +96,7 @@ export class BelongsToQueryBuilder extends BaseQueryBuilder { */ if (Array.isArray(this.parent)) { const foreignKeyValues = this.parent - .map((model) => model[this.relation.foreignKey]) + .map((model) => (model as any)[this.relation.foreignKey]) .filter((foreignKeyValue) => { if (foreignKeyValue === undefined) { this.raiseMissingForeignKey() @@ -111,11 +111,14 @@ export class BelongsToQueryBuilder extends BaseQueryBuilder { /** * Query constraints */ - if (this.parent[this.relation.foreignKey] === undefined) { + if ((this.parent as any)[this.relation.foreignKey] === undefined) { this.raiseMissingForeignKey() } - this.wrapExisting().where(this.relation.localKey, this.parent[this.relation.foreignKey]) + this.wrapExisting().where( + this.relation.localKey, + (this.parent as any)[this.relation.foreignKey] + ) /** * Do not add limit when updating or deleting @@ -130,7 +133,7 @@ export class BelongsToQueryBuilder extends BaseQueryBuilder { /** * Clones the current query */ - public clone() { + clone() { const clonedQuery = new BelongsToQueryBuilder( this.knexQuery.clone(), this.client, @@ -151,14 +154,14 @@ export class BelongsToQueryBuilder extends BaseQueryBuilder { /** * Dis-allow belongsTo pagination */ - public paginate(): Promise { + paginate(): Promise { throw new Error(`Cannot paginate a belongsTo relationship "(${this.relation.relationName})"`) } /** * Dis-allow belongsTo group query limit */ - public getGroupLimitQuery(): never { + getGroupLimitQuery(): never { throw new Error( `Cannot apply groupLimit or groupOrderBy on a belongsTo relationship "(${this.relation.relationName})"` ) diff --git a/src/Orm/Relations/BelongsTo/QueryClient.ts b/src/orm/relations/belongs_to/query_client.ts similarity index 65% rename from src/Orm/Relations/BelongsTo/QueryClient.ts rename to src/orm/relations/belongs_to/query_client.ts index a92f9ac6..e0df17da 100644 --- a/src/Orm/Relations/BelongsTo/QueryClient.ts +++ b/src/orm/relations/belongs_to/query_client.ts @@ -7,13 +7,15 @@ * file that was distributed with this source code. */ -import { QueryClientContract, OneOrMany } from '@ioc:Adonis/Lucid/Database' -import { LucidModel, LucidRow, BelongsToClientContract } from '@ioc:Adonis/Lucid/Orm' +import { OneOrMany } from '../../../../adonis-typings/querybuilder.js' +import { QueryClientContract } from '../../../../adonis-typings/database.js' +import { LucidModel, LucidRow } from '../../../../adonis-typings/model.js' +import { BelongsToClientContract } from '../../../../adonis-typings/relations.js' -import { BelongsTo } from './index' -import { managedTransaction } from '../../../utils' -import { BelongsToQueryBuilder } from './QueryBuilder' -import { BelongsToSubQueryBuilder } from './SubQueryBuilder' +import { BelongsTo } from './index.js' +import { managedTransaction } from '../../../utils/index.js' +import { BelongsToQueryBuilder } from './query_builder.js' +import { BelongsToSubQueryBuilder } from './sub_query_builder.js' /** * Query client for executing queries in scope to the belongsTo relationship. @@ -28,7 +30,7 @@ export class BelongsToQueryClient implements BelongsToClientContract) { + static query(client: QueryClientContract, relation: BelongsTo, rows: OneOrMany) { const query = new BelongsToQueryBuilder(client.knexQuery(), client, rows, relation) typeof relation.onQueryHook === 'function' && relation.onQueryHook(query) @@ -38,11 +40,7 @@ export class BelongsToQueryClient implements BelongsToClientContract - ) { + static eagerQuery(client: QueryClientContract, relation: BelongsTo, rows: OneOrMany) { const query = new BelongsToQueryBuilder(client.knexQuery(), client, rows, relation) query.isRelatedPreloadQuery = true @@ -53,9 +51,8 @@ export class BelongsToQueryClient implements BelongsToClientContract { related.$trx = trx await related.save() @@ -84,8 +81,8 @@ export class BelongsToQueryClient implements BelongsToClientContract /** * The relationship name */ - public readonly type = 'hasMany' + readonly type = 'hasMany' /** * Whether or not the relationship instance has been * booted */ - public booted: boolean = false + booted: boolean = false /** * The key name for serializing the relationship */ - public serializeAs = - this.options.serializeAs === undefined ? this.relationName : this.options.serializeAs + serializeAs /** * Local key is reference to the primary key in the self table * @note: Available after boot is invoked */ - public localKey: string - public localKeyColumName: string + declare localKey: string + declare localKeyColumName: string /** * Foreign key is reference to the foreign key in the related table * @note: Available after boot is invoked */ - public foreignKey: string - public foreignKeyColumName: string + declare foreignKey: string + declare foreignKeyColumName: string /** * Reference to the onQuery hook defined by the user */ - public onQueryHook = this.options.onQuery + onQueryHook constructor( public relationName: string, public relatedModel: () => LucidModel, - private options: RelationOptions>, + private options: RelationOptions>, public model: LucidModel - ) {} + ) { + this.serializeAs = + this.options.serializeAs === undefined ? this.relationName : this.options.serializeAs + this.onQueryHook = this.options.onQuery + } /** * Returns a boolean saving related row belongs to the parent * row or not. */ private isRelatedRow(parent: LucidRow, related: LucidRow) { - return parent[this.localKey] !== undefined && related[this.foreignKey] === parent[this.localKey] + return ( + (parent as any)[this.localKey] !== undefined && + (related as any)[this.foreignKey] === (parent as any)[this.localKey] + ) } /** * Clone relationship instance */ - public clone(parent: LucidModel): any { + clone(parent: LucidModel): any { return new HasMany(this.relationName, this.relatedModel, { ...this.options }, parent) } @@ -88,7 +94,7 @@ export class HasMany implements HasManyRelationContract * Boot the relationship and ensure that all keys are in * place for queries to do their job. */ - public boot() { + boot() { if (this.booted) { return } @@ -146,7 +152,7 @@ export class HasMany implements HasManyRelationContract /** * Set related model instances */ - public setRelated(parent: LucidRow, related: LucidRow[]): void { + setRelated(parent: LucidRow, related: LucidRow[]): void { ensureRelationIsBooted(this) parent.$setRelated(this.relationName, related) } @@ -154,7 +160,7 @@ export class HasMany implements HasManyRelationContract /** * Push related model instance(s) */ - public pushRelated(parent: LucidRow, related: LucidRow | LucidRow[]): void { + pushRelated(parent: LucidRow, related: LucidRow | LucidRow[]): void { ensureRelationIsBooted(this) parent.$pushRelated(this.relationName, related) } @@ -163,7 +169,7 @@ export class HasMany implements HasManyRelationContract * Finds and set the related model instances next to the parent * models. */ - public setRelatedForMany(parent: LucidRow[], related: LucidRow[]): void { + setRelatedForMany(parent: LucidRow[], related: LucidRow[]): void { ensureRelationIsBooted(this) parent.forEach((parentModel) => { @@ -177,7 +183,7 @@ export class HasMany implements HasManyRelationContract /** * Returns an instance of query client for invoking queries */ - public client(parent: LucidRow, client: QueryClientContract): any { + client(parent: LucidRow, client: QueryClientContract): any { ensureRelationIsBooted(this) return new HasManyQueryClient(this, parent, client) } @@ -185,7 +191,7 @@ export class HasMany implements HasManyRelationContract /** * Returns an instance of the eager query */ - public eagerQuery(parent: OneOrMany, client: QueryClientContract) { + eagerQuery(parent: OneOrMany, client: QueryClientContract) { ensureRelationIsBooted(this) return HasManyQueryClient.eagerQuery(client, this, parent) } @@ -193,7 +199,7 @@ export class HasMany implements HasManyRelationContract /** * Returns instance of query builder */ - public subQuery(client: QueryClientContract) { + subQuery(client: QueryClientContract) { ensureRelationIsBooted(this) return HasManyQueryClient.subQuery(client, this) } @@ -201,7 +207,7 @@ export class HasMany implements HasManyRelationContract /** * Hydrates values object for persistance. */ - public hydrateForPersistance(parent: LucidRow, values: ModelObject | LucidRow) { - values[this.foreignKey] = getValue(parent, this.localKey, this, 'persist') + hydrateForPersistance(parent: LucidRow, values: ModelObject | LucidRow) { + ;(values as any)[this.foreignKey] = getValue(parent, this.localKey, this, 'persist') } } diff --git a/src/Orm/Relations/HasMany/QueryBuilder.ts b/src/orm/relations/has_many/query_builder.ts similarity index 89% rename from src/Orm/Relations/HasMany/QueryBuilder.ts rename to src/orm/relations/has_many/query_builder.ts index 07c95faa..9045c823 100644 --- a/src/Orm/Relations/HasMany/QueryBuilder.ts +++ b/src/orm/relations/has_many/query_builder.ts @@ -8,12 +8,13 @@ */ import { Knex } from 'knex' -import { QueryClientContract } from '@ioc:Adonis/Lucid/Database' -import { LucidRow, LucidModel, HasManyQueryBuilderContract } from '@ioc:Adonis/Lucid/Orm' +import { QueryClientContract } from '../../../../adonis-typings/database.js' +import { LucidRow, LucidModel } from '../../../../adonis-typings/model.js' +import { HasManyQueryBuilderContract } from '../../../../adonis-typings/relations.js' -import { HasMany } from './index' -import { getValue, unique } from '../../../utils' -import { BaseQueryBuilder } from '../Base/QueryBuilder' +import { HasMany } from './index.js' +import { getValue, unique } from '../../../utils/index.js' +import { BaseQueryBuilder } from '../base/query_builder.js' /** * Extends the model query builder for executing queries in scope @@ -63,7 +64,7 @@ export class HasManyQueryBuilder /** * Clones the current query */ - public clone() { + clone() { const clonedQuery = new HasManyQueryBuilder( this.knexQuery.clone(), this.client, @@ -119,7 +120,7 @@ export class HasManyQueryBuilder * Same as standard model query builder paginate method. But ensures that * it is not invoked during eagerloading */ - public paginate(page: number, perPage: number = 20) { + paginate(page: number, perPage: number = 20) { if (this.isRelatedPreloadQuery) { throw new Error(`Cannot paginate relationship "${this.relation.relationName}" during preload`) } @@ -131,7 +132,7 @@ export class HasManyQueryBuilder /** * Returns the group limit query */ - public getGroupLimitQuery() { + getGroupLimitQuery() { const { direction, column } = this.groupConstraints.orderBy || { column: this.resolveKey(this.relation.relatedModel().primaryKey), direction: 'desc', diff --git a/src/Orm/Relations/HasMany/QueryClient.ts b/src/orm/relations/has_many/query_client.ts similarity index 83% rename from src/Orm/Relations/HasMany/QueryClient.ts rename to src/orm/relations/has_many/query_client.ts index ace17154..a52ce9c7 100644 --- a/src/Orm/Relations/HasMany/QueryClient.ts +++ b/src/orm/relations/has_many/query_client.ts @@ -7,19 +7,20 @@ * file that was distributed with this source code. */ -import { QueryClientContract, OneOrMany } from '@ioc:Adonis/Lucid/Database' +import { QueryClientContract } from '../../../../adonis-typings/database.js' +import { OneOrMany } from '../../../../adonis-typings/querybuilder.js' import { LucidRow, LucidModel, ModelObject, - HasManyClientContract, ModelAssignOptions, -} from '@ioc:Adonis/Lucid/Orm' +} from '../../../../adonis-typings/model.js' +import { HasManyClientContract } from '../../../../adonis-typings/relations.js' -import { HasMany } from './index' -import { managedTransaction } from '../../../utils' -import { HasManyQueryBuilder } from './QueryBuilder' -import { HasManySubQueryBuilder } from './SubQueryBuilder' +import { HasMany } from './index.js' +import { managedTransaction } from '../../../utils/index.js' +import { HasManyQueryBuilder } from './query_builder.js' +import { HasManySubQueryBuilder } from './sub_query_builder.js' /** * Query client for executing queries in scope to the defined @@ -35,7 +36,7 @@ export class HasManyQueryClient implements HasManyClientContract - ) { + static eagerQuery(client: QueryClientContract, relation: HasMany, rows: OneOrMany) { const query = new HasManyQueryBuilder(client.knexQuery(), client, rows, relation) query.isRelatedPreloadQuery = true @@ -59,7 +56,7 @@ export class HasManyQueryClient implements HasManyClientContract { this.parent.$trx = trx await this.parent.save() @@ -90,7 +87,7 @@ export class HasManyQueryClient implements HasManyClientContract { @@ -108,7 +105,7 @@ export class HasManyQueryClient implements HasManyClientContract { + async create(values: ModelObject, options?: ModelAssignOptions): Promise { return managedTransaction(this.parent.$trx || this.client, async (trx) => { this.parent.$trx = trx await this.parent.save() @@ -122,10 +119,7 @@ export class HasManyQueryClient implements HasManyClientContract { + async createMany(values: ModelObject[], options?: ModelAssignOptions): Promise { const parent = this.parent return managedTransaction(this.parent.$trx || this.client, async (trx) => { @@ -145,7 +139,7 @@ export class HasManyQueryClient implements HasManyClientContract { - public type = 'hasManyThrough' as const + type = 'hasManyThrough' as const - public booted: boolean = false + booted: boolean = false + serializeAs + throughModel - public serializeAs = - this.options.serializeAs === undefined ? this.relationName : this.options.serializeAs - - public throughModel = this.options.throughModel + /** + * Reference to the onQuery hook defined by the user + */ + onQueryHook /** * Available after boot is invoked */ - public localKey: string - public localKeyColumnName: string + declare localKey: string + declare localKeyColumnName: string /** * This exists on the through model */ - public foreignKey: string - public foreignKeyColumnName: string + declare foreignKey: string + declare foreignKeyColumnName: string /** * This exists on the through model */ - public throughLocalKey: string - public throughLocalKeyColumnName: string + declare throughLocalKey: string + declare throughLocalKeyColumnName: string /** * This exists on the related model */ - public throughForeignKey: string - public throughForeignKeyColumnName: string - - /** - * Reference to the onQuery hook defined by the user - */ - public onQueryHook = this.options.onQuery + declare throughForeignKey: string + declare throughForeignKeyColumnName: string constructor( public relationName: string, public relatedModel: () => LucidModel, - private options: ThroughRelationOptions> & { + private options: ThroughRelationOptions< + LucidModel, + LucidModel, + ModelHasManyThrough + > & { throughModel: () => LucidModel }, public model: LucidModel - ) {} + ) { + this.onQueryHook = this.options.onQuery + this.throughModel = this.options.throughModel + this.serializeAs = + this.options.serializeAs === undefined ? this.relationName : this.options.serializeAs + } /** * Clone relationship instance */ - public clone(parent: LucidModel): any { + clone(parent: LucidModel): any { return new HasManyThrough(this.relationName, this.relatedModel, { ...this.options }, parent) } /** * Returns the alias for the through key */ - public throughAlias(key: string): string { + throughAlias(key: string): string { return `through_${key}` } @@ -89,7 +95,7 @@ export class HasManyThrough implements HasManyThroughRelationContract { - const value = parentModel[this.localKey] + const value = (parentModel as any)[this.localKey] return value !== undefined && relatedModel.$extras[$foreignCastAsKeyAlias] === value }) ) @@ -212,7 +218,7 @@ export class HasManyThrough implements HasManyThroughRelationContract, client: QueryClientContract) { + eagerQuery(parent: OneOrMany, client: QueryClientContract) { ensureRelationIsBooted(this) return HasManyThroughClient.eagerQuery(client, this, parent) } @@ -228,7 +234,7 @@ export class HasManyThrough implements HasManyThroughRelationContract - ) { + static query(client: QueryClientContract, relation: HasManyThrough, rows: OneOrMany) { const query = new HasManyThroughQueryBuilder(client.knexQuery(), client, rows, relation) typeof relation.onQueryHook === 'function' && relation.onQueryHook(query) return query @@ -43,7 +41,7 @@ export class HasManyThroughClient /** * Generate a related eager query builder */ - public static eagerQuery( + static eagerQuery( client: QueryClientContract, relation: HasManyThrough, rows: OneOrMany @@ -58,7 +56,7 @@ export class HasManyThroughClient /** * Returns an instance of the sub query */ - public static subQuery(client: QueryClientContract, relation: HasManyThrough) { + static subQuery(client: QueryClientContract, relation: HasManyThrough) { const query = new HasManyThroughSubQueryBuilder(client.knexQuery(), client, relation) typeof relation.onQueryHook === 'function' && relation.onQueryHook(query) @@ -68,7 +66,7 @@ export class HasManyThroughClient /** * Returns an instance of has many through query builder */ - public query(): any { + query(): any { return HasManyThroughClient.query(this.client, this.relation, this.parent) } } diff --git a/src/Orm/Relations/HasManyThrough/SubQueryBuilder.ts b/src/orm/relations/has_many_through/sub_query_builder.ts similarity index 84% rename from src/Orm/Relations/HasManyThrough/SubQueryBuilder.ts rename to src/orm/relations/has_many_through/sub_query_builder.ts index 8a61354c..69ddffc2 100644 --- a/src/Orm/Relations/HasManyThrough/SubQueryBuilder.ts +++ b/src/orm/relations/has_many_through/sub_query_builder.ts @@ -8,11 +8,12 @@ */ import { Knex } from 'knex' -import { QueryClientContract } from '@ioc:Adonis/Lucid/Database' -import { LucidModel, RelationSubQueryBuilderContract } from '@ioc:Adonis/Lucid/Orm' +import { QueryClientContract } from '../../../../adonis-typings/database.js' +import { LucidModel } from '../../../../adonis-typings/model.js' +import { RelationSubQueryBuilderContract } from '../../../../adonis-typings/relations.js' -import { HasManyThrough } from './index' -import { BaseSubQueryBuilder } from '../Base/SubQueryBuilder' +import { HasManyThrough } from './index.js' +import { BaseSubQueryBuilder } from '../base/sub_query_builder.js' /** * Extends the model query builder for executing queries in scope @@ -31,14 +32,14 @@ export class HasManyThroughSubQueryBuilder /** * Reference to the related table */ - private relatedTable = this.relation.relatedModel().table + private relatedTable /** * Reference to the through table */ - private throughTable = this.relation.throughModel().table + private throughTable - private hasSelfRelation = this.relatedTable === this.relation.model.table + private hasSelfRelation constructor( builder: Knex.QueryBuilder, @@ -53,6 +54,9 @@ export class HasManyThroughSubQueryBuilder subQuery.applyWhere() } }) + this.relatedTable = this.relation.relatedModel().table + this.throughTable = this.relation.throughModel().table + this.hasSelfRelation = this.relatedTable === this.relation.model.table } /** @@ -99,7 +103,7 @@ export class HasManyThroughSubQueryBuilder /** * Select keys from the related table */ - public select(...args: any): this { + select(...args: any): this { let columns = args if (Array.isArray(args[0])) { columns = args[0] @@ -142,7 +146,7 @@ export class HasManyThroughSubQueryBuilder /** * Clones the current query */ - public clone() { + clone() { const clonedQuery = new HasManyThroughSubQueryBuilder( this.knexQuery.clone(), this.client, diff --git a/src/Orm/Relations/HasOne/index.ts b/src/orm/relations/has_one/index.ts similarity index 69% rename from src/Orm/Relations/HasOne/index.ts rename to src/orm/relations/has_one/index.ts index 17e10b97..cb0ac3bf 100644 --- a/src/Orm/Relations/HasOne/index.ts +++ b/src/orm/relations/has_one/index.ts @@ -7,61 +7,62 @@ * file that was distributed with this source code. */ -import { QueryClientContract, OneOrMany } from '@ioc:Adonis/Lucid/Database' +import { OneOrMany } from '../../../../adonis-typings/querybuilder.js' +import { QueryClientContract } from '../../../../adonis-typings/database.js' +import { LucidRow, LucidModel, ModelObject } from '../../../../adonis-typings/model.js' import { - LucidRow, - LucidModel, - ModelObject, RelationOptions, HasOne as ModelHasOne, HasOneRelationContract, -} from '@ioc:Adonis/Lucid/Orm' +} from '../../../../adonis-typings/relations.js' -import { KeysExtractor } from '../KeysExtractor' -import { HasOneQueryClient } from './QueryClient' -import { ensureRelationIsBooted, getValue } from '../../../utils' +import { KeysExtractor } from '../keys_extractor.js' +import { HasOneQueryClient } from './query_client.js' +import { ensureRelationIsBooted, getValue } from '../../../utils/index.js' /** * Manages loading and persisting has one relationship */ export class HasOne implements HasOneRelationContract { - public readonly type = 'hasOne' + readonly type = 'hasOne' - public booted: boolean = false - - public serializeAs = - this.options.serializeAs === undefined ? this.relationName : this.options.serializeAs + booted: boolean = false + serializeAs /** * Local key is reference to the primary key in the self table * @note: Available after boot is invoked */ - public localKey: string - public localKeyColumName: string + declare localKey: string + declare localKeyColumName: string /** * Foreign key is reference to the foreign key in the related table * @note: Available after boot is invoked */ - public foreignKey: string - public foreignKeyColumName: string + declare foreignKey: string + declare foreignKeyColumName: string /** * Reference to the onQuery hook defined by the user */ - public onQueryHook = this.options.onQuery + onQueryHook constructor( public relationName: string, public relatedModel: () => LucidModel, - private options: RelationOptions>, + private options: RelationOptions>, public model: LucidModel - ) {} + ) { + this.onQueryHook = this.options.onQuery + this.serializeAs = + this.options.serializeAs === undefined ? this.relationName : this.options.serializeAs + } /** * Clone relationship instance */ - public clone(parent: LucidModel): any { + clone(parent: LucidModel): any { return new HasOne(this.relationName, this.relatedModel, { ...this.options }, parent) } @@ -69,7 +70,7 @@ export class HasOne implements HasOneRelationContract { * Boot the relationship and ensure that all keys are in * place for queries to do their job. */ - public boot() { + boot() { if (this.booted) { return } @@ -127,7 +128,7 @@ export class HasOne implements HasOneRelationContract { /** * Set related model instance */ - public setRelated(parent: LucidRow, related: LucidRow | null): void { + setRelated(parent: LucidRow, related: LucidRow | null): void { ensureRelationIsBooted(this) if (related === undefined) { return @@ -139,7 +140,7 @@ export class HasOne implements HasOneRelationContract { /** * Push related model instance */ - public pushRelated(parent: LucidRow, related: LucidRow | null): void { + pushRelated(parent: LucidRow, related: LucidRow | null): void { ensureRelationIsBooted(this) if (related === undefined) { @@ -153,13 +154,13 @@ export class HasOne implements HasOneRelationContract { * Finds and set the related model instance next to the parent * models. */ - public setRelatedForMany(parent: LucidRow[], related: LucidRow[]): void { + setRelatedForMany(parent: LucidRow[], related: LucidRow[]): void { ensureRelationIsBooted(this) parent.forEach((parentModel) => { const match = related.find((relatedModel) => { - const value = parentModel[this.localKey] - return value !== undefined && value === relatedModel[this.foreignKey] + const value = (parentModel as any)[this.localKey] + return value !== undefined && value === (relatedModel as any)[this.foreignKey] }) this.setRelated(parentModel, match || null) @@ -169,7 +170,7 @@ export class HasOne implements HasOneRelationContract { /** * Returns an instance of query client for invoking queries */ - public client(parent: LucidRow, client: QueryClientContract): any { + client(parent: LucidRow, client: QueryClientContract): any { ensureRelationIsBooted(this) return new HasOneQueryClient(this, parent, client) } @@ -177,7 +178,7 @@ export class HasOne implements HasOneRelationContract { /** * Returns eager query instance */ - public eagerQuery(parent: OneOrMany, client: QueryClientContract): any { + eagerQuery(parent: OneOrMany, client: QueryClientContract): any { ensureRelationIsBooted(this) return HasOneQueryClient.eagerQuery(client, this, parent) } @@ -185,7 +186,7 @@ export class HasOne implements HasOneRelationContract { /** * Returns instance of query builder */ - public subQuery(client: QueryClientContract) { + subQuery(client: QueryClientContract) { ensureRelationIsBooted(this) return HasOneQueryClient.subQuery(client, this) } @@ -193,7 +194,7 @@ export class HasOne implements HasOneRelationContract { /** * Hydrates values object for persistance. */ - public hydrateForPersistance(parent: LucidRow, values: ModelObject | LucidRow) { - values[this.foreignKey] = getValue(parent, this.localKey, this, 'persist') + hydrateForPersistance(parent: LucidRow, values: ModelObject | LucidRow) { + ;(values as any)[this.foreignKey] = getValue(parent, this.localKey, this, 'persist') } } diff --git a/src/Orm/Relations/HasOne/QueryBuilder.ts b/src/orm/relations/has_one/query_builder.ts similarity index 89% rename from src/Orm/Relations/HasOne/QueryBuilder.ts rename to src/orm/relations/has_one/query_builder.ts index a2e961c5..0b811048 100644 --- a/src/Orm/Relations/HasOne/QueryBuilder.ts +++ b/src/orm/relations/has_one/query_builder.ts @@ -8,12 +8,12 @@ */ import { Knex } from 'knex' -import { LucidRow } from '@ioc:Adonis/Lucid/Orm' -import { QueryClientContract } from '@ioc:Adonis/Lucid/Database' +import { LucidRow } from '../../../../adonis-typings/model.js' +import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { HasOne } from './index' -import { getValue, unique } from '../../../utils' -import { BaseQueryBuilder } from '../Base/QueryBuilder' +import { HasOne } from './index.js' +import { getValue, unique } from '../../../utils/index.js' +import { BaseQueryBuilder } from '../base/query_builder.js' /** * Extends the model query builder for executing queries in scope @@ -60,7 +60,7 @@ export class HasOneQueryBuilder extends BaseQueryBuilder { /** * Clones the current query */ - public clone() { + clone() { const clonedQuery = new HasOneQueryBuilder( this.knexQuery.clone(), this.client, @@ -121,14 +121,14 @@ export class HasOneQueryBuilder extends BaseQueryBuilder { /** * Dis-allow hasOne pagination */ - public paginate(): Promise { + paginate(): Promise { throw new Error(`Cannot paginate a hasOne relationship "(${this.relation.relationName})"`) } /** * Dis-allow hasOne group query limit */ - public getGroupLimitQuery(): never { + getGroupLimitQuery(): never { throw new Error( `Cannot apply groupLimit or groupOrderBy on hasOne relationship "(${this.relation.relationName})"` ) diff --git a/src/Orm/Relations/HasOne/QueryClient.ts b/src/orm/relations/has_one/query_client.ts similarity index 78% rename from src/Orm/Relations/HasOne/QueryClient.ts rename to src/orm/relations/has_one/query_client.ts index b199de30..6463c08c 100644 --- a/src/Orm/Relations/HasOne/QueryClient.ts +++ b/src/orm/relations/has_one/query_client.ts @@ -7,19 +7,20 @@ * file that was distributed with this source code. */ -import { QueryClientContract, OneOrMany } from '@ioc:Adonis/Lucid/Database' +import { QueryClientContract } from '../../../../adonis-typings/database.js' +import { OneOrMany } from '../../../../adonis-typings/querybuilder.js' import { ModelObject, LucidModel, LucidRow, - HasOneClientContract, ModelAssignOptions, -} from '@ioc:Adonis/Lucid/Orm' +} from '../../../../adonis-typings/model.js' +import { HasOneClientContract } from '../../../../adonis-typings/relations.js' -import { HasOne } from './index' -import { managedTransaction } from '../../../utils' -import { HasOneQueryBuilder } from './QueryBuilder' -import { HasOneSubQueryBuilder } from './SubQueryBuilder' +import { HasOne } from './index.js' +import { managedTransaction } from '../../../utils/index.js' +import { HasOneQueryBuilder } from './query_builder.js' +import { HasOneSubQueryBuilder } from './sub_query_builder.js' /** * Query client for executing queries in scope to the defined @@ -35,7 +36,7 @@ export class HasOneQueryClient implements HasOneClientContract) { + static query(client: QueryClientContract, relation: HasOne, rows: OneOrMany) { const query = new HasOneQueryBuilder(client.knexQuery(), client, rows, relation) typeof relation.onQueryHook === 'function' && relation.onQueryHook(query) @@ -45,11 +46,7 @@ export class HasOneQueryClient implements HasOneClientContract - ) { + static eagerQuery(client: QueryClientContract, relation: HasOne, rows: OneOrMany) { const query = new HasOneQueryBuilder(client.knexQuery(), client, rows, relation) query.isRelatedPreloadQuery = true @@ -60,7 +57,7 @@ export class HasOneQueryClient implements HasOneClientContract { this.parent.$trx = trx await this.parent.save() @@ -91,7 +88,7 @@ export class HasOneQueryClient implements HasOneClientContract { + async create(values: ModelObject, options?: ModelAssignOptions): Promise { const parent = this.parent return managedTransaction(this.parent.$trx || this.client, async (trx) => { @@ -107,7 +104,7 @@ export class HasOneQueryClient implements HasOneClientContract { - public type = 'manyToMany' as const + type = 'manyToMany' as const - public booted: boolean = false - - public serializeAs = - this.options.serializeAs === undefined ? this.relationName : this.options.serializeAs + booted: boolean = false + serializeAs /** * Available after boot is invoked */ - public localKey: string - public localKeyColumnName: string + declare localKey: string + declare localKeyColumnName: string - public relatedKey: string - public relatedKeyColumnName: string + declare relatedKey: string + declare relatedKeyColumnName: string - public pivotForeignKey: string - public pivotRelatedForeignKey: string + declare pivotForeignKey: string + declare pivotRelatedForeignKey: string - public pivotTable: string - public pivotColumns: string[] = this.options.pivotColumns || [] + declare pivotTable: string + declare pivotColumns: string[] - public pivotCreatedAtTimestamp: string | undefined - public pivotUpdatedAtTimestamp: string | undefined + declare pivotCreatedAtTimestamp: string | undefined + declare pivotUpdatedAtTimestamp: string | undefined /** * Timestamp columns for the pivot table */ - public get pivotTimestamps(): string[] { + get pivotTimestamps(): string[] { const timestamps: string[] = [] this.pivotCreatedAtTimestamp && timestamps.push(this.pivotCreatedAtTimestamp) this.pivotUpdatedAtTimestamp && timestamps.push(this.pivotUpdatedAtTimestamp) @@ -63,7 +60,7 @@ export class ManyToMany implements ManyToManyRelationContract LucidModel, private options: ManyToManyRelationOptions>, public model: LucidModel - ) {} + ) { + this.serializeAs = + this.options.serializeAs === undefined ? this.relationName : this.options.serializeAs + this.pivotColumns = this.options.pivotColumns || [] + this.onQueryHook = this.options.onQuery + } /** * Returns the alias for the pivot key */ - public pivotAlias(key: string): string { + pivotAlias(key: string): string { return `pivot_${key}` } /** * Clone relationship instance */ - public clone(parent: LucidModel): any { + clone(parent: LucidModel): any { return new ManyToMany(this.relationName, this.relatedModel, { ...this.options }, parent) } @@ -132,7 +134,7 @@ export class ManyToMany implements ManyToManyRelationContract { - const value = parentModel[this.localKey] + const value = (parentModel as any)[this.localKey] return value !== undefined && relatedModel.$extras[pivotForeignKeyAlias] === value }) ) @@ -265,7 +267,7 @@ export class ManyToMany implements ManyToManyRelationContract['subQuery']> { ensureRelationIsBooted(this) - return ManyToManyQueryClient.subQuery(client, this) + return ManyToManyQueryClient.subQuery(client, this) as unknown as ReturnType< + ManyToManyRelationContract['subQuery'] + > } /** * Returns key-value pair for the pivot table in relation to the parent model */ - public getPivotPair(parent: LucidRow): [string, number | string] { + getPivotPair(parent: LucidRow): [string, number | string] { return [this.pivotForeignKey, getValue(parent, this.localKey, this, 'persist')] } /** * Returns key-value pair for the pivot table in relation to the related model */ - public getPivotRelatedPair(related: LucidRow): [string, number | string] { + getPivotRelatedPair(related: LucidRow): [string, number | string] { return [this.pivotRelatedForeignKey, getValue(related, this.relatedKey, this, 'persist')] } } diff --git a/src/Orm/Relations/ManyToMany/PivotHelpers.ts b/src/orm/relations/many_to_many/pivot_helpers.ts similarity index 76% rename from src/Orm/Relations/ManyToMany/PivotHelpers.ts rename to src/orm/relations/many_to_many/pivot_helpers.ts index 74e8d5d6..7885a230 100644 --- a/src/Orm/Relations/ManyToMany/PivotHelpers.ts +++ b/src/orm/relations/many_to_many/pivot_helpers.ts @@ -18,8 +18,8 @@ | */ -import { ManyToManyQueryBuilder } from './QueryBuilder' -import { ManyToManySubQueryBuilder } from './SubQueryBuilder' +import { ManyToManyQueryBuilder } from './query_builder.js' +import { ManyToManySubQueryBuilder } from './sub_query_builder.js' export class PivotHelpers { constructor( @@ -30,7 +30,7 @@ export class PivotHelpers { /** * Prefixes the pivot table name to a column */ - public prefixPivotTable(column: string) { + prefixPivotTable(column: string) { if (column.includes('.')) { return column } @@ -45,13 +45,8 @@ export class PivotHelpers { /** * Adds a where pivot condition to the query */ - public wherePivot( - varition: 'or' | 'and' | 'not' | 'orNot', - key: any, - operator?: any, - value?: any - ) { - let method: string = 'where' + wherePivot(varition: 'or' | 'and' | 'not' | 'orNot', key: any, operator?: any, value?: any) { + let method: keyof (ManyToManyQueryBuilder | ManyToManySubQueryBuilder) = 'where' switch (varition) { case 'or': @@ -76,8 +71,8 @@ export class PivotHelpers { /** * Adds a where pivot condition to the query */ - public whereNullPivot(varition: 'or' | 'and' | 'not' | 'orNot', key: string) { - let method: string = 'whereNull' + whereNullPivot(varition: 'or' | 'and' | 'not' | 'orNot', key: string) { + let method: keyof (ManyToManyQueryBuilder | ManyToManySubQueryBuilder) = 'whereNull' switch (varition) { case 'or': @@ -90,14 +85,14 @@ export class PivotHelpers { method = 'orWhereNotNull' } - return this.query[method](this.prefixPivotTable(key)) + return (this.query as any)[method](this.prefixPivotTable(key)) } /** * Adds a where pivot condition to the query */ - public whereInPivot(varition: 'or' | 'and' | 'not' | 'orNot', key: any, value?: any) { - let method: string = 'whereIn' + whereInPivot(varition: 'or' | 'and' | 'not' | 'orNot', key: any, value: any) { + let method: keyof (ManyToManyQueryBuilder | ManyToManySubQueryBuilder) = 'whereIn' switch (varition) { case 'or': @@ -114,17 +109,13 @@ export class PivotHelpers { ? key.map((one) => this.prefixPivotTable(one)) : this.prefixPivotTable(key) - if (value !== undefined) { - return this.query[method](key, value) - } else { - return this.query[method](key) - } + return this.query[method](key, value) } /** * Select pivot columns */ - public pivotColumns(columns: string[]): this { + pivotColumns(columns: string[]): this { this.query.knexQuery.select( columns.map((column) => { if (this.aliasSelectColumns) { diff --git a/src/Orm/Relations/ManyToMany/QueryBuilder.ts b/src/orm/relations/many_to_many/query_builder.ts similarity index 85% rename from src/Orm/Relations/ManyToMany/QueryBuilder.ts rename to src/orm/relations/many_to_many/query_builder.ts index 6a0afae6..eed15152 100644 --- a/src/Orm/Relations/ManyToMany/QueryBuilder.ts +++ b/src/orm/relations/many_to_many/query_builder.ts @@ -9,13 +9,14 @@ import { Knex } from 'knex' import { DateTime } from 'luxon' -import { QueryClientContract } from '@ioc:Adonis/Lucid/Database' -import { LucidModel, LucidRow, ManyToManyQueryBuilderContract } from '@ioc:Adonis/Lucid/Orm' +import { QueryClientContract } from '../../../../adonis-typings/database.js' +import { LucidModel, LucidRow } from '../../../../adonis-typings/model.js' +import { ManyToManyQueryBuilderContract } from '../../../../adonis-typings/relations.js' -import { ManyToMany } from './index' -import { PivotHelpers } from './PivotHelpers' -import { getValue, unique } from '../../../utils' -import { BaseQueryBuilder } from '../Base/QueryBuilder' +import { ManyToMany } from './index.js' +import { PivotHelpers } from './pivot_helpers.js' +import { getValue, unique } from '../../../utils/index.js' +import { BaseQueryBuilder } from '../base/query_builder.js' /** * Extends the model query builder for executing queries in scope @@ -26,7 +27,7 @@ export class ManyToManyQueryBuilder implements ManyToManyQueryBuilderContract { private pivotQuery = false - private relatedTable = this.relation.relatedModel().table + private relatedTable private pivotHelpers = new PivotHelpers(this, true) protected cherryPickingKeys: boolean = false @@ -36,10 +37,11 @@ export class ManyToManyQueryBuilder * A boolean to know if query build targets only the pivot * table or not */ - public get isPivotOnlyQuery() { + get isPivotOnlyQuery() { return this.pivotQuery } - public set isPivotOnlyQuery(pivotOnly) { + + set isPivotOnlyQuery(pivotOnly) { this.pivotQuery = pivotOnly /** @@ -71,6 +73,7 @@ export class ManyToManyQueryBuilder subQuery.applyWhere() } }) + this.relatedTable = this.relation.relatedModel().table } /** @@ -200,7 +203,7 @@ export class ManyToManyQueryBuilder /** * Select keys from the related table */ - public select(...args: any[]): this { + select(...args: any[]): this { let columns = args if (Array.isArray(args[0])) { columns = args[0] @@ -214,7 +217,7 @@ export class ManyToManyQueryBuilder /** * Add where clause with pivot table prefix */ - public wherePivot(key: any, operator?: any, value?: any): this { + wherePivot(key: any, operator?: any, value?: any): this { this.pivotHelpers.wherePivot('and', key, operator, value) return this } @@ -222,7 +225,7 @@ export class ManyToManyQueryBuilder /** * Add or where clause with pivot table prefix */ - public orWherePivot(key: any, operator?: any, value?: any): this { + orWherePivot(key: any, operator?: any, value?: any): this { this.pivotHelpers.wherePivot('or', key, operator, value) return this } @@ -230,14 +233,14 @@ export class ManyToManyQueryBuilder /** * Alias for wherePivot */ - public andWherePivot(key: any, operator?: any, value?: any): this { + andWherePivot(key: any, operator?: any, value?: any): this { return this.wherePivot(key, operator, value) } /** * Add where not pivot */ - public whereNotPivot(key: any, operator?: any, value?: any): this { + whereNotPivot(key: any, operator?: any, value?: any): this { this.pivotHelpers.wherePivot('not', key, operator, value) return this } @@ -245,7 +248,7 @@ export class ManyToManyQueryBuilder /** * Add or where not pivot */ - public orWhereNotPivot(key: any, operator?: any, value?: any): this { + orWhereNotPivot(key: any, operator?: any, value?: any): this { this.pivotHelpers.wherePivot('orNot', key, operator, value) return this } @@ -253,14 +256,14 @@ export class ManyToManyQueryBuilder /** * Alias for `whereNotPivot` */ - public andWhereNotPivot(key: any, operator?: any, value?: any): this { + andWhereNotPivot(key: any, operator?: any, value?: any): this { return this.whereNotPivot(key, operator, value) } /** * Adds where in clause */ - public whereInPivot(key: any, value: any) { + whereInPivot(key: any, value: any) { this.pivotHelpers.whereInPivot('and', key, value) return this } @@ -268,7 +271,7 @@ export class ManyToManyQueryBuilder /** * Adds or where in clause */ - public orWhereInPivot(key: any, value: any) { + orWhereInPivot(key: any, value: any) { this.pivotHelpers.whereInPivot('or', key, value) return this } @@ -276,14 +279,14 @@ export class ManyToManyQueryBuilder /** * Alias from `whereInPivot` */ - public andWhereInPivot(key: any, value: any): this { + andWhereInPivot(key: any, value: any): this { return this.whereInPivot(key, value) } /** * Adds where not in clause */ - public whereNotInPivot(key: any, value: any) { + whereNotInPivot(key: any, value: any) { this.pivotHelpers.whereInPivot('not', key, value) return this } @@ -291,7 +294,7 @@ export class ManyToManyQueryBuilder /** * Adds or where not in clause */ - public orWhereNotInPivot(key: any, value: any) { + orWhereNotInPivot(key: any, value: any) { this.pivotHelpers.whereInPivot('orNot', key, value) return this } @@ -299,14 +302,14 @@ export class ManyToManyQueryBuilder /** * Alias from `whereNotInPivot` */ - public andWhereNotInPivot(key: any, value: any): this { + andWhereNotInPivot(key: any, value: any): this { return this.whereNotInPivot(key, value) } /** * Same as "whereNull", but for the pivot table only */ - public whereNullPivot(key: string): this { + whereNullPivot(key: string): this { this.pivotHelpers.whereNullPivot('and', key) return this } @@ -314,7 +317,7 @@ export class ManyToManyQueryBuilder /** * Same as "orWhereNull", but for the pivot table only */ - public orWhereNullPivot(key: string): this { + orWhereNullPivot(key: string): this { this.pivotHelpers.whereNullPivot('or', key) return this } @@ -322,14 +325,14 @@ export class ManyToManyQueryBuilder /** * Same as "andWhereNull", but for the pivot table only */ - public andWhereNullPivot(key: string): this { + andWhereNullPivot(key: string): this { return this.whereNullPivot(key) } /** * Same as "whereNotNull", but for the pivot table only */ - public whereNotNullPivot(key: string): this { + whereNotNullPivot(key: string): this { this.pivotHelpers.whereNullPivot('not', key) return this } @@ -337,7 +340,7 @@ export class ManyToManyQueryBuilder /** * Same as "orWhereNotNull", but for the pivot table only */ - public orWhereNotNullPivot(key: string): this { + orWhereNotNullPivot(key: string): this { this.pivotHelpers.whereNullPivot('orNot', key) return this } @@ -345,14 +348,14 @@ export class ManyToManyQueryBuilder /** * Same as "andWhereNotNull", but for the pivot table only */ - public andWhereNotNullPivot(key: string): this { + andWhereNotNullPivot(key: string): this { return this.whereNotNullPivot(key) } /** * Select pivot columns */ - public pivotColumns(columns: string[]): this { + pivotColumns(columns: string[]): this { this.pivotHelpers.pivotColumns(columns) return this } @@ -360,7 +363,7 @@ export class ManyToManyQueryBuilder /** * Clones query */ - public clone() { + clone() { this.applyConstraints() const clonedQuery = new ManyToManyQueryBuilder( this.knexQuery.clone(), @@ -384,7 +387,7 @@ export class ManyToManyQueryBuilder /** * Paginate through rows inside a given table */ - public paginate(page: number, perPage: number = 20) { + paginate(page: number, perPage: number = 20) { if (this.isRelatedPreloadQuery) { throw new Error(`Cannot paginate relationship "${this.relation.relationName}" during preload`) } @@ -393,7 +396,7 @@ export class ManyToManyQueryBuilder return super.paginate(page, perPage) } - public async exec() { + async exec() { const pivotTimestamps = this.relation.pivotTimestamps.map((timestamp) => this.relation.pivotAlias(timestamp) ) @@ -432,7 +435,7 @@ export class ManyToManyQueryBuilder /** * Returns the group limit query */ - public getGroupLimitQuery() { + getGroupLimitQuery() { const { direction, column } = this.groupConstraints.orderBy || { column: this.prefixRelatedTable(this.resolveKey(this.relation.relatedModel().primaryKey)), direction: 'desc', diff --git a/src/Orm/Relations/ManyToMany/QueryClient.ts b/src/orm/relations/many_to_many/query_client.ts similarity index 91% rename from src/Orm/Relations/ManyToMany/QueryClient.ts rename to src/orm/relations/many_to_many/query_client.ts index f29468dc..bd9c6794 100644 --- a/src/Orm/Relations/ManyToMany/QueryClient.ts +++ b/src/orm/relations/many_to_many/query_client.ts @@ -12,19 +12,19 @@ import { LucidModel, LucidRow, ModelObject, - ManyToManyClientContract, ModelAssignOptions, -} from '@ioc:Adonis/Lucid/Orm' +} from '../../../../adonis-typings/model.js' +import { ManyToManyClientContract } from '../../../../adonis-typings/relations.js' import { - OneOrMany, QueryClientContract, TransactionClientContract, -} from '@ioc:Adonis/Lucid/Database' +} from '../../../../adonis-typings/database.js' +import { OneOrMany } from '../../../../adonis-typings/querybuilder.js' -import { ManyToMany } from './index' -import { ManyToManyQueryBuilder } from './QueryBuilder' -import { ManyToManySubQueryBuilder } from './SubQueryBuilder' -import { managedTransaction, syncDiff } from '../../../utils' +import { ManyToMany } from './index.js' +import { ManyToManyQueryBuilder } from './query_builder.js' +import { ManyToManySubQueryBuilder } from './sub_query_builder.js' +import { managedTransaction, syncDiff } from '../../../utils/index.js' /** * ------------------------------------------------------------ @@ -83,11 +83,7 @@ export class ManyToManyQueryClient implements ManyToManyClientContract - ) { + static query(client: QueryClientContract, relation: ManyToMany, rows: OneOrMany) { const query = new ManyToManyQueryBuilder(client.knexQuery(), client, rows, relation) typeof relation.onQueryHook === 'function' && relation.onQueryHook(query) @@ -97,11 +93,7 @@ export class ManyToManyQueryClient implements ManyToManyClientContract - ) { + static eagerQuery(client: QueryClientContract, relation: ManyToMany, rows: OneOrMany) { const query = new ManyToManyQueryBuilder(client.knexQuery(), client, rows, relation) query.isRelatedPreloadQuery = true @@ -112,7 +104,7 @@ export class ManyToManyQueryClient implements ManyToManyClientContract - ) { + static pivotQuery(client: QueryClientContract, relation: ManyToMany, rows: OneOrMany) { const query = new ManyToManyQueryBuilder(client.knexQuery(), client, rows, relation) query.isRelatedPreloadQuery = false query.isPivotOnlyQuery = true @@ -138,14 +126,14 @@ export class ManyToManyQueryClient implements ManyToManyClientContract { /** * Persist parent @@ -188,7 +176,7 @@ export class ManyToManyQueryClient implements ManyToManyClientContract { @@ -343,7 +331,7 @@ export class ManyToManyQueryClient implements ManyToManyClientContract { @@ -53,6 +55,8 @@ export class ManyToManySubQueryBuilder subQuery.applyWhere() } }) + this.relatedTable = this.relation.relatedModel().table + this.hasSelfRelation = this.relatedTable === this.relation.model.table } /** @@ -126,7 +130,7 @@ export class ManyToManySubQueryBuilder /** * Select keys from the related table */ - public select(...args: any[]): this { + select(...args: any[]): this { let columns = args if (Array.isArray(args[0])) { columns = args[0] @@ -139,7 +143,7 @@ export class ManyToManySubQueryBuilder /** * Add where clause with pivot table prefix */ - public wherePivot(key: any, operator?: any, value?: any): this { + wherePivot(key: any, operator?: any, value?: any): this { this.pivotHelpers.wherePivot('and', key, operator, value) return this } @@ -147,7 +151,7 @@ export class ManyToManySubQueryBuilder /** * Add or where clause with pivot table prefix */ - public orWherePivot(key: any, operator?: any, value?: any): this { + orWherePivot(key: any, operator?: any, value?: any): this { this.pivotHelpers.wherePivot('or', key, operator, value) return this } @@ -155,14 +159,14 @@ export class ManyToManySubQueryBuilder /** * Alias for wherePivot */ - public andWherePivot(key: any, operator?: any, value?: any): this { + andWherePivot(key: any, operator?: any, value?: any): this { return this.wherePivot(key, operator, value) } /** * Add where not pivot */ - public whereNotPivot(key: any, operator?: any, value?: any): this { + whereNotPivot(key: any, operator?: any, value?: any): this { this.pivotHelpers.wherePivot('not', key, operator, value) return this } @@ -170,7 +174,7 @@ export class ManyToManySubQueryBuilder /** * Add or where not pivot */ - public orWhereNotPivot(key: any, operator?: any, value?: any): this { + orWhereNotPivot(key: any, operator?: any, value?: any): this { this.pivotHelpers.wherePivot('orNot', key, operator, value) return this } @@ -178,14 +182,14 @@ export class ManyToManySubQueryBuilder /** * Alias for `whereNotPivot` */ - public andWhereNotPivot(key: any, operator?: any, value?: any): this { + andWhereNotPivot(key: any, operator?: any, value?: any): this { return this.whereNotPivot(key, operator, value) } /** * Adds where in clause */ - public whereInPivot(key: any, value: any) { + whereInPivot(key: any, value: any) { this.pivotHelpers.whereInPivot('and', key, value) return this } @@ -193,7 +197,7 @@ export class ManyToManySubQueryBuilder /** * Adds or where in clause */ - public orWhereInPivot(key: any, value: any) { + orWhereInPivot(key: any, value: any) { this.pivotHelpers.whereInPivot('or', key, value) return this } @@ -201,14 +205,14 @@ export class ManyToManySubQueryBuilder /** * Alias from `whereInPivot` */ - public andWhereInPivot(key: any, value: any): this { + andWhereInPivot(key: any, value: any): this { return this.whereInPivot(key, value) } /** * Adds where not in clause */ - public whereNotInPivot(key: any, value: any) { + whereNotInPivot(key: any, value: any) { this.pivotHelpers.whereInPivot('not', key, value) return this } @@ -216,7 +220,7 @@ export class ManyToManySubQueryBuilder /** * Adds or where not in clause */ - public orWhereNotInPivot(key: any, value: any) { + orWhereNotInPivot(key: any, value: any) { this.pivotHelpers.whereInPivot('orNot', key, value) return this } @@ -224,14 +228,14 @@ export class ManyToManySubQueryBuilder /** * Alias from `whereNotInPivot` */ - public andWhereNotInPivot(key: any, value: any): this { + andWhereNotInPivot(key: any, value: any): this { return this.whereNotInPivot(key, value) } /** * Same as "whereNull", but for the pivot table only */ - public whereNullPivot(key: string): this { + whereNullPivot(key: string): this { this.pivotHelpers.whereNullPivot('and', key) return this } @@ -239,7 +243,7 @@ export class ManyToManySubQueryBuilder /** * Same as "orWhereNull", but for the pivot table only */ - public orWhereNullPivot(key: string): this { + orWhereNullPivot(key: string): this { this.pivotHelpers.whereNullPivot('or', key) return this } @@ -247,14 +251,14 @@ export class ManyToManySubQueryBuilder /** * Same as "andWhereNull", but for the pivot table only */ - public andWhereNullPivot(key: string): this { + andWhereNullPivot(key: string): this { return this.whereNullPivot(key) } /** * Same as "whereNotNull", but for the pivot table only */ - public whereNotNullPivot(key: string): this { + whereNotNullPivot(key: string): this { this.pivotHelpers.whereNullPivot('not', key) return this } @@ -262,7 +266,7 @@ export class ManyToManySubQueryBuilder /** * Same as "orWhereNotNull", but for the pivot table only */ - public orWhereNotNullPivot(key: string): this { + orWhereNotNullPivot(key: string): this { this.pivotHelpers.whereNullPivot('orNot', key) return this } @@ -270,14 +274,14 @@ export class ManyToManySubQueryBuilder /** * Same as "andWhereNotNull", but for the pivot table only */ - public andWhereNotNullPivot(key: string): this { + andWhereNotNullPivot(key: string): this { return this.whereNotNullPivot(key) } /** * Select pivot columns */ - public pivotColumns(columns: string[]): this { + pivotColumns(columns: string[]): this { this.pivotHelpers.pivotColumns(columns) return this } @@ -285,7 +289,7 @@ export class ManyToManySubQueryBuilder /** * Clones the current query */ - public clone() { + clone() { const clonedQuery = new ManyToManySubQueryBuilder( this.knexQuery.clone(), this.client, diff --git a/src/query_client/index.ts b/src/query_client/index.ts index 57c112c0..be5eca17 100644 --- a/src/query_client/index.ts +++ b/src/query_client/index.ts @@ -20,7 +20,6 @@ import { } from '../../adonis-typings/database.js' import { dialects } from '../dialects/index.js' -// import { ModelQueryBuilder } from '../Orm/QueryBuilder' import { TransactionClient } from '../transaction_client/index.js' import { RawBuilder } from '../database/static_builder/raw.js' import { RawQueryBuilder } from '../database/query_builder/raw.js' @@ -32,6 +31,7 @@ import { RawQueryBindings, DatabaseQueryBuilderContract, } from '../../adonis-typings/querybuilder.js' +import { ModelQueryBuilder } from '../orm/query_builder/index.js' /** * Query client exposes the API to fetch instance of different query builders @@ -232,8 +232,11 @@ export class QueryClient implements QueryClientContract { * Returns a query builder instance for a given model. */ modelQuery(model: T): ModelQueryBuilderContract { - // modelQuery(model: any): any { - // return new ModelQueryBuilder(this.knexQuery(), model, this) + return new ModelQueryBuilder( + this.knexQuery(), + model, + this + ) as unknown as ModelQueryBuilderContract } /** diff --git a/src/transaction_client/index.ts b/src/transaction_client/index.ts index 00751a2f..837804e2 100644 --- a/src/transaction_client/index.ts +++ b/src/transaction_client/index.ts @@ -17,12 +17,13 @@ import { TransactionClientContract, } from '../../adonis-typings/database.js' +import { ModelQueryBuilder } from '../orm/query_builder/index.js' import { RawBuilder } from '../database/static_builder/raw.js' -// import { ModelQueryBuilder } from '../Orm/QueryBuilder/index.js' import { RawQueryBuilder } from '../database/query_builder/raw.js' import { InsertQueryBuilder } from '../database/query_builder/insert.js' import { ReferenceBuilder } from '../database/static_builder/reference.js' import { DatabaseQueryBuilder } from '../database/query_builder/database.js' +import { LucidModel, ModelQueryBuilderContract } from '../../adonis-typings/model.js' /** * Transaction uses a dedicated connection from the connection pool @@ -169,8 +170,12 @@ export class TransactionClient extends EventEmitter implements TransactionClient * and `profiler` is passed down to the model, so that it continue * using the same options */ - modelQuery(model: any): any { - // return new ModelQueryBuilder(this.knexQuery(), model, this) + modelQuery(model: T): ModelQueryBuilderContract { + return new ModelQueryBuilder( + this.knexQuery(), + model, + this + ) as unknown as ModelQueryBuilderContract } /** diff --git a/test-helpers/index.ts b/test-helpers/index.ts index 4ff2ada3..74087caf 100644 --- a/test-helpers/index.ts +++ b/test-helpers/index.ts @@ -11,6 +11,7 @@ import dotenv from 'dotenv' import { join } from 'node:path' import { Chance } from 'chance' import knex, { Knex } from 'knex' +import { getActiveTest } from '@japa/runner' import { Logger } from '@adonisjs/core/logger' import { Emitter } from '@adonisjs/core/events' import { AppFactory } from '@adonisjs/core/factories/app' @@ -33,7 +34,6 @@ import { LucidRow, LucidModel, AdapterContract } from '../adonis-typings/model.j import { fileURLToPath } from 'node:url' // import { QueryClient } from '../src/QueryClient/index.js' import { DefineCallback, FactoryModelContract } from '../adonis-typings/factory.js' -import { EventsList } from '../adonis-typings/events.js' import { QueryClient } from '../src/query_client/index.js' import { Database } from '../src/database/index.js' import { DatabaseQueryBuilder } from '../src/database/query_builder/database.js' @@ -42,6 +42,8 @@ import { InsertQueryBuilder } from '../src/database/query_builder/insert.js' import { Migrator } from '../src/migrator/index.js' import { Application } from '@adonisjs/core/app' import { Schema } from '../src/schema/index.js' +import { BaseModel } from '../src/orm/base_model/index.js' +import { Adapter } from '../src/orm/adapter/index.js' // import { Schema } from '../src/Schema' // import { Migrator } from '../src/Migrator' @@ -412,23 +414,28 @@ export function getDb(eventEmitter?: Emitter) { }, } - return new Database(config, logger, eventEmitter || createEmitter()) + const db = new Database(config, logger, eventEmitter || createEmitter()) + const test = getActiveTest() + test?.cleanup(() => { + return db.manager.closeAll() + }) + return db } /** * Returns the orm adapter */ -export function ormAdapter(db: DatabaseContract) { +export function ormAdapter(db: Database) { return new Adapter(db) } /** * Returns the base model with the adapter attached to it */ -export function getBaseModel(adapter: AdapterContract, application: ApplicationContract) { +export function getBaseModel(adapter: AdapterContract, application: Application) { BaseModel.$adapter = adapter BaseModel.$container = application.container - return BaseModel as LucidModel + return BaseModel } /** @@ -486,7 +493,7 @@ export class FakeAdapter implements AdapterContract { on(action: 'find', handler: (model: LucidModel, options?: any) => void): void on(action: 'findAll', handler: (model: LucidModel, options?: any) => void): void on( - action: string, + action: 'insert' | 'update' | 'delete' | 'refresh' | 'find' | 'findAll', handler: ((model: LucidRow, attributes?: any) => void) | ((model: LucidModel) => void) ): void { this._handlers[action] = handler diff --git a/test/orm/base-model.spec.ts b/test/orm/base_model.spec.ts similarity index 63% rename from test/orm/base-model.spec.ts rename to test/orm/base_model.spec.ts index 3f934f19..809b0fcf 100644 --- a/test/orm/base-model.spec.ts +++ b/test/orm/base_model.spec.ts @@ -7,15 +7,13 @@ * file that was distributed with this source code. */ -/// - -import { test } from '@japa/runner' import { DateTime } from 'luxon' -import { lodash } from '@poppinss/utils' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' -import type { HasOne, HasMany, BelongsTo } from '@ioc:Adonis/Lucid/Orm' +import { test } from '@japa/runner' +import lodash from '@poppinss/utils/lodash' +import { AppFactory } from '@adonisjs/core/factories/app' -import { ModelQueryBuilder } from '../../src/Orm/QueryBuilder' +import { ModelQueryBuilder } from '../../src/orm/query_builder/index.js' +import type { HasOne, HasMany, BelongsTo } from '../../adonis-typings/relations.js' import { column, @@ -37,12 +35,10 @@ import { afterPaginate, beforePaginate, computed, -} from '../../src/Orm/Decorators' +} from '../../src/orm/decorators/index.js' import { - fs, getDb, - cleanup, setup, mapToObj, getUsers, @@ -50,40 +46,40 @@ import { resetTables, FakeAdapter, getBaseModel, - setupApplication, sleep, -} from '../../test-helpers' -import { ModelPaginator } from '../../src/Orm/Paginator' -import { SimplePaginator } from '../../src/Database/Paginator/SimplePaginator' -import { SnakeCaseNamingStrategy } from '../../src/Orm/NamingStrategies/SnakeCase' - -let db: ReturnType -let BaseModel: ReturnType -let app: ApplicationContract + cleanup as cleanupTables, +} from '../../test-helpers/index.js' +import { ModelPaginator } from '../../src/orm/paginator/index.js' +import { QueryClientContract } from '../../adonis-typings/database.js' +import { SimplePaginator } from '../../src/database/paginator/simple_paginator.js' +import { InsertQueryBuilderContract } from '../../adonis-typings/querybuilder.js' +import { SnakeCaseNamingStrategy } from '../../src/orm/naming_strategies/snake_case.js' +import { ModelQueryBuilderContract, LucidModel, LucidRow } from '../../adonis-typings/model.js' test.group('Base model | boot', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() - await cleanup() - await fs.cleanup() + await cleanupTables() }) - test('ensure save method is chainable', async ({ assert }) => { + test('ensure save method is chainable', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) const adapter = new FakeAdapter() + await app.init() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column() - public age: number + declare age: number } + User.$adapter = adapter const user = new User() @@ -94,13 +90,19 @@ test.group('Base model | boot', (group) => { assert.instanceOf(chained, User) }) - test('ensure fill method is chainable', async ({ assert }) => { + test('ensure fill method is chainable', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + const adapter = new FakeAdapter() + await app.init() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column() - public age: number + declare age: number } const user = new User() @@ -112,13 +114,19 @@ test.group('Base model | boot', (group) => { assert.instanceOf(chained, User) }) - test('ensure merge method is chainable', async ({ assert }) => { + test('ensure merge method is chainable', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + const adapter = new FakeAdapter() + await app.init() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column() - public age: number + declare age: number } const user = new User() @@ -130,14 +138,19 @@ test.group('Base model | boot', (group) => { assert.instanceOf(chained, User) }) - test('ensure refresh method is chainable', async ({ assert }) => { + test('ensure refresh method is chainable', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) const adapter = new FakeAdapter() + await app.init() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column() - public age: number + declare age: number } User.$adapter = adapter @@ -147,35 +160,51 @@ test.group('Base model | boot', (group) => { assert.instanceOf(chained, User) }) - test('compute table name from model name', async ({ assert }) => { + test('compute table name from model name', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + const adapter = new FakeAdapter() + await app.init() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() assert.equal(User.table, 'users') }) - test('allow overriding table name', async ({ assert }) => { + test('allow overriding table name', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + const adapter = new FakeAdapter() + await app.init() + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static table = 'my_users' + static table = 'my_users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() assert.equal(User.table, 'my_users') }) - test('initiate all required static properties', async ({ assert }) => { + test('initiate all required static properties', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + const adapter = new FakeAdapter() + await app.init() + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel {} User.boot() @@ -184,90 +213,120 @@ test.group('Base model | boot', (group) => { assert.deepEqual(mapToObj(User.$computedDefinitions), {}) }) - test('resolve column name from attribute name', async ({ assert }) => { + test('resolve column name from attribute name', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + const adapter = new FakeAdapter() + await app.init() + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $increments = false + static $increments = false @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userName: string + declare userName: string } User.boot() assert.deepEqual(User.$keys.attributesToColumns.get('userName'), 'user_name') }) - test('resolve serializeAs name from the attribute name', async ({ assert }) => { + test('resolve serializeAs name from the attribute name', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + const adapter = new FakeAdapter() + await app.init() + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $increments = false + static $increments = false @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userName: string + declare userName: string } User.boot() assert.deepEqual(User.$keys.attributesToSerialized.get('userName'), 'user_name') }) - test('resolve attribute name from column name', async ({ assert }) => { + test('resolve attribute name from column name', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + const adapter = new FakeAdapter() + await app.init() + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $increments = false + static $increments = false @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userName: string + declare userName: string } User.boot() assert.deepEqual(User.$keys.columnsToAttributes.get('user_name'), 'userName') }) - test('resolve serializeAs name from column name', async ({ assert }) => { + test('resolve serializeAs name from column name', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + const adapter = new FakeAdapter() + await app.init() + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $increments = false + static $increments = false @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userName: string + declare userName: string } User.boot() assert.deepEqual(User.$keys.columnsToSerialized.get('user_name'), 'user_name') }) - test('resolve attribute name from serializeAs name', async ({ assert }) => { + test('resolve attribute name from serializeAs name', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + const adapter = new FakeAdapter() + await app.init() + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $increments = false + static $increments = false @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userName: string + declare userName: string } User.boot() assert.deepEqual(User.$keys.serializedToAttributes.get('user_name'), 'userName') }) - test('resolve column name from serializeAs name', async ({ assert }) => { + test('resolve column name from serializeAs name', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + const adapter = new FakeAdapter() + await app.init() + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $increments = false + static $increments = false @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userName: string + declare userName: string } User.boot() @@ -277,66 +336,54 @@ test.group('Base model | boot', (group) => { test.group('Base Model | options', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() - await cleanup() - await fs.cleanup() + await cleanupTables() }) - test('set connection using useConnection method', ({ assert }) => { - class User extends BaseModel { - @column() - public username: string - } + test('set connection using useConnection method', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) - const user = new User() - user.username = 'virk' + const BaseModel = getBaseModel(adapter, app) - user.useConnection('foo') - assert.deepEqual(user.$options, { connection: 'foo' }) - }) - - test('set connection do not overwrite profiler from the options', ({ assert }) => { class User extends BaseModel { @column() - public username: string + declare username: string } const user = new User() user.username = 'virk' - const profiler = app.profiler - user.$options = { profiler: profiler } - user.useConnection('foo') - assert.deepEqual(user.$options, { connection: 'foo', profiler: profiler }) + assert.deepEqual(user.$options, { connection: 'foo' }) }) }) test.group('Base Model | getter-setters', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() - await cleanup() - await fs.cleanup() + await cleanupTables() }) - test('set property on $attributes when defined on model instance', ({ assert }) => { + test('set property on $attributes when defined on model instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string } const user = new User() @@ -345,7 +392,14 @@ test.group('Base Model | getter-setters', (group) => { assert.deepEqual(user.$attributes, { username: 'virk' }) }) - test('pass value to setter when defined', ({ assert }) => { + test('pass value to setter when defined', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() public set username(value: any) { @@ -359,9 +413,16 @@ test.group('Base Model | getter-setters', (group) => { assert.deepEqual(user.$attributes, { username: 'VIRK' }) }) - test('set value on model instance when is not a column', ({ assert }) => { + test('set value on model instance when is not a column', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public username: string + declare username: string } User.boot() @@ -372,10 +433,17 @@ test.group('Base Model | getter-setters', (group) => { assert.equal(user.username, 'virk') }) - test('get value from attributes', ({ assert }) => { + test('get value from attributes', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string } const user = new User() @@ -384,7 +452,14 @@ test.group('Base Model | getter-setters', (group) => { assert.equal(user.username, 'virk') }) - test('rely on getter when column is defined as a getter', ({ assert }) => { + test('rely on getter when column is defined as a getter', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() public get username() { @@ -398,9 +473,16 @@ test.group('Base Model | getter-setters', (group) => { assert.equal(user.username, 'VIRK') }) - test('get value from model instance when is not a column', ({ assert }) => { + test('get value from model instance when is not a column', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public username = 'virk' + username = 'virk' } User.boot() @@ -408,13 +490,20 @@ test.group('Base Model | getter-setters', (group) => { assert.equal(user.username, 'virk') }) - test('get value for primary key', ({ assert }) => { + test('get value for primary key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } const user = new User() @@ -423,7 +512,14 @@ test.group('Base Model | getter-setters', (group) => { assert.deepEqual(user.$primaryKeyValue, 1) }) - test('invoke getter when accessing value using primaryKeyValue', ({ assert }) => { + test('invoke getter when accessing value using primaryKeyValue', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) public get id() { @@ -431,7 +527,7 @@ test.group('Base Model | getter-setters', (group) => { } @column() - public username: string + declare username: string } const user = new User() @@ -440,7 +536,14 @@ test.group('Base Model | getter-setters', (group) => { assert.deepEqual(user.$primaryKeyValue, '1') }) - test('invoke column serialize method when serializing model', ({ assert }) => { + test('invoke column serialize method when serializing model', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) public get id() { @@ -452,7 +555,7 @@ test.group('Base Model | getter-setters', (group) => { return value.toUpperCase() }, }) - public username: string + declare username: string } const user = new User() @@ -461,7 +564,14 @@ test.group('Base Model | getter-setters', (group) => { assert.equal(user.toJSON().username, 'VIRK') }) - test('implement custom merge strategies using getters and setters', ({ assert }) => { + test('implement custom merge strategies using getters and setters', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() public get preferences(): object { @@ -506,22 +616,24 @@ test.group('Base Model | getter-setters', (group) => { test.group('Base Model | dirty', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() - await cleanup() - await fs.cleanup() + await cleanupTables() }) - test('get dirty properties on a fresh model', ({ assert }) => { + test('get dirty properties on a fresh model', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string } const user = new User() @@ -531,10 +643,17 @@ test.group('Base Model | dirty', (group) => { assert.isTrue(user.$isDirty) }) - test('get empty object when model is not dirty', ({ assert }) => { + test('get empty object when model is not dirty', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string } const user = new User() @@ -547,10 +666,17 @@ test.group('Base Model | dirty', (group) => { assert.isFalse(user.$isDirty) }) - test('get empty object when model is not dirty with null values', ({ assert }) => { + test('get empty object when model is not dirty with null values', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string } const user = new User() @@ -563,10 +689,17 @@ test.group('Base Model | dirty', (group) => { assert.isFalse(user.$isDirty) }) - test('get empty object when model is not dirty with false values', ({ assert }) => { + test('get empty object when model is not dirty with false values', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string } const user = new User() @@ -579,15 +712,21 @@ test.group('Base Model | dirty', (group) => { assert.isFalse(user.$isDirty) }) - test('get values removed as a side-effect of fill as dirty', async ({ assert }) => { + test('get values removed as a side-effect of fill as dirty', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column() - public age: number + declare age: number } + User.$adapter = adapter const user = new User() @@ -603,17 +742,22 @@ test.group('Base Model | dirty', (group) => { assert.deepEqual(user.$dirty, { age: null }) }) - test('compute diff for properties represented as objects', async ({ assert }) => { + test('compute diff for properties represented as objects', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column() - public age: number + declare age: number @column() - public location: any + declare location: any } User.$adapter = adapter @@ -630,7 +774,13 @@ test.group('Base Model | dirty', (group) => { assert.deepEqual(user.$dirty, { location: { state: 'goa', country: 'India' } }) }) - test('compute diff for properties represented as classes', async ({ assert }) => { + test('compute diff for properties represented as classes', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class Location { public isDirty = false constructor( @@ -639,13 +789,12 @@ test.group('Base Model | dirty', (group) => { ) {} } - const adapter = new FakeAdapter() class User extends BaseModel { @column() - public username: string + declare username: string @column() - public age: number + declare age: number @column() public location: any @@ -669,34 +818,33 @@ test.group('Base Model | dirty', (group) => { test.group('Base Model | persist', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() - await cleanup() - await fs.cleanup() + await cleanupTables() }) group.each.teardown(async () => { await resetTables() }) - test('persist model with the column name', async ({ assert }) => { + test('persist model with the column name', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) const adapter = new FakeAdapter() + await app.init() + + const BaseModel = getBaseModel(adapter, app) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column({ columnName: 'full_name' }) - public fullName: string + declare fullName: string } User.$adapter = adapter @@ -724,15 +872,19 @@ test.group('Base Model | persist', (group) => { assert.deepEqual(user.$original, { username: 'virk', fullName: 'H virk', id: 1 }) }) - test('merge adapter insert return value with attributes', async ({ assert }) => { + test('merge adapter insert return value with attributes', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) const adapter = new FakeAdapter() + await app.init() + + const BaseModel = getBaseModel(adapter, app) class User extends BaseModel { @column() - public username: string + declare username: string @column() - public id: number + declare id: number } User.$adapter = adapter @@ -758,12 +910,16 @@ test.group('Base Model | persist', (group) => { assert.deepEqual(user.$original, { username: 'virk', id: 1 }) }) - test('do not merge adapter results when not part of model columns', async ({ assert }) => { + test('do not merge adapter results when not part of model columns', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) const adapter = new FakeAdapter() + await app.init() + + const BaseModel = getBaseModel(adapter, app) class User extends BaseModel { @column() - public username: string + declare username: string } User.$adapter = adapter @@ -789,12 +945,16 @@ test.group('Base Model | persist', (group) => { assert.deepEqual(user.$original, { username: 'virk' }) }) - test('issue update when model has already been persisted', async ({ assert }) => { + test('issue update when model has already been persisted', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) const adapter = new FakeAdapter() + await app.init() + + const BaseModel = getBaseModel(adapter, app) class User extends BaseModel { @column() - public username: string + declare username: string } User.$adapter = adapter @@ -818,15 +978,19 @@ test.group('Base Model | persist', (group) => { assert.deepEqual(user.$original, { username: 'virk' }) }) - test('merge return values from update', async ({ assert }) => { + test('merge return values from update', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) const adapter = new FakeAdapter() + await app.init() + + const BaseModel = getBaseModel(adapter, app) class User extends BaseModel { @column() - public username: string + declare username: string @column({ columnName: 'updated_at' }) - public updatedAt: string + declare updatedAt: string } adapter.on('update', (model) => { @@ -854,15 +1018,19 @@ test.group('Base Model | persist', (group) => { assert.deepEqual(user.$original, { username: 'virk', updatedAt: '2019-11-20' }) }) - test('do not issue update when model is not dirty', async ({ assert }) => { + test('do not issue update when model is not dirty', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) const adapter = new FakeAdapter() + await app.init() + + const BaseModel = getBaseModel(adapter, app) class User extends BaseModel { @column() - public username: string + declare username: string @column({ columnName: 'updated_at' }) - public updatedAt: string + declare updatedAt: string } User.$adapter = adapter @@ -878,19 +1046,26 @@ test.group('Base Model | persist', (group) => { assert.deepEqual(user.$original, {}) }) - test('refresh model instance', async ({ assert }) => { + test('refresh model instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public createdAt: string + declare createdAt: string @column({ columnName: 'updated_at' }) - public updatedAt: string + declare updatedAt: string } const user = new User() @@ -907,19 +1082,26 @@ test.group('Base Model | persist', (group) => { assert.isDefined(user.updatedAt) }) - test('refresh model instance inside a transaction', async ({ assert }) => { + test('refresh model instance inside a transaction', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public createdAt: string + declare createdAt: string @column({ columnName: 'updated_at' }) - public updatedAt: string + declare updatedAt: string } /** @@ -952,21 +1134,28 @@ test.group('Base Model | persist', (group) => { assert.equal(user.username, 'virk') }) - test('raise exception when attempted to refresh deleted row', async ({ assert }) => { + test('raise exception when attempted to refresh deleted row', async ({ fs, assert }) => { assert.plan(4) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public createdAt: string + declare createdAt: string @column({ columnName: 'updated_at' }) - public updatedAt: string + declare updatedAt: string } const user = new User() @@ -986,15 +1175,21 @@ test.group('Base Model | persist', (group) => { } }) - test('invoke column prepare method before passing values to the adapter', async ({ assert }) => { + test('invoke column prepare method before passing values to the adapter', async ({ + fs, + assert, + }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() const adapter = new FakeAdapter() + const BaseModel = getBaseModel(adapter, app) class User extends BaseModel { @column() - public username: string + declare username: string @column({ columnName: 'full_name', prepare: (value) => value.toUpperCase() }) - public fullName: string + declare fullName: string } User.$adapter = adapter @@ -1018,21 +1213,25 @@ test.group('Base Model | persist', (group) => { assert.deepEqual(user.$original, { username: 'virk', fullName: 'H virk' }) }) - test('send values mutated by the hooks to the adapter', async ({ assert }) => { + test('send values mutated by the hooks to the adapter', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() const adapter = new FakeAdapter() + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column({ columnName: 'full_name' }) - public fullName: string + declare fullName: string @beforeUpdate() - public static touchValues(model: User) { + static touchValues(model: User) { model.fullName = 'Foo' } } @@ -1050,19 +1249,24 @@ test.group('Base Model | persist', (group) => { assert.deepEqual(user.$original, { fullName: 'Foo' }) }) - test('allow datetime column value to be null', async ({ assert }) => { + test('allow datetime column value to be null', async ({ fs, assert }) => { assert.plan(3) + + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() const adapter = new FakeAdapter() + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public createdAt: DateTime | null + declare createdAt: DateTime | null } User.$adapter = adapter @@ -1080,22 +1284,29 @@ test.group('Base Model | persist', (group) => { assert.deepEqual(user.$original, { createdAt: null }) }) - test('assign local id to the model', async ({ assert }) => { + test('assign local id to the model', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = await getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static table = 'uuid_users' - public static selfAssignPrimaryKey = true + static table = 'uuid_users' + static selfAssignPrimaryKey = true @column({ isPrimary: true }) - public id: string + declare id: string @column() - public username: string + declare username: string @column() - public createdAt: string + declare createdAt: string @column({ columnName: 'updated_at' }) - public updatedAt: string + declare updatedAt: string } User.boot() @@ -1119,22 +1330,29 @@ test.group('Base Model | persist', (group) => { assert.equal(user.id.toLocaleLowerCase(), uuid) }) - test('perform update query when local primary key is updated', async ({ assert }) => { + test('perform update query when local primary key is updated', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = await getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static table = 'uuid_users' - public static selfAssignPrimaryKey = true + static table = 'uuid_users' + static selfAssignPrimaryKey = true @column({ isPrimary: true }) - public id: string + declare id: string @column() - public username: string + declare username: string @column() - public createdAt: string + declare createdAt: string @column({ columnName: 'updated_at' }) - public updatedAt: string + declare updatedAt: string } User.boot() @@ -1157,21 +1375,26 @@ test.group('Base Model | persist', (group) => { }) test.group('Self assign primary key', () => { - test('send primary value during insert to the adapter', async ({ assert }) => { + test('send primary value during insert to the adapter', async ({ fs, assert }) => { assert.plan(1) + + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() const adapter = new FakeAdapter() + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static selfAssignPrimaryKey = true + static selfAssignPrimaryKey = true @column({ isPrimary: true }) - public id: string + declare id: string @column() - public username: string + declare username: string @column({ columnName: 'full_name' }) - public fullName: string + declare fullName: string } User.$adapter = adapter @@ -1191,21 +1414,26 @@ test.group('Self assign primary key', () => { await user.save() }) - test('update primary key when changed', async ({ assert }) => { + test('update primary key when changed', async ({ fs, assert }) => { assert.plan(3) + + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() const adapter = new FakeAdapter() + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static selfAssignPrimaryKey = true + static selfAssignPrimaryKey = true @column({ isPrimary: true }) - public id: string + declare id: string @column() - public username: string + declare username: string @column({ columnName: 'full_name' }) - public fullName: string + declare fullName: string } User.$adapter = adapter @@ -1237,25 +1465,26 @@ test.group('Self assign primary key', () => { test.group('Base Model | create from adapter results', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() - await cleanup() - await fs.cleanup() + await cleanupTables() }) - test('create model instance using $createFromAdapterResult method', async ({ assert }) => { + test('create model instance using $createFromAdapterResult method', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column({ columnName: 'full_name' }) - public fullName: string + declare fullName: string } const user = User.$createFromAdapterResult({ username: 'virk' }) @@ -1268,13 +1497,22 @@ test.group('Base Model | create from adapter results', (group) => { assert.deepEqual(user!.$original, { username: 'virk' }) }) - test('set options on model instance passed to $createFromAdapterResult', async ({ assert }) => { + test('set options on model instance passed to $createFromAdapterResult', async ({ + fs, + assert, + }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column({ columnName: 'full_name' }) - public fullName: string + declare fullName: string } const user = User.$createFromAdapterResult({ username: 'virk' }, [], { connection: 'foo' }) @@ -1287,13 +1525,22 @@ test.group('Base Model | create from adapter results', (group) => { assert.deepEqual(user!.$original, { username: 'virk' }) }) - test('return null from $createFromAdapterResult when input is not object', ({ assert }) => { + test('return null from $createFromAdapterResult when input is not object', async ({ + fs, + assert, + }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column({ columnName: 'full_name' }) - public fullName: string + declare fullName: string } const user = User.$createFromAdapterResult([]) @@ -1302,13 +1549,20 @@ test.group('Base Model | create from adapter results', (group) => { test('create multiple model instance using $createMultipleFromAdapterResult', async ({ assert, + fs, }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column({ columnName: 'full_name' }) - public fullName: string + declare fullName: string } const users = User.$createMultipleFromAdapterResult([ @@ -1330,13 +1584,19 @@ test.group('Base Model | create from adapter results', (group) => { assert.deepEqual(users[1].$original, { username: 'prasan' }) }) - test('pass model options via $createMultipleFromAdapterResult', async ({ assert }) => { + test('pass model options via $createMultipleFromAdapterResult', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column({ columnName: 'full_name' }) - public fullName: string + declare fullName: string } const users = User.$createMultipleFromAdapterResult( @@ -1362,13 +1622,19 @@ test.group('Base Model | create from adapter results', (group) => { assert.deepEqual(users[1].$original, { username: 'prasan' }) }) - test('skip rows that are not valid objects inside array', async ({ assert }) => { + test('skip rows that are not valid objects inside array', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column({ columnName: 'full_name' }) - public fullName: string + declare fullName: string } const users = User.$createMultipleFromAdapterResult([ @@ -1384,15 +1650,21 @@ test.group('Base Model | create from adapter results', (group) => { assert.deepEqual(users[0].$original, { username: 'virk', fullName: 'H virk' }) }) - test('invoke column consume method', async ({ assert }) => { + test('invoke column consume method', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column({ consume: (value) => value.toUpperCase(), }) - public fullName: string + declare fullName: string } const user = User.$createFromAdapterResult({ full_name: 'virk' }) @@ -1404,15 +1676,21 @@ test.group('Base Model | create from adapter results', (group) => { assert.deepEqual(user!.$original, { fullName: 'VIRK' }) }) - test('original and attributes should not be shared', async ({ assert }) => { + test('original and attributes should not be shared', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public user: { + declare user: { username: string } @column({ columnName: 'full_name' }) - public fullName: string + declare fullName: string } const user = User.$createFromAdapterResult({ @@ -1429,24 +1707,23 @@ test.group('Base Model | create from adapter results', (group) => { test.group('Base Model | delete', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() - await cleanup() - await fs.cleanup() + await cleanupTables() }) - test('delete model instance using adapter', async ({ assert }) => { + test('delete model instance using adapter', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() const adapter = new FakeAdapter() + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string } User.$adapter = adapter @@ -1463,13 +1740,18 @@ test.group('Base Model | delete', (group) => { assert.isTrue(user.$isDeleted) }) - test('raise exception when trying to mutate model after deletion', async ({ assert }) => { - const adapter = new FakeAdapter() + test('raise exception when trying to mutate model after deletion', async ({ fs, assert }) => { assert.plan(1) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string } User.$adapter = adapter @@ -1480,16 +1762,22 @@ test.group('Base Model | delete', (group) => { try { user.username = 'virk' } catch ({ message }) { - assert.equal(message, 'E_MODEL_DELETED: Cannot mutate delete model instance') + assert.equal(message, 'Cannot mutate delete model instance') } }) }) test.group('Base Model | serializeAttributes', () => { - test('serialize attributes', async ({ assert }) => { + test('serialize attributes', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string } const user = new User() @@ -1498,10 +1786,16 @@ test.group('Base Model | serializeAttributes', () => { assert.deepEqual(user.serializeAttributes(), { username: 'virk' }) }) - test('invoke custom serialize method when serializing attributes', async ({ assert }) => { + test('invoke custom serialize method when serializing attributes', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ serialize: (value) => value.toUpperCase() }) - public username: string + declare username: string } const user = new User() @@ -1510,10 +1804,16 @@ test.group('Base Model | serializeAttributes', () => { assert.deepEqual(user.serializeAttributes(), { username: 'VIRK' }) }) - test('use custom serializeAs key', async ({ assert }) => { + test('use custom serializeAs key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ serializeAs: 'uname' }) - public username: string + declare username: string } const user = new User() @@ -1522,10 +1822,16 @@ test.group('Base Model | serializeAttributes', () => { assert.deepEqual(user.serializeAttributes(), { uname: 'virk' }) }) - test('do not serialize when serializeAs key is null', async ({ assert }) => { + test('do not serialize when serializeAs key is null', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ serializeAs: null }) - public username: string + declare username: string } const user = new User() @@ -1534,13 +1840,19 @@ test.group('Base Model | serializeAttributes', () => { assert.deepEqual(user.serializeAttributes(), {}) }) - test('pick fields during serialization', async ({ assert }) => { + test('pick fields during serialization', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column() - public id: string + declare id: string } const user = new User() @@ -1550,13 +1862,19 @@ test.group('Base Model | serializeAttributes', () => { assert.deepEqual(user.serializeAttributes(['id']), { id: '1' }) }) - test('ignore fields under omit', async ({ assert }) => { + test('ignore fields under omit', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column() - public id: string + declare id: string } const user = new User() @@ -1571,13 +1889,19 @@ test.group('Base Model | serializeAttributes', () => { ) }) - test('use omit and pick together', async ({ assert }) => { + test('use omit and pick together', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column() - public id: string + declare id: string } const user = new User() @@ -1595,13 +1919,20 @@ test.group('Base Model | serializeAttributes', () => { test('ignore fields that has serializeAs = null, even when part of pick array', async ({ assert, + fs, }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column({ serializeAs: null }) - public id: string + declare id: string } const user = new User() @@ -1611,10 +1942,16 @@ test.group('Base Model | serializeAttributes', () => { assert.deepEqual(user.serializeAttributes(['id']), {}) }) - test('do not invoke custom serialize method when raw flag is on', async ({ assert }) => { + test('do not invoke custom serialize method when raw flag is on', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ serialize: (value) => value.toUpperCase() }) - public username: string + declare username: string } const user = new User() @@ -1623,10 +1960,16 @@ test.group('Base Model | serializeAttributes', () => { assert.deepEqual(user.serializeAttributes(undefined, true), { username: 'virk' }) }) - test('use custom serializeAs key when raw flag is on', async ({ assert }) => { + test('use custom serializeAs key when raw flag is on', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ serializeAs: 'uname' }) - public username: string + declare username: string } const user = new User() @@ -1635,10 +1978,16 @@ test.group('Base Model | serializeAttributes', () => { assert.deepEqual(user.serializeAttributes(undefined, true), { uname: 'virk' }) }) - test('do not serialize with serializeAs = null, when raw flag is on', async ({ assert }) => { + test('do not serialize with serializeAs = null, when raw flag is on', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ serializeAs: null }) - public username: string + declare username: string } const user = new User() @@ -1647,13 +1996,19 @@ test.group('Base Model | serializeAttributes', () => { assert.deepEqual(user.serializeAttributes(undefined, true), {}) }) - test('cherry pick fields in raw mode', async ({ assert }) => { + test('cherry pick fields in raw mode', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column() - public id: string + declare id: string } const user = new User() @@ -1663,13 +2018,19 @@ test.group('Base Model | serializeAttributes', () => { assert.deepEqual(user.serializeAttributes(['id'], true), { id: '1' }) }) - test('ignore fields under omit array in raw mode', async ({ assert }) => { + test('ignore fields under omit array in raw mode', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column() - public id: string + declare id: string } const user = new User() @@ -1690,21 +2051,27 @@ test.group('Base Model | serializeAttributes', () => { }) test.group('Base Model | serializeRelations', () => { - test('serialize relations', async ({ assert }) => { + test('serialize relations', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public username: string + declare username: string @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } const user = new User() @@ -1721,21 +2088,27 @@ test.group('Base Model | serializeRelations', () => { }) }) - test('use custom serializeAs key when raw flag is on', async ({ assert }) => { + test('use custom serializeAs key when raw flag is on', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public username: string + declare username: string @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile, { serializeAs: 'userProfile' }) - public profile: HasOne + declare profile: HasOne } const user = new User() @@ -1752,21 +2125,27 @@ test.group('Base Model | serializeRelations', () => { }) }) - test('do not serialize relations when serializeAs is null', async ({ assert }) => { + test('do not serialize relations when serializeAs is null', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public username: string + declare username: string @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile, { serializeAs: null }) - public profile: HasOne + declare profile: HasOne } const user = new User() @@ -1778,21 +2157,27 @@ test.group('Base Model | serializeRelations', () => { assert.deepEqual(user.serializeRelations(), {}) }) - test('do not recursively serialize relations when raw is true', async ({ assert }) => { + test('do not recursively serialize relations when raw is true', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public username: string + declare username: string @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } const user = new User() @@ -1806,21 +2191,27 @@ test.group('Base Model | serializeRelations', () => { }) }) - test('use custom serializeAs key when raw flag is on', async ({ assert }) => { + test('use custom serializeAs key when raw flag is on', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public username: string + declare username: string @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile, { serializeAs: 'userProfile' }) - public profile: HasOne + declare profile: HasOne } const user = new User() @@ -1836,21 +2227,28 @@ test.group('Base Model | serializeRelations', () => { test('do not serialize relations with serializeAs is null when raw flag is on', async ({ assert, + fs, }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public username: string + declare username: string @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile, { serializeAs: null }) - public profile: HasOne + declare profile: HasOne } const user = new User() @@ -1862,21 +2260,27 @@ test.group('Base Model | serializeRelations', () => { assert.deepEqual(user.serializeRelations(undefined, true), {}) }) - test('cherry pick relationship fields', async ({ assert }) => { + test('cherry pick relationship fields', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public username: string + declare username: string @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } const user = new User() @@ -1900,22 +2304,29 @@ test.group('Base Model | serializeRelations', () => { }) test('select all fields when no custom fields are defined for a relationship', async ({ + fs, assert, }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public username: string + declare username: string @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } const user = new User() @@ -1939,21 +2350,28 @@ test.group('Base Model | serializeRelations', () => { test('do not select any fields when relationship fields is an empty array', async ({ assert, + fs, }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public username: string + declare username: string @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } const user = new User() @@ -1977,22 +2395,23 @@ test.group('Base Model | serializeRelations', () => { test.group('Base Model | toJSON', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() - await cleanup() - await fs.cleanup() + await cleanupTables() }) - test('convert model to its JSON representation', async ({ assert }) => { + test('convert model to its JSON representation', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string } const user = new User() @@ -2001,10 +2420,16 @@ test.group('Base Model | toJSON', (group) => { assert.deepEqual(user.toJSON(), { username: 'virk' }) }) - test('use serializeAs key when converting model to JSON', async ({ assert }) => { + test('use serializeAs key when converting model to JSON', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ serializeAs: 'theUsername' }) - public username: string + declare username: string } const user = new User() @@ -2013,10 +2438,16 @@ test.group('Base Model | toJSON', (group) => { assert.deepEqual(user.toJSON(), { theUsername: 'virk' }) }) - test('do not serialize when serializeAs is set to null', async ({ assert }) => { + test('do not serialize when serializeAs is set to null', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ serializeAs: null }) - public username: string + declare username: string } const user = new User() @@ -2025,13 +2456,19 @@ test.group('Base Model | toJSON', (group) => { assert.deepEqual(user.toJSON(), {}) }) - test('add computed properties to toJSON result', async ({ assert }) => { + test('add computed properties to toJSON result', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @computed() - public get fullName() { + get fullName() { return this.username.toUpperCase() } } @@ -2042,13 +2479,19 @@ test.group('Base Model | toJSON', (group) => { assert.deepEqual(user.toJSON(), { username: 'virk', fullName: 'VIRK' }) }) - test('do not add computed property when it returns undefined', async ({ assert }) => { + test('do not add computed property when it returns undefined', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @computed() - public get fullName() { + get fullName() { return undefined } } @@ -2059,13 +2502,19 @@ test.group('Base Model | toJSON', (group) => { assert.deepEqual(user.toJSON(), { username: 'virk' }) }) - test('cherry pick keys during serialization', async ({ assert }) => { + test('cherry pick keys during serialization', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @computed() - public get fullName() { + get fullName() { return this.username.toUpperCase() } } @@ -2081,15 +2530,21 @@ test.group('Base Model | toJSON', (group) => { ) }) - test('serialize extras', async ({ assert }) => { + test('serialize extras', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public serializeExtras = true + serializeExtras = true @column() - public username: string + declare username: string @computed() - public get fullName() { + get fullName() { return this.username.toUpperCase() } } @@ -2107,9 +2562,15 @@ test.group('Base Model | toJSON', (group) => { }) }) - test('define serialize extras as a function', async ({ assert }) => { + test('define serialize extras as a function', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public serializeExtras() { + serializeExtras() { return { posts: { count: this.$extras.postsCount, @@ -2118,10 +2579,10 @@ test.group('Base Model | toJSON', (group) => { } @column() - public username: string + declare username: string @computed() - public get fullName() { + get fullName() { return this.username.toUpperCase() } } @@ -2139,13 +2600,19 @@ test.group('Base Model | toJSON', (group) => { }) }) - test('do not serialize undefined values', async ({ assert }) => { + test('do not serialize undefined values', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column() - public age: number + declare age: number } const user = new User() @@ -2154,13 +2621,19 @@ test.group('Base Model | toJSON', (group) => { assert.deepEqual(user.toJSON(), { username: 'virk' }) }) - test('serialize null values', async ({ assert }) => { + test('serialize null values', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column() - public age: number | null + declare age: number | null } const user = new User() @@ -2173,24 +2646,24 @@ test.group('Base Model | toJSON', (group) => { test.group('BaseModel | cache', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() - await cleanup() - await fs.cleanup() + await cleanupTables() }) - test('cache getter value', ({ assert }) => { + test('cache getter value', async ({ fs, assert }) => { let invokedCounter = 0 + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) class User extends BaseModel { @column() - public get username() { + get username() { return this.$getAttributeFromCache('username', (value) => { invokedCounter++ return value.toUpperCase() @@ -2209,12 +2682,17 @@ test.group('BaseModel | cache', (group) => { assert.equal(invokedCounter, 1) }) - test('re-call getter function when attribute value changes', ({ assert }) => { + test('re-call getter function when attribute value changes', async ({ fs, assert }) => { let invokedCounter = 0 + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) class User extends BaseModel { @column() - public get username() { + get username() { return this.$getAttributeFromCache('username', (value) => { invokedCounter++ return value.toUpperCase() @@ -2239,22 +2717,23 @@ test.group('BaseModel | cache', (group) => { test.group('BaseModel | fill/merge', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() - await cleanup() - await fs.cleanup() + await cleanupTables() }) - test('fill model instance with bulk attributes', ({ assert }) => { + test('fill model instance with bulk attributes', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string } const user = new User() @@ -2262,10 +2741,16 @@ test.group('BaseModel | fill/merge', (group) => { assert.deepEqual(user.$attributes, { username: 'virk' }) }) - test('raise error when extra properties are defined', ({ assert }) => { + test('raise error when extra properties are defined', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string } const user = new User() @@ -2276,10 +2761,19 @@ test.group('BaseModel | fill/merge', (group) => { ) }) - test('set extra properties via fill when allowExtraProperties is true', ({ assert }) => { + test('set extra properties via fill when allowExtraProperties is true', async ({ + fs, + assert, + }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string } const user = new User() @@ -2288,13 +2782,19 @@ test.group('BaseModel | fill/merge', (group) => { assert.deepEqual(user.$extras, { isAdmin: true }) }) - test('overwrite existing values when using fill', ({ assert }) => { + test('overwrite existing values when using fill', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column() - public age: number + declare age: number } const user = new User() @@ -2305,13 +2805,19 @@ test.group('BaseModel | fill/merge', (group) => { assert.deepEqual(user.$attributes, { username: 'virk' }) }) - test('merge to existing when using merge instead of fill', ({ assert }) => { + test('merge to existing when using merge instead of fill', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column() - public age: number + declare age: number } const user = new User() @@ -2322,13 +2828,19 @@ test.group('BaseModel | fill/merge', (group) => { assert.deepEqual(user.$attributes, { username: 'virk', age: 22 }) }) - test('set properties with explicit undefined values', ({ assert }) => { + test('set properties with explicit undefined values', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column() - public age: number + declare age: number } const user = new User() @@ -2339,17 +2851,23 @@ test.group('BaseModel | fill/merge', (group) => { assert.deepEqual(user.$attributes, { username: 'virk', age: undefined }) }) - test('invoke setter when using fill', ({ assert }) => { + test('invoke setter when using fill', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column() - public get age(): number { + get age(): number { return this.$getAttribute('age') } - public set age(age: number) { + set age(age: number) { this.$setAttribute('age', age + 1) } } @@ -2362,10 +2880,16 @@ test.group('BaseModel | fill/merge', (group) => { assert.deepEqual(user.$attributes, { username: 'virk', age: 23 }) }) - test('fill using the column name', ({ assert }) => { + test('fill using the column name', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public firstName: string + declare firstName: string } const user = new User() @@ -2373,17 +2897,23 @@ test.group('BaseModel | fill/merge', (group) => { assert.deepEqual(user.$attributes, { firstName: 'virk' }) }) - test('invoke setter during fill when using column name', ({ assert }) => { + test('invoke setter during fill when using column name', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column({ columnName: 'user_age' }) - public get age(): number { + get age(): number { return this.$getAttribute('age') } - public set age(age: number) { + set age(age: number) { this.$setAttribute('age', age + 1) } } @@ -2393,15 +2923,21 @@ test.group('BaseModel | fill/merge', (group) => { assert.deepEqual(user.$attributes, { age: 23 }) }) - test('merge set non-column model properties', ({ assert }) => { + test('merge set non-column model properties', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @column() - public age: number + declare age: number - public foo: string + foo!: string } const user = new User() @@ -2413,17 +2949,23 @@ test.group('BaseModel | fill/merge', (group) => { assert.equal(user.foo, 'bar') }) - test('merge set non-column model properties with inheritance', ({ assert }) => { + test('merge set non-column model properties with inheritance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class Super extends BaseModel { - public foo: string + foo!: string } class User extends Super { @column() - public username: string + declare username: string @column() - public age: number + declare age: number } const user = new User() @@ -2438,24 +2980,26 @@ test.group('BaseModel | fill/merge', (group) => { test.group('Base | apdater', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() - await cleanup() - await fs.cleanup() + await cleanupTables() }) - test('pass model instance with attributes to the adapter insert method', async ({ assert }) => { + test('pass model instance with attributes to the adapter insert method', async ({ + fs, + assert, + }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() const adapter = new FakeAdapter() + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string } User.$adapter = adapter @@ -2473,12 +3017,19 @@ test.group('Base | apdater', (group) => { ]) }) - test('pass model instance with attributes to the adapter update method', async ({ assert }) => { + test('pass model instance with attributes to the adapter update method', async ({ + fs, + assert, + }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() const adapter = new FakeAdapter() + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string } User.$adapter = adapter @@ -2504,12 +3055,16 @@ test.group('Base | apdater', (group) => { ]) }) - test('pass model instance to the adapter delete method', async ({ assert }) => { + test('pass model instance to the adapter delete method', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() const adapter = new FakeAdapter() + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string } User.$adapter = adapter @@ -2534,11 +3089,17 @@ test.group('Base | apdater', (group) => { test('fill model instance with bulk attributes via column name is different', async ({ assert, + fs, }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ columnName: 'first_name' }) - public firstName: string + declare firstName: string } User.$adapter = adapter @@ -2559,22 +3120,26 @@ test.group('Base | apdater', (group) => { test.group('Base Model | sideloaded', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() - await cleanup() - await fs.cleanup() + await cleanupTables() }) - test('define sideloaded properties using $consumeAdapterResults method', ({ assert }) => { + test('define sideloaded properties using $consumeAdapterResults method', async ({ + fs, + assert, + }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string } const user = new User() @@ -2584,10 +3149,19 @@ test.group('Base Model | sideloaded', (group) => { assert.deepEqual(user.$sideloaded, { loggedInUser: { id: 1 } }) }) - test('define sideloaded properties using $createFromAdapterResult method', ({ assert }) => { + test('define sideloaded properties using $createFromAdapterResult method', async ({ + fs, + assert, + }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string } const user = User.$createFromAdapterResult({ username: 'virk' }, { loggedInUser: { id: 1 } })! @@ -2595,12 +3169,19 @@ test.group('Base Model | sideloaded', (group) => { assert.deepEqual(user.$sideloaded, { loggedInUser: { id: 1 } }) }) - test('define sideloaded properties using $createMultipleFromAdapterResult method', ({ + test('define sideloaded properties using $createMultipleFromAdapterResult method', async ({ assert, + fs, }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string } const users = User.$createMultipleFromAdapterResult( @@ -2620,34 +3201,34 @@ test.group('Base Model | sideloaded', (group) => { test.group('Base Model | relations', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() - await cleanup() - await fs.cleanup() + await cleanupTables() }) - test('set hasOne relation', async ({ assert }) => { + test('set hasOne relation', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public username: string + declare username: string @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } const user = new User() @@ -2659,21 +3240,27 @@ test.group('Base Model | relations', (group) => { assert.instanceOf(user.$preloaded.profile, Profile) }) - test('return undefined when relation is not preloaded', ({ assert }) => { + test('return undefined when relation is not preloaded', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public username: string + declare username: string @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } const user = new User() @@ -2685,22 +3272,27 @@ test.group('Base Model | relations', (group) => { assert.deepEqual(user.$preloaded, {}) }) - test('serialize relation toJSON', async ({ assert }) => { + test('serialize relation toJSON', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public username: string + declare username: string @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } const user = new User() @@ -2716,22 +3308,27 @@ test.group('Base Model | relations', (group) => { }) }) - test('cherry pick relationship keys during serialize', async ({ assert }) => { + test('cherry pick relationship keys during serialize', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public username: string + declare username: string @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } const user = new User() @@ -2760,28 +3357,33 @@ test.group('Base Model | relations', (group) => { ) }) - test('cherry pick nested relationship keys during serialize', async ({ assert }) => { + test('cherry pick nested relationship keys during serialize', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public username: string + declare username: string @column() - public userId: number + declare userId: number @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public email: string + declare email: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } Profile.$adapter = adapter @@ -2823,22 +3425,27 @@ test.group('Base Model | relations', (group) => { ) }) - test('serialize relation toJSON with custom serializeAs key', async ({ assert }) => { + test('serialize relation toJSON with custom serializeAs key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public username: string + declare username: string @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile, { serializeAs: 'social' }) - public profile: HasOne + declare profile: HasOne } const user = new User() @@ -2854,22 +3461,27 @@ test.group('Base Model | relations', (group) => { }) }) - test('push relationship', async ({ assert }) => { + test('push relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public username: string + declare username: string @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Profile) - public profiles: HasMany + declare profiles: HasMany } const user = new User() @@ -2887,22 +3499,27 @@ test.group('Base Model | relations', (group) => { }) }) - test('push relationship to existing list', async ({ assert }) => { + test('push relationship to existing list', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public username: string + declare username: string @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Profile) - public profiles: HasMany + declare profiles: HasMany } const user = new User() @@ -2924,22 +3541,27 @@ test.group('Base Model | relations', (group) => { }) }) - test('push an array of relationships', async ({ assert }) => { + test('push an array of relationships', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public username: string + declare username: string @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Profile) - public profiles: HasMany + declare profiles: HasMany } const user = new User() @@ -2963,22 +3585,27 @@ test.group('Base Model | relations', (group) => { }) }) - test('raise error when pushing an array of relationships for hasOne', async ({ assert }) => { + test('raise error when pushing an array of relationships for hasOne', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public username: string + declare username: string @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } const user = new User() @@ -2992,22 +3619,27 @@ test.group('Base Model | relations', (group) => { assert.throws(fn, '"User.profile" cannot reference more than one instance of "Profile" model') }) - test('raise error when setting single relationships for hasMany', async ({ assert }) => { + test('raise error when setting single relationships for hasMany', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() const adapter = new FakeAdapter() + + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public username: string + declare username: string @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Profile) - public profiles: HasMany + declare profiles: HasMany } const user = new User() @@ -3023,32 +3655,34 @@ test.group('Base Model | relations', (group) => { test.group('Base Model | fetch', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() - await cleanup() - await fs.cleanup() + await cleanupTables() }) group.each.teardown(async () => { await resetTables() }) - test('find using the primary key', async ({ assert }) => { + test('find using the primary key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -3058,36 +3692,51 @@ test.group('Base Model | fetch', (group) => { assert.equal(user!.$primaryKeyValue, 1) }) - test('raise exception when row is not found', async ({ assert }) => { + test('raise exception when row is not found', async ({ fs, assert }) => { assert.plan(1) + + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string } try { await User.findOrFail(1) } catch ({ message }) { - assert.equal(message, 'E_ROW_NOT_FOUND: Row not found') + assert.equal(message, 'Row not found') } }) - test('find many using the primary key', async ({ assert }) => { + test('find many using the primary key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string } await db @@ -3101,16 +3750,23 @@ test.group('Base Model | fetch', (group) => { assert.equal(users[1].$primaryKeyValue, 1) }) - test('return the existing row when search criteria matches', async ({ assert }) => { + test('return the existing row when search criteria matches', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column({ columnName: 'username' }) - public userName: string + declare userName: string @column() - public email: string + declare email: string } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -3124,16 +3780,23 @@ test.group('Base Model | fetch', (group) => { assert.equal(user!.$primaryKeyValue, 1) }) - test("create new row when search criteria doesn't match", async ({ assert }) => { + test("create new row when search criteria doesn't match", async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column({ columnName: 'username' }) - public userName: string + declare userName: string @column() - public email: string + declare email: string } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -3152,16 +3815,24 @@ test.group('Base Model | fetch', (group) => { test('return the existing row when search criteria matches using firstOrNew', async ({ assert, + fs, }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column({ columnName: 'username' }) - public userName: string + declare userName: string @column() - public email: string + declare email: string } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -3177,16 +3848,24 @@ test.group('Base Model | fetch', (group) => { test("instantiate new row when search criteria doesn't match using firstOrNew", async ({ assert, + fs, }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column({ columnName: 'username' }) - public userName: string + declare userName: string @column() - public email: string + declare email: string } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -3203,19 +3882,26 @@ test.group('Base Model | fetch', (group) => { assert.equal(user!.userName, 'nikk') }) - test('update the existing row when search criteria matches', async ({ assert }) => { + test('update the existing row when search criteria matches', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column({ columnName: 'username' }) - public userName: string + declare userName: string @column() - public email: string + declare email: string @column() - public points: number + declare points: number } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -3230,21 +3916,28 @@ test.group('Base Model | fetch', (group) => { assert.equal(users[0].points, 20) }) - test('lock row for update to handle concurrent requests', async ({ assert }) => { + test('lock row for update to handle concurrent requests', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column({ columnName: 'username' }) - public userName: string + declare userName: string @column() - public email: string + declare email: string @column() - public points: number + declare points: number - public static boot() { + static boot() { if (this.booted) { return } @@ -3281,19 +3974,26 @@ test.group('Base Model | fetch', (group) => { assert.equal(users[0].points, 22) }) - test('execute updateOrCreate update action inside a transaction', async ({ assert }) => { + test('execute updateOrCreate update action inside a transaction', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column({ columnName: 'username' }) - public userName: string + declare userName: string @column() - public email: string + declare email: string @column() - public points: number + declare points: number } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -3314,19 +4014,26 @@ test.group('Base Model | fetch', (group) => { assert.equal(users[0].points, 0) }) - test('create a new row when search criteria fails', async ({ assert }) => { + test('create a new row when search criteria fails', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @column() - public points: number + declare points: number } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -3346,19 +4053,26 @@ test.group('Base Model | fetch', (group) => { assert.equal(users[1].points, 20) }) - test('execute updateOrCreate create action inside a transaction', async ({ assert }) => { + test('execute updateOrCreate create action inside a transaction', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @column() - public points: number + declare points: number } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -3379,19 +4093,26 @@ test.group('Base Model | fetch', (group) => { assert.equal(users[0].points, 0) }) - test('persist records to db when find call returns zero rows', async ({ assert }) => { + test('persist records to db when find call returns zero rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @column() - public points: number + declare points: number } const users = await User.fetchOrCreateMany('username', [ @@ -3426,19 +4147,26 @@ test.group('Base Model | fetch', (group) => { assert.lengthOf(usersList, 3) }) - test('sync records by avoiding duplicates', async ({ assert }) => { + test('sync records by avoiding duplicates', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @column() - public points: number + declare points: number } await db.insertQuery().table('users').insert({ @@ -3482,19 +4210,26 @@ test.group('Base Model | fetch', (group) => { assert.lengthOf(usersList, 3) }) - test('wrap create calls inside a transaction', async ({ assert }) => { + test('wrap create calls inside a transaction', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @column() - public points: number + declare points: number } await db.insertQuery().table('users').insert({ @@ -3531,19 +4266,26 @@ test.group('Base Model | fetch', (group) => { assert.lengthOf(usersList, 1) }) - test('handle columns with different cast key name', async ({ assert }) => { + test('handle columns with different cast key name', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column({ columnName: 'username' }) - public userName: string + declare userName: string @column() - public email: string + declare email: string @column() - public points: number + declare points: number } await db.insertQuery().table('users').insert({ @@ -3587,21 +4329,28 @@ test.group('Base Model | fetch', (group) => { assert.lengthOf(usersList, 3) }) - test('raise exception when one or more rows fails', async ({ assert }) => { + test('raise exception when one or more rows fails', async ({ fs, assert }) => { assert.plan(2) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @column() - public points: number + declare points: number } await db.insertQuery().table('users').insert({ @@ -3640,21 +4389,29 @@ test.group('Base Model | fetch', (group) => { test('raise exception when value of unique key inside payload is undefined', async ({ assert, + fs, }) => { assert.plan(2) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @column() - public points: number + declare points: number } await db.insertQuery().table('users').insert({ @@ -3684,18 +4441,25 @@ test.group('Base Model | fetch', (group) => { assert.lengthOf(usersList, 1) }) - test('raise exception when key is not defined on the model', async ({ assert }) => { + test('raise exception when key is not defined on the model', async ({ fs, assert }) => { assert.plan(2) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public email: string + declare email: string @column() - public points: number + declare points: number } await db.insertQuery().table('users').insert({ @@ -3725,19 +4489,26 @@ test.group('Base Model | fetch', (group) => { assert.lengthOf(usersList, 1) }) - test('persist records to db when find call returns zero rows', async ({ assert }) => { + test('persist records to db when find call returns zero rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @column() - public points: number + declare points: number } const users = await User.updateOrCreateMany('username', [ @@ -3772,19 +4543,26 @@ test.group('Base Model | fetch', (group) => { assert.lengthOf(usersList, 3) }) - test('update records and avoid duplicates', async ({ assert }) => { + test('update records and avoid duplicates', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @column() - public points: number + declare points: number } await db.insertQuery().table('users').insert({ @@ -3829,22 +4607,29 @@ test.group('Base Model | fetch', (group) => { assert.lengthOf(usersList, 3) }) - test('use multiple keys to predicate a row as unique', async ({ assert }) => { + test('use multiple keys to predicate a row as unique', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @column() - public countryId: number + declare countryId: number @column() - public points: number + declare points: number } await db.insertQuery().table('users').insert({ @@ -3895,19 +4680,29 @@ test.group('Base Model | fetch', (group) => { assert.lengthOf(usersList, 4) }) - test('wrap create calls inside a transaction using updateOrCreateMany', async ({ assert }) => { + test('wrap create calls inside a transaction using updateOrCreateMany', async ({ + fs, + assert, + }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @column() - public points: number + declare points: number } await db.insertQuery().table('users').insert({ @@ -3946,19 +4741,27 @@ test.group('Base Model | fetch', (group) => { test('wrap update calls inside a custom transaction using updateOrCreateMany', async ({ assert, + fs, }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @column() - public points: number + declare points: number } await db.insertQuery().table('users').insert({ @@ -3997,21 +4800,28 @@ test.group('Base Model | fetch', (group) => { assert.equal(usersList[0].points, 10) }) - test('handle concurrent update calls using updateOrCreateMany', async ({ assert }) => { + test('handle concurrent update calls using updateOrCreateMany', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @column() - public points: number + declare points: number - public static boot() { + static boot() { if (this.booted) { return } @@ -4052,59 +4862,62 @@ test.group('Base Model | fetch', (group) => { test.group('Base Model | hooks', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() - await cleanup() - await fs.cleanup() + await cleanupTables() }) group.each.teardown(async () => { await resetTables() }) - test('invoke before and after create hooks', async ({ assert }) => { + test('invoke before and after create hooks', async ({ fs, assert }) => { assert.plan(9) + + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + const stack: string[] = [] class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @beforeCreate() - public static beforeCreateHook(model: User) { + static beforeCreateHook(model: User) { stack.push('beforeCreateHook') assert.instanceOf(model, User) assert.isFalse(model.$isPersisted) } @beforeSave() - public static beforeSaveHook(model: User) { + static beforeSaveHook(model: User) { stack.push('beforeSaveHook') assert.instanceOf(model, User) assert.isFalse(model.$isPersisted) } @afterCreate() - public static afterCreateHook(model: User) { + static afterCreateHook(model: User) { stack.push('afterCreateHook') assert.instanceOf(model, User) assert.isTrue(model.$isPersisted) } @afterSave() - public static afterSaveHook(model: User) { + static afterSaveHook(model: User) { stack.push('afterSaveHook') assert.instanceOf(model, User) assert.isTrue(model.$isPersisted) @@ -4114,6 +4927,7 @@ test.group('Base Model | hooks', (group) => { const user = new User() user.username = 'virk' await user.save() + assert.deepEqual(stack, [ 'beforeCreateHook', 'beforeSaveHook', @@ -4122,20 +4936,27 @@ test.group('Base Model | hooks', (group) => { ]) }) - test('abort create when before hook raises exception', async ({ assert }) => { + test('abort create when before hook raises exception', async ({ fs, assert }) => { assert.plan(3) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string - public static boot() { + static boot() { if (this.booted) { return } @@ -4175,21 +4996,28 @@ test.group('Base Model | hooks', (group) => { } }) - test('listen for trx on after save commit', async ({ assert }) => { + test('listen for trx on after save commit', async ({ fs, assert }) => { assert.plan(1) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @afterSave() - public static afterSaveHook(model: User) { + static afterSaveHook(model: User) { if (model.$trx) { model.$trx.on('commit', () => { assert.isTrue(true) @@ -4208,21 +5036,28 @@ test.group('Base Model | hooks', (group) => { await trx.commit() }) - test('listen for trx on after save rollback', async ({ assert }) => { + test('listen for trx on after save rollback', async ({ fs, assert }) => { assert.plan(1) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @afterSave() - public static afterSaveHook(model: User) { + static afterSaveHook(model: User) { if (model.$trx) { model.$trx.on('rollback', () => { assert.isTrue(true) @@ -4241,39 +5076,46 @@ test.group('Base Model | hooks', (group) => { await trx.rollback() }) - test('invoke before and after update hooks', async ({ assert }) => { + test('invoke before and after update hooks', async ({ fs, assert }) => { assert.plan(10) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @beforeUpdate() - public static beforeUpdateHook(model: User) { + static beforeUpdateHook(model: User) { assert.instanceOf(model, User) assert.isTrue(model.$isDirty) } @beforeSave() - public static beforeSaveHook(model: User) { + static beforeSaveHook(model: User) { assert.instanceOf(model, User) assert.isTrue(model.$isDirty) } @afterUpdate() - public static afterUpdateHook(model: User) { + static afterUpdateHook(model: User) { assert.instanceOf(model, User) assert.isFalse(model.$isDirty) } @afterSave() - public static afterSaveHook(model: User) { + static afterSaveHook(model: User) { assert.instanceOf(model, User) assert.isFalse(model.$isDirty) } @@ -4290,20 +5132,27 @@ test.group('Base Model | hooks', (group) => { assert.equal(users[0].username, 'nikk') }) - test('abort update when before hook raises exception', async ({ assert }) => { + test('abort update when before hook raises exception', async ({ fs, assert }) => { assert.plan(5) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string - public static boot() { + static boot() { if (this.booted) { return } @@ -4349,26 +5198,33 @@ test.group('Base Model | hooks', (group) => { assert.equal(users[0].username, 'virk') }) - test('invoke before and after delete hooks', async ({ assert }) => { + test('invoke before and after delete hooks', async ({ fs, assert }) => { assert.plan(3) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @beforeDelete() - public static beforeDeleteHook(model: User) { + static beforeDeleteHook(model: User) { assert.instanceOf(model, User) } @afterDelete() - public static afterDeleteHook(model: User) { + static afterDeleteHook(model: User) { assert.instanceOf(model, User) } } @@ -4381,20 +5237,27 @@ test.group('Base Model | hooks', (group) => { assert.equal(usersCount[0].total, 0) }) - test('abort delete when before hook raises exception', async ({ assert }) => { + test('abort delete when before hook raises exception', async ({ fs, assert }) => { assert.plan(3) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string - public static boot() { + static boot() { if (this.booted) { return } @@ -4425,26 +5288,33 @@ test.group('Base Model | hooks', (group) => { assert.equal(usersCount[0].total, 1) }) - test('invoke before and after fetch hooks', async ({ assert }) => { + test('invoke before and after fetch hooks', async ({ fs, assert }) => { assert.plan(3) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @beforeFetch() - public static beforeFetchHook(query: ModelQueryBuilder) { + static beforeFetchHook(query: ModelQueryBuilder) { assert.instanceOf(query, ModelQueryBuilder) } @afterFetch() - public static afterFetchHook(users: User[]) { + static afterFetchHook(users: User[]) { assert.lengthOf(users, 1) assert.equal(users[0].username, 'virk') } @@ -4454,24 +5324,31 @@ test.group('Base Model | hooks', (group) => { await User.query() }) - test('@regression do not invoke after fetch hooks when updating rows', async () => { + test('@regression do not invoke after fetch hooks when updating rows', async ({ fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @beforeFetch() - public static beforeFetchHook() { + static beforeFetchHook() { throw new Error('Never expected to reach here') } @afterFetch() - public static afterFetchHook() { + static afterFetchHook() { throw new Error('Never expected to reach here') } } @@ -4480,24 +5357,31 @@ test.group('Base Model | hooks', (group) => { await User.query().update({ username: 'nikk' }) }) - test('@regression do not invoke after fetch hooks when deleting rows', async () => { + test('@regression do not invoke after fetch hooks when deleting rows', async ({ fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @beforeFetch() - public static beforeFetchHook() { + static beforeFetchHook() { throw new Error('Never expected to reach here') } @afterFetch() - public static afterFetchHook() { + static afterFetchHook() { throw new Error('Never expected to reach here') } } @@ -4506,26 +5390,33 @@ test.group('Base Model | hooks', (group) => { await User.query().del() }) - test('invoke before and after find hooks', async ({ assert }) => { + test('invoke before and after find hooks', async ({ fs, assert }) => { assert.plan(2) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @beforeFind() - public static beforeFindHook(query: ModelQueryBuilder) { + static beforeFindHook(query: ModelQueryBuilder) { assert.instanceOf(query, ModelQueryBuilder) } @afterFind() - public static afterFindHook(user: User) { + static afterFindHook(user: User) { assert.equal(user.username, 'virk') } } @@ -4534,26 +5425,33 @@ test.group('Base Model | hooks', (group) => { await User.find(1) }) - test('invoke before and after find hooks when .first method is used', async ({ assert }) => { + test('invoke before and after find hooks when .first method is used', async ({ fs, assert }) => { assert.plan(2) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @beforeFind() - public static beforeFindHook(query: ModelQueryBuilder) { + static beforeFindHook(query: ModelQueryBuilder) { assert.instanceOf(query, ModelQueryBuilder) } @afterFind() - public static afterFindHook(user: User) { + static afterFindHook(user: User) { assert.equal(user.username, 'virk') } } @@ -4562,31 +5460,35 @@ test.group('Base Model | hooks', (group) => { await User.query().where('id', 1).first() }) - test('invoke before and after paginate hooks', async ({ assert }) => { + test('invoke before and after paginate hooks', async ({ fs, assert }) => { assert.plan(5) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @beforePaginate() - public static beforePaginateHook([countQuery, query]: [ - ModelQueryBuilder, - ModelQueryBuilder, - ]) { + static beforePaginateHook([countQuery, query]: [ModelQueryBuilder, ModelQueryBuilder]) { assert.instanceOf(query, ModelQueryBuilder) assert.instanceOf(countQuery, ModelQueryBuilder) assert.notDeepEqual(countQuery, query) } @afterPaginate() - public static afterPaginateHook(paginator: SimplePaginator) { + static afterPaginateHook(paginator: SimplePaginator) { assert.equal(paginator.total, 1) assert.equal(paginator.all()[0].username, 'virk') } @@ -4596,26 +5498,33 @@ test.group('Base Model | hooks', (group) => { await User.query().paginate(1) }) - test('invoke before and after fetch hooks on paginate', async ({ assert }) => { + test('invoke before and after fetch hooks on paginate', async ({ fs, assert }) => { assert.plan(2) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @beforeFetch() - public static beforeFetchHook(query: ModelQueryBuilder) { + static beforeFetchHook(query: ModelQueryBuilder) { assert.instanceOf(query, ModelQueryBuilder) } @afterFetch() - public static afterFetchHook(users: User[]) { + static afterFetchHook(users: User[]) { assert.equal(users[0].username, 'virk') } } @@ -4624,24 +5533,31 @@ test.group('Base Model | hooks', (group) => { await User.query().paginate(1) }) - test('do not invoke before and after paginate hooks when using pojo', async () => { + test('do not invoke before and after paginate hooks when using pojo', async ({ fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string @beforePaginate() - public static beforePaginateHook() { + static beforePaginateHook() { throw new Error('Never expected to reached here') } @afterPaginate() - public static afterPaginateHook() { + static afterPaginateHook() { throw new Error('Never expected to reached here') } } @@ -4650,16 +5566,23 @@ test.group('Base Model | hooks', (group) => { await User.query().pojo().paginate(1) }) - test('@regression resolve update keys when an object is passed', async ({ assert }) => { + test('@regression resolve update keys when an object is passed', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column({ columnName: 'username' }) - public theUserName: string + declare theUserName: string @column() - public email: string + declare email: string } await db.table('users').insert({ username: 'virk' }) @@ -4669,16 +5592,26 @@ test.group('Base Model | hooks', (group) => { assert.equal(users[0].username, 'nikk') }) - test('@regression resolve update keys when a key value pair is passed', async ({ assert }) => { + test('@regression resolve update keys when a key value pair is passed', async ({ + fs, + assert, + }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column({ columnName: 'username' }) - public theUserName: string + declare theUserName: string @column() - public email: string + declare email: string } await db.table('users').insert({ username: 'virk' }) @@ -4691,25 +5624,27 @@ test.group('Base Model | hooks', (group) => { test.group('Base model | extend', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() - await cleanup() - await fs.cleanup() + await cleanupTables() }) - test('extend model query builder', async ({ assert }) => { + test('extend model query builder', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() @@ -4729,21 +5664,39 @@ test.group('Base model | extend', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('extend model insert query builder', async ({ assert }) => { + test('extend model insert query builder', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string - public $getQueryFor(_, client) { + $getQueryFor( + action: 'insert', + client: QueryClientContract + ): InsertQueryBuilderContract + $getQueryFor( + action: 'update' | 'delete' | 'refresh', + client: QueryClientContract + ): ModelQueryBuilderContract + $getQueryFor( + _: 'insert' | 'update' | 'delete' | 'refresh', + client: QueryClientContract + ): InsertQueryBuilderContract | ModelQueryBuilderContract { return client.insertQuery().table('users').withId() } } User.boot() - db.InsertQueryBuilder.macro('withId', function () { + db.InsertQueryBuilder.macro('withId', function (this: InsertQueryBuilderContract) { this.knexQuery.returning('id') return this }) @@ -4766,32 +5719,34 @@ test.group('Base model | extend', (group) => { test.group('Base Model | aggregates', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() - await cleanup() - await fs.cleanup() + await cleanupTables() }) group.each.teardown(async () => { await resetTables() }) - test('count *', async ({ assert }) => { + test('count *', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string } await db @@ -4809,16 +5764,23 @@ test.group('Base Model | aggregates', (group) => { ) }) - test('count * distinct', async ({ assert }) => { + test('count * distinct', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string } await db @@ -4839,32 +5801,34 @@ test.group('Base Model | aggregates', (group) => { test.group('Base Model | date', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() - await cleanup() - await fs.cleanup() + await cleanupTables() }) group.each.teardown(async () => { await resetTables() }) - test('define date column', async ({ assert }) => { + test('define date column', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.date() - public dob: DateTime + declare dob: DateTime } assert.deepEqual(User.$getColumn('dob')!.meta, { @@ -4874,16 +5838,23 @@ test.group('Base Model | date', (group) => { }) }) - test('define date column and turn on autoCreate flag', async ({ assert }) => { + test('define date column and turn on autoCreate flag', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.date({ autoCreate: true }) - public dob: DateTime + declare dob: DateTime } assert.deepEqual(User.$getColumn('dob')!.meta, { @@ -4893,16 +5864,23 @@ test.group('Base Model | date', (group) => { }) }) - test('define date column and turn on autoUpdate flag', async ({ assert }) => { + test('define date column and turn on autoUpdate flag', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.date({ autoUpdate: true }) - public dob: DateTime + declare dob: DateTime } assert.deepEqual(User.$getColumn('dob')!.meta, { @@ -4912,26 +5890,31 @@ test.group('Base Model | date', (group) => { }) }) - test('initiate date column values with current date when missing', async ({ assert }) => { + test('initiate date column values with current date when missing', async ({ fs, assert }) => { assert.plan(1) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + const BaseModel = getBaseModel(adapter, app) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.date({ autoCreate: true }) - public dob: DateTime + declare dob: DateTime } const user = new User() User.$adapter = adapter - adapter.on('insert', (model: User) => { - assert.instanceOf(model.dob, DateTime) + + adapter.on('insert', (model: LucidRow, _: any) => { + assert.instanceOf((model as User).dob, DateTime) }) user.username = 'virk' @@ -4940,56 +5923,66 @@ test.group('Base Model | date', (group) => { test('do initiate date column values with current date when autoCreate is off', async ({ assert, + fs, }) => { assert.plan(2) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + const BaseModel = getBaseModel(adapter, app) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.date({ autoCreate: true }) - public dob: DateTime + declare dob: DateTime @column.date() - public createdAt: DateTime + declare createdAt: DateTime } const user = new User() User.$adapter = adapter - adapter.on('insert', (model: User) => { - assert.instanceOf(model.dob, DateTime) - assert.isUndefined(model.createdAt) + + adapter.on('insert', (model: LucidRow, _: any) => { + assert.instanceOf((model as User).dob, DateTime) + assert.isUndefined((model as User).createdAt) }) user.username = 'virk' await user.save() }) - test('always update date column value when autoUpdate is on', async ({ assert }) => { + test('always update date column value when autoUpdate is on', async ({ fs, assert }) => { assert.plan(1) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + const BaseModel = getBaseModel(adapter, app) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.date({ autoUpdate: true }) - public updatedAt: DateTime + declare updatedAt: DateTime } const user = new User() User.$adapter = adapter - adapter.on('update', (model: User) => { - assert.instanceOf(model.updatedAt, DateTime) + adapter.on('update', (model: LucidRow) => { + assert.instanceOf((model as User).updatedAt, DateTime) }) user.username = 'virk' @@ -4999,24 +5992,29 @@ test.group('Base Model | date', (group) => { await user.save() }) - test('format date instance to string before sending to the adapter', async ({ assert }) => { + test('format date instance to string before sending to the adapter', async ({ fs, assert }) => { assert.plan(1) + + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + const BaseModel = getBaseModel(adapter, app) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.date({ autoCreate: true }) - public dob: DateTime + declare dob: DateTime } const user = new User() User.$adapter = adapter - adapter.on('insert', (_: User, attributes) => { + adapter.on('insert', (_: LucidRow, attributes) => { assert.deepEqual(attributes, { username: 'virk', dob: DateTime.local().toISODate() }) }) @@ -5024,24 +6022,29 @@ test.group('Base Model | date', (group) => { await user.save() }) - test('leave date untouched when it is defined as string', async ({ assert }) => { + test('leave date untouched when it is defined as string', async ({ fs, assert }) => { assert.plan(1) + + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + const BaseModel = getBaseModel(adapter, app) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.date() - public dob: DateTime + declare dob: DateTime } const user = new User() User.$adapter = adapter - adapter.on('insert', (_: User, attributes) => { + adapter.on('insert', (_: LucidRow, attributes) => { assert.deepEqual(attributes, { username: 'virk', dob: '2010-11-20' }) }) @@ -5050,24 +6053,29 @@ test.group('Base Model | date', (group) => { await user.save() }) - test('do not attempt to format undefined values', async ({ assert }) => { + test('do not attempt to format undefined values', async ({ fs, assert }) => { assert.plan(1) + + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + const BaseModel = getBaseModel(adapter, app) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.date() - public dob: DateTime + declare dob: DateTime } const user = new User() User.$adapter = adapter - adapter.on('insert', (_: User, attributes) => { + adapter.on('insert', (_: LucidRow, attributes) => { assert.deepEqual(attributes, { username: 'virk' }) }) @@ -5075,20 +6083,24 @@ test.group('Base Model | date', (group) => { await user.save() }) - test('raise error when date column value is unprocessable', async ({ assert }) => { + test('raise error when date column value is unprocessable', async ({ fs, assert }) => { assert.plan(1) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + const BaseModel = getBaseModel(adapter, app) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.date() - public dob: DateTime + declare dob: DateTime } const user = new User() @@ -5099,27 +6111,28 @@ test.group('Base Model | date', (group) => { try { await user.save() } catch ({ message }) { - assert.equal( - message, - 'E_INVALID_DATE_COLUMN_VALUE: The value for "User.dob" must be an instance of "luxon.DateTime"' - ) + assert.equal(message, 'The value for "User.dob" must be an instance of "luxon.DateTime"') } }) - test('raise error when datetime is invalid', async ({ assert }) => { + test('raise error when datetime is invalid', async ({ fs, assert }) => { assert.plan(1) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + const BaseModel = getBaseModel(adapter, app) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.date() - public dob: DateTime + declare dob: DateTime } const user = new User() @@ -5130,31 +6143,36 @@ test.group('Base Model | date', (group) => { try { await user.save() } catch ({ message }) { - assert.equal(message, 'E_INVALID_DATE_COLUMN_VALUE: Invalid value for "User.dob". unparsable') + assert.equal(message, 'Invalid value for "User.dob". unparsable') } }) - test('allow overriding prepare method', async ({ assert }) => { + test('allow overriding prepare method', async ({ fs, assert }) => { assert.plan(1) + + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + const BaseModel = getBaseModel(adapter, app) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.date({ autoCreate: true, prepare: (value: DateTime) => value.toISOWeekDate(), }) - public dob: DateTime + declare dob: DateTime } const user = new User() User.$adapter = adapter - adapter.on('insert', (_: User, attributes) => { + adapter.on('insert', (_, attributes) => { assert.deepEqual(attributes, { username: 'virk', dob: DateTime.local().toISOWeekDate() }) }) @@ -5162,16 +6180,23 @@ test.group('Base Model | date', (group) => { await user.save() }) - test('convert date to datetime instance during fetch', async ({ assert }) => { + test('convert date to datetime instance during fetch', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.date() - public createdAt: DateTime + declare createdAt: DateTime } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -5179,16 +6204,23 @@ test.group('Base Model | date', (group) => { assert.instanceOf(user!.createdAt, DateTime) }) - test('ignore null or empty values during fetch', async ({ assert }) => { + test('ignore null or empty values during fetch', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.date() - public updatedAt: DateTime + declare updatedAt: DateTime } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -5196,16 +6228,23 @@ test.group('Base Model | date', (group) => { assert.isNull(user!.updatedAt) }) - test('convert date to toISODate during serialize', async ({ assert }) => { + test('convert date to toISODate during serialize', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.date() - public createdAt: DateTime + declare createdAt: DateTime } await db.insertQuery().table('users').insert({ @@ -5216,13 +6255,20 @@ test.group('Base Model | date', (group) => { assert.match(user!.toJSON().created_at, /\d{4}-\d{2}-\d{2}/) }) - test('do not attempt to serialize, when already a string', async ({ assert }) => { + test('do not attempt to serialize, when already a string', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.date({ consume: (value) => @@ -5230,7 +6276,7 @@ test.group('Base Model | date', (group) => { ? DateTime.fromSQL(value).minus({ days: 1 }).toISODate() : DateTime.fromJSDate(value).minus({ days: 1 }).toISODate(), }) - public createdAt: DateTime + declare createdAt: DateTime } await db.insertQuery().table('users').insert({ @@ -5244,32 +6290,34 @@ test.group('Base Model | date', (group) => { test.group('Base Model | datetime', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() - await cleanup() - await fs.cleanup() + await cleanupTables() }) group.each.teardown(async () => { await resetTables() }) - test('define datetime column', async ({ assert }) => { + test('define datetime column', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.dateTime() - public dob: DateTime + declare dob: DateTime } assert.deepEqual(User.$getColumn('dob')!.meta, { @@ -5279,16 +6327,23 @@ test.group('Base Model | datetime', (group) => { }) }) - test('define datetime column and turn on autoCreate flag', async ({ assert }) => { + test('define datetime column and turn on autoCreate flag', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.dateTime({ autoCreate: true }) - public dob: DateTime + declare dob: DateTime } assert.deepEqual(User.$getColumn('dob')!.meta, { @@ -5298,16 +6353,23 @@ test.group('Base Model | datetime', (group) => { }) }) - test('define datetime column and turn on autoUpdate flag', async ({ assert }) => { + test('define datetime column and turn on autoUpdate flag', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.dateTime({ autoUpdate: true }) - public dob: DateTime + declare dob: DateTime } assert.deepEqual(User.$getColumn('dob')!.meta, { @@ -5317,16 +6379,23 @@ test.group('Base Model | datetime', (group) => { }) }) - test('initiate datetime column values with current date when missing', async ({ assert }) => { + test('initiate datetime column values with current date when missing', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.dateTime({ autoCreate: true }) - public joinedAt: DateTime + declare joinedAt: DateTime } const user = new User() @@ -5348,25 +6417,29 @@ test.group('Base Model | datetime', (group) => { ) }) - test('ignore undefined values', async ({ assert }) => { + test('ignore undefined values', async ({ fs, assert }) => { assert.plan(1) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + const BaseModel = getBaseModel(adapter, app) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.dateTime() - public dob: DateTime + declare dob: DateTime } const user = new User() User.$adapter = adapter - adapter.on('insert', (_: User, attributes) => { + adapter.on('insert', (_, attributes) => { assert.isUndefined(attributes.dob) }) @@ -5374,25 +6447,29 @@ test.group('Base Model | datetime', (group) => { await user.save() }) - test('ignore string values', async ({ assert }) => { + test('ignore string values', async ({ fs, assert }) => { assert.plan(1) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + const BaseModel = getBaseModel(adapter, app) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.dateTime() - public dob: DateTime + declare dob: DateTime } const user = new User() User.$adapter = adapter - adapter.on('insert', (_: User, attributes) => { + adapter.on('insert', (_, attributes) => { assert.equal(attributes.dob, localTime) }) @@ -5402,20 +6479,24 @@ test.group('Base Model | datetime', (group) => { await user.save() }) - test('raise error when datetime column value is unprocessable', async ({ assert }) => { + test('raise error when datetime column value is unprocessable', async ({ fs, assert }) => { assert.plan(1) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + const BaseModel = getBaseModel(adapter, app) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.dateTime() - public dob: DateTime + declare dob: DateTime } const user = new User() @@ -5426,34 +6507,36 @@ test.group('Base Model | datetime', (group) => { try { await user.save() } catch ({ message }) { - assert.equal( - message, - 'E_INVALID_DATETIME_COLUMN_VALUE: The value for "User.dob" must be an instance of "luxon.DateTime"' - ) + assert.equal(message, 'The value for "User.dob" must be an instance of "luxon.DateTime"') } }) - test('allow overriding prepare method', async ({ assert }) => { + test('allow overriding prepare method', async ({ fs, assert }) => { assert.plan(1) + + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const adapter = new FakeAdapter() + const BaseModel = getBaseModel(adapter, app) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.dateTime({ autoCreate: true, prepare: (value: DateTime) => value.toISOWeekDate(), }) - public dob: DateTime + declare dob: DateTime } const user = new User() User.$adapter = adapter - adapter.on('insert', (_: User, attributes) => { + adapter.on('insert', (_, attributes) => { assert.deepEqual(attributes, { username: 'virk', dob: DateTime.local().toISOWeekDate() }) }) @@ -5461,16 +6544,23 @@ test.group('Base Model | datetime', (group) => { await user.save() }) - test('convert timestamp to datetime instance during fetch', async ({ assert }) => { + test('convert timestamp to datetime instance during fetch', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.dateTime() - public createdAt: DateTime + declare createdAt: DateTime } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -5478,16 +6568,23 @@ test.group('Base Model | datetime', (group) => { assert.instanceOf(user!.createdAt, DateTime) }) - test('ignore null or empty values during fetch', async ({ assert }) => { + test('ignore null or empty values during fetch', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.dateTime() - public updatedAt: DateTime + declare updatedAt: DateTime } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -5495,19 +6592,24 @@ test.group('Base Model | datetime', (group) => { assert.isNull(user!.updatedAt) }) - test('always set datetime value when autoUpdate is true', async ({ assert }) => { + test('always set datetime value when autoUpdate is true', async ({ fs, assert }) => { assert.plan(2) + + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() const adapter = new FakeAdapter() + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.dateTime({ autoCreate: true, autoUpdate: true }) - public joinedAt: DateTime + declare joinedAt: DateTime } User.$adapter = adapter @@ -5524,16 +6626,23 @@ test.group('Base Model | datetime', (group) => { await user.save() }) - test('do not set autoUpdate field datetime when model is not dirty', async ({ assert }) => { + test('do not set autoUpdate field datetime when model is not dirty', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.dateTime({ autoCreate: true, autoUpdate: true }) - public joinedAt: DateTime + declare joinedAt: DateTime } const user = new User() @@ -5545,19 +6654,26 @@ test.group('Base Model | datetime', (group) => { assert.equal(originalDateTimeString, user.joinedAt.toString()) }) - test('set datetime when model is dirty but after invoking a hook', async ({ assert }) => { + test('set datetime when model is dirty but after invoking a hook', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.dateTime({ autoCreate: true, autoUpdate: true }) - public joinedAt: DateTime + declare joinedAt: DateTime @beforeSave() - public static updateUserName(model: User) { + static updateUserName(model: User) { if (!model.$isPersisted) { return } @@ -5576,16 +6692,23 @@ test.group('Base Model | datetime', (group) => { assert.notEqual(originalDateTimeString, user.joinedAt.toString()) }) - test('convert datetime to toISO during serialize', async ({ assert }) => { + test('convert datetime to toISO during serialize', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.dateTime() - public joinedAt: DateTime + declare joinedAt: DateTime } await db @@ -5603,13 +6726,20 @@ test.group('Base Model | datetime', (group) => { ) }) - test('do not attempt to serialize, when already a string', async ({ assert }) => { + test('do not attempt to serialize, when already a string', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.dateTime({ consume: (value) => @@ -5617,7 +6747,7 @@ test.group('Base Model | datetime', (group) => { ? DateTime.fromSQL(value).minus({ days: 1 }).toISODate() : DateTime.fromJSDate(value).minus({ days: 1 }).toISODate(), }) - public joinedAt: DateTime + declare joinedAt: DateTime } await db @@ -5632,16 +6762,23 @@ test.group('Base Model | datetime', (group) => { assert.equal(user!.toJSON().joined_at, DateTime.local().minus({ days: 1 }).toISODate()) }) - test('force update when enabledForceUpdate method is called', async ({ assert }) => { + test('force update when enabledForceUpdate method is called', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column.dateTime({ autoCreate: true, autoUpdate: true }) - public joinedAt: DateTime + declare joinedAt: DateTime } const user = new User() @@ -5657,18 +6794,26 @@ test.group('Base Model | datetime', (group) => { test('force update when enabledForceUpdate method and there are no timestamps', async ({ assert, + fs, }) => { assert.plan(1) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @afterUpdate() - public static afterHook(user: User) { + static afterHook(user: User) { assert.instanceOf(user, User) } } @@ -5683,32 +6828,34 @@ test.group('Base Model | datetime', (group) => { test.group('Base Model | paginate', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() - await cleanup() - await fs.cleanup() + await cleanupTables() }) group.each.teardown(async () => { await resetTables() }) - test('paginate through rows', async ({ assert }) => { + test('paginate through rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string } await db.insertQuery().table('users').multiInsert(getUsers(18)) @@ -5740,16 +6887,23 @@ test.group('Base Model | paginate', (group) => { }) }) - test('serialize from model paginator', async ({ assert }) => { + test('serialize from model paginator', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string } await db.insertQuery().table('users').multiInsert(getUsers(18)) @@ -5778,16 +6932,23 @@ test.group('Base Model | paginate', (group) => { }) }) - test('return simple paginator instance when using pojo', async ({ assert }) => { + test('return simple paginator instance when using pojo', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string } await db.insertQuery().table('users').multiInsert(getUsers(18)) @@ -5819,16 +6980,23 @@ test.group('Base Model | paginate', (group) => { }) }) - test('use model naming strategy for pagination properties', async ({ assert }) => { + test('use model naming strategy for pagination properties', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string } User.namingStrategy = new SnakeCaseNamingStrategy() @@ -5873,16 +7041,23 @@ test.group('Base Model | paginate', (group) => { }) }) - test('use table aliases', async ({ assert }) => { + test('use table aliases', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string } const usersList = getUsers(18) @@ -5923,22 +7098,24 @@ test.group('Base Model | paginate', (group) => { test.group('Base Model | toObject', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() - await cleanup() - await fs.cleanup() + await cleanupTables() }) - test('convert model to its object representation', async ({ assert }) => { + test('convert model to its object representation', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string } const user = new User() @@ -5947,10 +7124,17 @@ test.group('Base Model | toObject', (group) => { assert.deepEqual(user.toObject(), { username: 'virk', $extras: {} }) }) - test('use model property key when converting model to object', async ({ assert }) => { + test('use model property key when converting model to object', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ serializeAs: 'theUserName', columnName: 'user_name' }) - public username: string + declare username: string } const user = new User() @@ -5959,13 +7143,20 @@ test.group('Base Model | toObject', (group) => { assert.deepEqual(user.toObject(), { username: 'virk', $extras: {} }) }) - test('add computed properties to toObject result', async ({ assert }) => { + test('add computed properties to toObject result', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @computed() - public get fullName() { + get fullName() { return this.username.toUpperCase() } } @@ -5976,13 +7167,20 @@ test.group('Base Model | toObject', (group) => { assert.deepEqual(user.toObject(), { username: 'virk', fullName: 'VIRK', $extras: {} }) }) - test('do not add computed property when it returns undefined', async ({ assert }) => { + test('do not add computed property when it returns undefined', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column() - public username: string + declare username: string @computed() - public get fullName() { + get fullName() { return undefined } } @@ -5993,24 +7191,31 @@ test.group('Base Model | toObject', (group) => { assert.deepEqual(user.toObject(), { username: 'virk', $extras: {} }) }) - test('add preloaded hasOne relationship to toObject result', async ({ assert }) => { + test('add preloaded hasOne relationship to toObject result', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public username: string + declare username: string @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } const user = new User() @@ -6026,35 +7231,42 @@ test.group('Base Model | toObject', (group) => { }) }) - test('add preloaded hasMany relationship to toObject result', async ({ assert }) => { + test('add preloaded hasMany relationship to toObject result', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class Comment extends BaseModel { @column() - public body: string + declare body: string @column() - public postId: number + declare postId: number } class Post extends BaseModel { @column() - public title: string + declare title: string @column() - public userId: number + declare userId: number @hasMany(() => Comment) - public comments: HasMany + declare comments: HasMany } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } const user = new User() @@ -6090,29 +7302,31 @@ test.group('Base Model | toObject', (group) => { test.group('Base model | inheritance', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() - await cleanup() - await fs.cleanup() + await cleanupTables() }) - test('inherit primary key from the base model', async ({ assert }) => { + test('inherit primary key from the base model', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class MyBaseModel extends BaseModel { - public static primaryKey = 'user_id' + static primaryKey = 'user_id' } class User extends MyBaseModel { @column() - public username: string + declare username: string @column() - public age: number + declare age: number } MyBaseModel.boot() @@ -6121,19 +7335,26 @@ test.group('Base model | inheritance', (group) => { assert.equal(User.primaryKey, 'user_id') }) - test('use explicitly defined primary key', async ({ assert }) => { + test('use explicitly defined primary key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class MyBaseModel extends BaseModel { - public static primaryKey = 'user_id' + static primaryKey = 'user_id' } class User extends MyBaseModel { - public static primaryKey = 'the_user_id' + static primaryKey = 'the_user_id' @column() - public username: string + declare username: string @column() - public age: number + declare age: number } MyBaseModel.boot() @@ -6142,17 +7363,24 @@ test.group('Base model | inheritance', (group) => { assert.equal(User.primaryKey, 'the_user_id') }) - test('do not inherit table from the base model', async ({ assert }) => { + test('do not inherit table from the base model', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class MyBaseModel extends BaseModel { - public static table = 'foo' + static table = 'foo' } class User extends MyBaseModel { @column() - public username: string + declare username: string @column() - public age: number + declare age: number } MyBaseModel.boot() @@ -6161,18 +7389,25 @@ test.group('Base model | inheritance', (group) => { assert.equal(User.table, 'users') }) - test('inherting a model should copy columns', async ({ assert }) => { + test('inherting a model should copy columns', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class MyBaseModel extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends MyBaseModel { @column() - public username: string + declare username: string @column() - public age: number + declare age: number } MyBaseModel.boot() @@ -6257,21 +7492,28 @@ test.group('Base model | inheritance', (group) => { }) }) - test('allow overwriting column', async ({ assert }) => { + test('allow overwriting column', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class MyBaseModel extends BaseModel { @column({ isPrimary: true }) - public userId: string + declare userId: string } class User extends MyBaseModel { @column({ isPrimary: true, columnName: 'user_uuid' }) - public declare userId: string + declare userId: string @column() - public username: string + declare username: string @column() - public age: number + declare age: number } MyBaseModel.boot() @@ -6356,21 +7598,28 @@ test.group('Base model | inheritance', (group) => { }) }) - test('inherting a model should copy computed properties', async ({ assert }) => { + test('inherting a model should copy computed properties', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class MyBaseModel extends BaseModel { @computed() - public fullName: string + declare fullName: string } class User extends MyBaseModel { @column() - public username: string + declare username: string @column() - public age: number + declare age: number @computed() - public score: number + declare score: number } MyBaseModel.boot() @@ -6451,21 +7700,28 @@ test.group('Base model | inheritance', (group) => { assert.deepEqual(MyBaseModel.$keys.attributesToColumns.all(), {}) }) - test('allow overwriting computed properties', async ({ assert }) => { + test('allow overwriting computed properties', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class MyBaseModel extends BaseModel { @computed() - public fullName: string + declare fullName: string } class User extends MyBaseModel { @column() - public username: string + declare username: string @column() - public age: number + declare age: number @computed({ serializeAs: 'name' }) - public declare fullName: string + declare fullName: string } MyBaseModel.boot() @@ -6539,14 +7795,21 @@ test.group('Base model | inheritance', (group) => { assert.deepEqual(MyBaseModel.$keys.attributesToColumns.all(), {}) }) - test('inherting a model should copy relationships', async ({ assert }) => { + test('inherting a model should copy relationships', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public userId: number + declare userId: number } class Email extends BaseModel { @column() - public userId: number + declare userId: number } Profile.boot() @@ -6554,15 +7817,15 @@ test.group('Base model | inheritance', (group) => { class MyBaseModel extends BaseModel { @column() - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } class User extends MyBaseModel { @hasMany(() => Email) - public emails: HasMany + declare emails: HasMany } MyBaseModel.boot() @@ -6574,23 +7837,30 @@ test.group('Base model | inheritance', (group) => { assert.isFalse(MyBaseModel.$relationsDefinitions.has('emails')) }) - test('overwrite relationship during relationsip', async ({ assert }) => { + test('overwrite relationship during relationsip', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class SocialProfile extends BaseModel { @column() - public socialParentId: number + declare socialParentId: number @column() - public userId: number + declare userId: number } class Profile extends BaseModel { @column() - public userId: number + declare userId: number } class Email extends BaseModel { @column() - public userId: number + declare userId: number } SocialProfile.boot() @@ -6599,18 +7869,18 @@ test.group('Base model | inheritance', (group) => { class MyBaseModel extends BaseModel { @column() - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } class User extends MyBaseModel { @hasMany(() => Email) - public emails: HasMany + declare emails: HasMany @hasOne(() => SocialProfile, { foreignKey: 'socialParentId' }) - public declare profile: HasOne + declare profile: HasOne } MyBaseModel.boot() @@ -6623,15 +7893,22 @@ test.group('Base model | inheritance', (group) => { assert.deepEqual(MyBaseModel.$getRelation('profile').model, MyBaseModel) }) - test('allow overwriting relationships', async ({ assert }) => { + test('allow overwriting relationships', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public userId: number + declare userId: number } class Email extends BaseModel { @column() - public userId: number + declare userId: number } Profile.boot() @@ -6639,20 +7916,20 @@ test.group('Base model | inheritance', (group) => { class MyBaseModel extends BaseModel { @column() - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } class User extends MyBaseModel { @hasOne(() => Profile, { onQuery() {}, }) - public declare profile: HasOne + declare profile: HasOne @hasMany(() => Email) - public emails: HasMany + declare emails: HasMany } MyBaseModel.boot() @@ -6662,16 +7939,22 @@ test.group('Base model | inheritance', (group) => { assert.isTrue(User.$relationsDefinitions.has('profile')) assert.isTrue(MyBaseModel.$relationsDefinitions.has('profile')) assert.isFalse(MyBaseModel.$relationsDefinitions.has('emails')) - assert.isFunction(User.$relationsDefinitions.get('profile')!['onQueryHook']) - assert.isUndefined(MyBaseModel.$relationsDefinitions.get('profile')!['onQueryHook']) + assert.isFunction((User.$relationsDefinitions.get('profile') as any)['onQueryHook']) + assert.isUndefined((MyBaseModel.$relationsDefinitions.get('profile') as any)['onQueryHook']) }) - test('inherting a model should copy hooks', async ({ assert }) => { + test('inherting a model should copy hooks', async ({ fs, assert }) => { function hook1() {} function hook2() {} + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class MyBaseModel extends BaseModel { - public static boot() { + static boot() { const isBooted = MyBaseModel.hasOwnProperty('booted') && MyBaseModel.booted === true super.boot() @@ -6682,7 +7965,7 @@ test.group('Base model | inheritance', (group) => { } class User extends MyBaseModel { - public static boot() { + static boot() { super.boot() this.before('create', hook2) } @@ -6691,9 +7974,9 @@ test.group('Base model | inheritance', (group) => { MyBaseModel.boot() User.boot() - assert.isTrue(User.$hooks.has('before', 'create', hook1)) - assert.isTrue(User.$hooks.has('before', 'create', hook2)) - assert.isTrue(MyBaseModel.$hooks.has('before', 'create', hook1)) - assert.isFalse(MyBaseModel.$hooks.has('before', 'create', hook2)) + assert.isTrue(User.$hooks.has('before:create', hook1)) + assert.isTrue(User.$hooks.has('before:create', hook2)) + assert.isTrue(MyBaseModel.$hooks.has('before:create', hook1)) + assert.isFalse(MyBaseModel.$hooks.has('before:create', hook2)) }) }) From 7af92d95de5f32a966e0aa14015313e3b4ed3d89 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Mon, 18 Sep 2023 16:04:39 +0530 Subject: [PATCH 06/70] refactor: relationships module --- adonis-typings/model.ts | 9 +- adonis-typings/relations.ts | 15 +- src/database/index.ts | 55 +- src/helpers/scope.ts | 19 - src/orm/base_model/index.ts | 50 +- test-helpers/index.ts | 1 + test/orm/adapter.spec.ts | 165 +- ...ons.spec.ts => base_model_options.spec.ts} | 998 +++---- ...gs-to.spec.ts => model_belongs_to.spec.ts} | 976 ++++--- ...as-many.spec.ts => model_has_many.spec.ts} | 1741 +++++++----- ...spec.ts => model_has_many_through.spec.ts} | 1242 ++++---- ...-has-one.spec.ts => model_has_one.spec.ts} | 1261 +++++---- ...any.spec.ts => model_many_to_many.spec.ts} | 2498 +++++++++++------ ...er.spec.ts => model_query_builder.spec.ts} | 231 +- 14 files changed, 5409 insertions(+), 3852 deletions(-) delete mode 100644 src/helpers/scope.ts rename test/orm/{base-model-options.spec.ts => base_model_options.spec.ts} (56%) rename test/orm/{model-belongs-to.spec.ts => model_belongs_to.spec.ts} (65%) rename test/orm/{model-has-many.spec.ts => model_has_many.spec.ts} (74%) rename test/orm/{model-has-many-through.spec.ts => model_has_many_through.spec.ts} (74%) rename test/orm/{model-has-one.spec.ts => model_has_one.spec.ts} (66%) rename test/orm/{model-many-to-many.spec.ts => model_many_to_many.spec.ts} (73%) rename test/orm/{model-query-builder.spec.ts => model_query_builder.spec.ts} (58%) diff --git a/adonis-typings/model.ts b/adonis-typings/model.ts index 2c1726e0..de877857 100644 --- a/adonis-typings/model.ts +++ b/adonis-typings/model.ts @@ -149,9 +149,10 @@ export type CherryPick = { * List of events for which a model will trigger hooks */ export type EventsList = 'save' | 'create' | 'update' | 'delete' | 'fetch' | 'find' | 'paginate' -export type HooksHandler = - | ((data: Data, event: Event) => Promise | void) - | string +export type HooksHandler = ( + data: Data, + event: Event +) => Promise | void /** * ------------------------------------------------------ @@ -854,7 +855,7 @@ export interface LucidModel { $getRelation>>( this: Model, name: Name - ): InstanceType[Name] extends ModelRelations + ): InstanceType[Name] extends ModelRelations ? InstanceType[Name]['client']['relation'] : RelationshipsContract $getRelation(this: Model, name: string): RelationshipsContract diff --git a/adonis-typings/relations.ts b/adonis-typings/relations.ts index 65540327..cd73937c 100644 --- a/adonis-typings/relations.ts +++ b/adonis-typings/relations.ts @@ -281,6 +281,12 @@ export interface BaseRelationContract< readonly serializeAs: string | null readonly booted: boolean readonly model: ParentModel + + foreignKey: string + foreignKeyColumnName: string + localKey: string + localKeyColumnName: string + relatedModel(): RelatedModel boot(): void clone(parent: LucidModel): this @@ -462,6 +468,7 @@ export interface ManyToManyRelationContract< readonly pivotRelatedForeignKey: string readonly pivotTable: string pivotColumns: string[] + relatedKeyColumnName: string /** * Set related models as a relationship on the parent model @@ -529,6 +536,8 @@ export interface HasManyThroughRelationContract< readonly foreignKey: string readonly throughLocalKey: string readonly throughForeignKey: string + throughLocalKeyColumnName: string + throughForeignKeyColumnName: string /** * Set related models as a relationship on the parent model @@ -888,10 +897,8 @@ interface WhereNullPivot { interface WhereInPivot { (K: string, value: StrictValues[]): Builder (K: string[], value: StrictValues[][]): Builder - ( - k: string, - subquery: ChainableContract | ((builder: Builder) => void) | RawBuilderContract | RawQuery - ): Builder + (k: string, callback: (builder: Builder) => void): Builder + (k: string, subquery: ChainableContract | RawBuilderContract | RawQuery): Builder (k: string[], subquery: ChainableContract | RawBuilderContract | RawQuery): Builder } diff --git a/src/database/index.ts b/src/database/index.ts index 895a1073..59c55ce3 100644 --- a/src/database/index.ts +++ b/src/database/index.ts @@ -30,6 +30,7 @@ import { ReferenceBuilder } from './static_builder/reference.js' import { SimplePaginator } from './paginator/simple_paginator.js' import { DatabaseQueryBuilder } from './query_builder/database.js' import { ModelQueryBuilder } from '../orm/query_builder/index.js' +import { LucidModel } from '../../adonis-typings/model.js' /** * Database class exposes the API to manage multiple connections and obtain an instance @@ -77,20 +78,10 @@ export class Database extends Macroable { this.manager = new ConnectionManager(this.logger, this.emitter) this.primaryConnectionName = this.config.connection - this.validateConfig() this.registerConnections() this.findIfHealthChecksAreEnabled() } - /** - * Validate config at runtime - */ - private validateConfig() { - // const validator = new ManagerConfigValidator(this.config, 'database', 'config/database') - // validator.validateDefault('connection') - // validator.validateList('connections', 'connection') - } - /** * Compute whether health check is enabled or not after registering the connections. * There are chances that all pre-registered connections are not using health @@ -188,8 +179,8 @@ export class Database extends Macroable { /** * Returns query builder. Optionally one can define the mode as well */ - query(options?: DatabaseClientOptions) { - return this.connection(this.primaryConnectionName, options).query() + query(options?: DatabaseClientOptions) { + return this.connection(this.primaryConnectionName, options).query() } /** @@ -197,15 +188,15 @@ export class Database extends Macroable { * hence it doesn't matter, since in both `dual` and `write` mode, * the `write` connection is always used. */ - insertQuery(options?: DatabaseClientOptions) { - return this.connection(this.primaryConnectionName, options).insertQuery() + insertQuery(options?: DatabaseClientOptions) { + return this.connection(this.primaryConnectionName, options).insertQuery() } /** * Returns a query builder instance for a given model. */ - modelQuery(model: any, options?: DatabaseClientOptions) { - return this.connection(this.primaryConnectionName, options).modelQuery(model) + modelQuery(model: any, options?: DatabaseClientOptions) { + return this.connection(this.primaryConnectionName, options).modelQuery(model) } /** @@ -213,8 +204,8 @@ export class Database extends Macroable { * defined the `read/write` mode in which to execute the * query */ - rawQuery(sql: string, bindings?: any, options?: DatabaseClientOptions) { - return this.connection(this.primaryConnectionName, options).rawQuery(sql, bindings) + rawQuery(sql: string, bindings?: any, options?: DatabaseClientOptions) { + return this.connection(this.primaryConnectionName, options).rawQuery(sql, bindings) } /** @@ -236,31 +227,37 @@ export class Database extends Macroable { /** * Returns instance of a query builder and selects the table */ - from(table: any) { + from: QueryClientContract['from'] = (table) => { return this.connection().from(table) } /** * Returns insert query builder and selects the table */ - table(table: any) { - return this.connection().table(table) + table(table: any) { + return this.connection().table(table) } /** * Returns a transaction instance on the default * connection */ - transaction( - callback?: - | { isolationLevel?: IsolationLevels } - | ((trx: TransactionClientContract) => Promise), + transaction( + callback: (trx: TransactionClientContract) => Promise, options?: { isolationLevel?: IsolationLevels } - ) { + ): Promise + transaction(options?: { isolationLevel?: IsolationLevels }): Promise + transaction( + callbackOrOptions?: + | ((trx: TransactionClientContract) => Promise) + | { isolationLevel?: IsolationLevels }, + options?: { isolationLevel?: IsolationLevels } + ): Promise { const client = this.connection() - return typeof callback === 'function' - ? client.transaction(callback, options) - : client.transaction(callback) + + return typeof callbackOrOptions === 'function' + ? client.transaction(callbackOrOptions, options) + : client.transaction(callbackOrOptions) } /** diff --git a/src/helpers/scope.ts b/src/helpers/scope.ts deleted file mode 100644 index eb160b1e..00000000 --- a/src/helpers/scope.ts +++ /dev/null @@ -1,19 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -import { LucidModel, QueryScope, QueryScopeCallback } from '../../adonis-typings/model.js' - -/** - * Helper to mark a function as query scope - */ -export function scope>( - callback: Callback -): QueryScope { - return callback as QueryScope -} diff --git a/src/orm/base_model/index.ts b/src/orm/base_model/index.ts index c6c0e80a..29cafd01 100644 --- a/src/orm/base_model/index.ts +++ b/src/orm/base_model/index.ts @@ -33,6 +33,10 @@ import { ModelAssignOptions, ModelAdapterOptions, ModelRelationOptions, + ModelQueryBuilderContract, + ModelPaginatorContract, + QueryScopeCallback, + QueryScope, } from '../../../adonis-typings/model.js' import { @@ -595,17 +599,46 @@ class BaseModelImpl implements LucidRow { /** * Register before hooks */ - static before(event: EventsList, handler: HooksHandler) { + static before( + this: Model, + event: Event, + handler: HooksHandler, Event> + ): void + static before( + this: Model, + event: 'paginate', + handler: HooksHandler< + [ModelQueryBuilderContract, ModelQueryBuilderContract], + 'paginate' + > + ): void + static before( + this: Model, + event: Event, + handler: HooksHandler, Event> + ): void { this.$hooks.add(`before:${event}`, handler) - return this } /** * Register after hooks */ - static after(event: EventsList, handler: HooksHandler) { + static after( + this: Model, + event: 'fetch', + handler: HooksHandler[], 'fetch'> + ): void + static after( + this: Model, + event: 'paginate', + handler: HooksHandler>, 'paginate'> + ): void + static after( + this: Model, + event: Event, + handler: HooksHandler, Event> + ): void { this.$hooks.add(`after:${event}`, handler) - return this } /** @@ -2038,3 +2071,12 @@ class BaseModelImpl implements LucidRow { } export const BaseModel: LucidModel = BaseModelImpl + +/** + * Helper to mark a function as query scope + */ +export function scope>( + callback: Callback +): QueryScope { + return callback as QueryScope +} diff --git a/test-helpers/index.ts b/test-helpers/index.ts index 74087caf..26c8f2f5 100644 --- a/test-helpers/index.ts +++ b/test-helpers/index.ts @@ -419,6 +419,7 @@ export function getDb(eventEmitter?: Emitter) { test?.cleanup(() => { return db.manager.closeAll() }) + return db } diff --git a/test/orm/adapter.spec.ts b/test/orm/adapter.spec.ts index 3347db3f..e30b691b 100644 --- a/test/orm/adapter.spec.ts +++ b/test/orm/adapter.spec.ts @@ -7,50 +7,36 @@ * file that was distributed with this source code. */ -/// - import { test } from '@japa/runner' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -import { column } from '../../src/Orm/Decorators' +import { column } from '../../src/orm/decorators/index.js' -import { - setup, - cleanup, - getDb, - getBaseModel, - ormAdapter, - setupApplication, - fs, -} from '../../test-helpers' - -let db: ReturnType -let BaseModel: ReturnType -let app: ApplicationContract +import { setup, cleanup, getDb, getBaseModel, ormAdapter } from '../../test-helpers/index.js' +import { AppFactory } from '@adonisjs/core/factories/app' test.group('Adapter', (group) => { group.each.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.each.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) - test('make insert call using a model', async ({ assert }) => { + test('make insert call using a model', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() @@ -65,15 +51,21 @@ test.group('Adapter', (group) => { assert.isTrue(user.$isPersisted) }) - test('make update call using a model', async ({ assert }) => { + test('make update call using a model', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() @@ -93,15 +85,21 @@ test.group('Adapter', (group) => { await user.save() }) - test('make delete call using a model', async ({ assert }) => { + test('make delete call using a model', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() @@ -121,15 +119,21 @@ test.group('Adapter', (group) => { assert.lengthOf(users, 0) }) - test('get array of model instances using the all call', async ({ assert }) => { + test('get array of model instances using the all call', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() @@ -151,15 +155,21 @@ test.group('Adapter', (group) => { assert.deepEqual(users[1].$attributes, { id: 1, username: 'virk' }) }) - test('use transaction client set on the model for the insert', async ({ assert }) => { + test('use transaction client set on the model for the insert', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() @@ -181,15 +191,21 @@ test.group('Adapter', (group) => { assert.isTrue(user.$isPersisted) }) - test('do not insert when transaction rollbacks', async ({ assert }) => { + test('do not insert when transaction rollbacks', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() @@ -211,15 +227,21 @@ test.group('Adapter', (group) => { assert.isTrue(user.$isPersisted) }) - test('cleanup old trx event listeners when transaction is updated', async ({ assert }) => { + test('cleanup old trx event listeners when transaction is updated', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() @@ -236,15 +258,21 @@ test.group('Adapter', (group) => { await trx.rollback() }) - test('use transaction client set on the model for the update', async ({ assert }) => { + test('use transaction client set on the model for the update', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() @@ -268,15 +296,21 @@ test.group('Adapter', (group) => { assert.equal(users[0].username, 'virk') }) - test('use transaction client set on the model for the delete', async ({ assert }) => { + test('use transaction client set on the model for the delete', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() @@ -301,15 +335,22 @@ test.group('Adapter', (group) => { test('set primary key value when colun name is different from attribute name', async ({ assert, + fs, }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true, columnName: 'id' }) - public userId: number + declare userId: number @column() - public username: string + declare username: string } User.boot() diff --git a/test/orm/base-model-options.spec.ts b/test/orm/base_model_options.spec.ts similarity index 56% rename from test/orm/base-model-options.spec.ts rename to test/orm/base_model_options.spec.ts index 820cf290..add1aad0 100644 --- a/test/orm/base-model-options.spec.ts +++ b/test/orm/base_model_options.spec.ts @@ -7,13 +7,10 @@ * file that was distributed with this source code. */ -/// - import { test } from '@japa/runner' -import type { HasOne } from '@ioc:Adonis/Lucid/Orm' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' +import type { HasOne } from '../../adonis-typings/relations.js' -import { column, hasOne } from '../../src/Orm/Decorators' +import { column, hasOne } from '../../src/orm/decorators/index.js' import { setup, getDb, @@ -21,41 +18,37 @@ import { ormAdapter, resetTables, getBaseModel, - setupApplication, - fs, -} from '../../test-helpers' - -let db: ReturnType -let BaseModel: ReturnType -let app: ApplicationContract +} from '../../test-helpers/index.js' +import { AppFactory } from '@adonisjs/core/factories/app' test.group('Model options | QueryBuilder', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() - await db.manager.closeAll() }) group.each.teardown(async () => { await resetTables() }) - test('query builder set model options from the query client', async ({ assert }) => { + test('query builder set model options from the query client', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -64,18 +57,23 @@ test.group('Model options | QueryBuilder', (group) => { assert.lengthOf(users, 1) assert.equal(users[0].$options!.connection, 'primary') - assert.deepEqual(users[0].$options!.profiler, app.profiler) }) - test('query builder set model options when only one row is fetched', async ({ assert }) => { + test('query builder set model options when only one row is fetched', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -83,18 +81,23 @@ test.group('Model options | QueryBuilder', (group) => { const user = await User.query().first() assert.equal(user!.$options!.connection, 'primary') - assert.deepEqual(user!.$options!.profiler, app.profiler) }) - test('query builder use transaction when updating rows', async ({ assert }) => { + test('query builder use transaction when updating rows', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -112,15 +115,21 @@ test.group('Model options | QueryBuilder', (group) => { assert.equal(usersFresh[0].username, 'virk') }) - test('cleanup transaction reference after commit or rollback', async ({ assert }) => { + test('cleanup transaction reference after commit or rollback', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -141,68 +150,55 @@ test.group('Model options | QueryBuilder', (group) => { test.group('Model options | Adapter', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() - await db.manager.closeAll() }) group.each.teardown(async () => { await resetTables() }) - test('use correct client when custom connection is defined', async ({ assert }) => { + test('use correct client when custom connection is defined', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } await db.insertQuery().table('users').insert({ username: 'virk' }) const user = await User.query({ connection: 'secondary' }).first() assert.equal(user!.$options!.connection, 'secondary') - assert.deepEqual(user!.$options!.profiler, app.profiler) }) - test('pass profiler to the client when defined explicitly', async ({ assert }) => { - class User extends BaseModel { - public static $table = 'users' - - @column({ isPrimary: true }) - public id: number + test('pass custom client to query builder', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) - @column() - public username: string - } - - await db.insertQuery().table('users').insert({ username: 'virk' }) - const profiler = app.profiler - - const user = await User.query({ profiler }).first() - assert.equal(user!.$options!.connection, 'primary') - assert.deepEqual(user!.$options!.profiler, profiler) - }) - - test('pass custom client to query builder', async ({ assert }) => { class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -213,15 +209,21 @@ test.group('Model options | Adapter', (group) => { assert.equal(user!.$options!.connection, 'primary') }) - test('pass transaction client to query builder', async ({ assert }) => { + test('pass transaction client to query builder', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -236,256 +238,215 @@ test.group('Model options | Adapter', (group) => { test.group('Model options | Model.find', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() - await db.manager.closeAll() }) group.each.teardown(async () => { await resetTables() }) - test('define custom connection', async ({ assert }) => { + test('define custom connection', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } await db.insertQuery().table('users').insert({ username: 'virk' }) const user = await User.find(1, { connection: 'secondary' }) assert.equal(user!.$options!.connection, 'secondary') - assert.deepEqual(user!.$options!.profiler, app.profiler) }) - test('define custom profiler', async ({ assert }) => { - class User extends BaseModel { - public static $table = 'users' - - @column({ isPrimary: true }) - public id: number - - @column() - public username: string - } - - await db.insertQuery().table('users').insert({ username: 'virk' }) - const profiler = app.profiler - - const user = await User.find(1, { profiler }) - assert.deepEqual(user!.$options!.profiler, profiler) - }) + test('define custom query client', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) - test('define custom query client', async ({ assert }) => { class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } await db.insertQuery().table('users').insert({ username: 'virk' }) const client = db.connection() const user = await User.find(1, { client }) - assert.deepEqual(user!.$options!.profiler, client.profiler) assert.deepEqual(user!.$options!.connection, client.connectionName) }) }) test.group('Model options | Model.findOrFail', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() - await db.manager.closeAll() }) group.each.teardown(async () => { await resetTables() }) - test('define custom connection', async ({ assert }) => { + test('define custom connection', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } await db.insertQuery().table('users').insert({ username: 'virk' }) const user = await User.findOrFail(1, { connection: 'secondary' }) assert.equal(user.$options!.connection, 'secondary') - assert.deepEqual(user.$options!.profiler, app.profiler) }) - test('define custom profiler', async ({ assert }) => { - class User extends BaseModel { - public static $table = 'users' - - @column({ isPrimary: true }) - public id: number - - @column() - public username: string - } - - const customDb = getDb(app) - await customDb.insertQuery().table('users').insert({ username: 'virk' }) - const profiler = app.profiler - - const user = await User.findOrFail(1, { profiler }) - assert.deepEqual(user.$options!.profiler, profiler) - - await customDb.manager.closeAll() - }) + test('define custom query client', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) - test('define custom query client', async ({ assert }) => { class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } await db.insertQuery().table('users').insert({ username: 'virk' }) const client = db.connection('secondary') const user = await User.findOrFail(1, { client }) - assert.deepEqual(user.$options!.profiler, client.profiler) assert.deepEqual(user.$options!.connection, client.connectionName) }) }) test.group('Model options | Model.findMany', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() - await db.manager.closeAll() }) group.each.teardown(async () => { await resetTables() }) - test('define custom connection', async ({ assert }) => { + test('define custom connection', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } await db.insertQuery().table('users').insert({ username: 'virk' }) const users = await User.findMany([1], { connection: 'secondary' }) assert.equal(users[0].$options!.connection, 'secondary') - assert.deepEqual(users[0].$options!.profiler, app.profiler) }) - test('define custom profiler', async ({ assert }) => { - class User extends BaseModel { - public static $table = 'users' - - @column({ isPrimary: true }) - public id: number - - @column() - public username: string - } + test('define custom query client', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) - await db.insertQuery().table('users').insert({ username: 'virk' }) - const profiler = app.profiler - - const users = await User.findMany([1], { profiler }) - assert.deepEqual(users[0].$options!.profiler, profiler) - }) - - test('define custom query client', async ({ assert }) => { class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } await db.insertQuery().table('users').insert({ username: 'virk' }) const client = db.connection('secondary') const users = await User.findMany([1], { client }) - assert.deepEqual(users[0].$options!.profiler, client.profiler) assert.deepEqual(users[0].$options!.connection, client.connectionName) }) }) test.group('Model options | Model.firstOrCreate', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() - await db.manager.closeAll() }) group.each.teardown(async () => { await resetTables() }) - test('define custom connection', async ({ assert }) => { + test('define custom connection', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -497,18 +458,23 @@ test.group('Model options | Model.firstOrCreate', (group) => { assert.equal(total[0].total, 1) assert.equal(user.$options!.connection, 'secondary') - assert.deepEqual(user.$options!.profiler, app.profiler) }) - test('define custom connection when search fails', async ({ assert }) => { + test('define custom connection when search fails', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -520,61 +486,23 @@ test.group('Model options | Model.firstOrCreate', (group) => { assert.equal(total[0].total, 2) assert.equal(user.$options!.connection, 'secondary') - assert.deepEqual(user.$options!.profiler, app.profiler) }) - test('define custom profiler', async ({ assert }) => { - class User extends BaseModel { - public static $table = 'users' - - @column({ isPrimary: true }) - public id: number - - @column() - public username: string - } - - await db.insertQuery().table('users').insert({ username: 'virk' }) - const profiler = app.profiler - - const user = await User.firstOrCreate({ username: 'virk' }, undefined, { profiler }) - const total = await db.from('users').count('*', 'total') - - assert.equal(total[0].total, 1) - assert.equal(user.$options!.connection, 'primary') - assert.deepEqual(user.$options!.profiler, profiler) - }) - - test('define custom profiler when search fails', async ({ assert }) => { - class User extends BaseModel { - public static $table = 'users' - - @column({ isPrimary: true }) - public id: number - - @column() - public username: string - } - - await db.insertQuery().table('users').insert({ username: 'virk' }) - const profiler = app.profiler - - const user = await User.firstOrCreate({ username: 'nikk' }, undefined, { profiler }) - const total = await db.from('users').count('*', 'total') - - assert.equal(total[0].total, 2) - assert.deepEqual(user.$options!.profiler, profiler) - }) + test('define custom client', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) - test('define custom client', async ({ assert }) => { class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -584,19 +512,24 @@ test.group('Model options | Model.firstOrCreate', (group) => { const total = await db.from('users').count('*', 'total') assert.equal(total[0].total, 1) - assert.deepEqual(user.$options!.profiler, client.profiler) assert.deepEqual(user.$options!.connection, client.connectionName) }) - test('define custom client when search fails', async ({ assert }) => { + test('define custom client when search fails', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -606,19 +539,24 @@ test.group('Model options | Model.firstOrCreate', (group) => { const total = await db.from('users').count('*', 'total') assert.equal(total[0].total, 2) - assert.deepEqual(user.$options!.profiler, client.profiler) assert.deepEqual(user.$options!.connection, client.connectionName) }) - test('use transaction', async ({ assert }) => { + test('use transaction', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -630,19 +568,24 @@ test.group('Model options | Model.firstOrCreate', (group) => { const total = await db.from('users').count('*', 'total') assert.equal(total[0].total, 1) - assert.deepEqual(user.$options!.profiler, client.profiler) assert.deepEqual(user.$options!.connection, client.connectionName) }) - test('use transaction to save when search fails', async ({ assert }) => { + test('use transaction to save when search fails', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } const client = await db.connection('secondary').transaction() @@ -653,38 +596,38 @@ test.group('Model options | Model.firstOrCreate', (group) => { const total = await db.from('users').count('*', 'total') assert.equal(total[0].total, 0) - assert.deepEqual(user.$options!.profiler, client.profiler) assert.deepEqual(user.$options!.connection, client.connectionName) }) }) test.group('Model options | Model.fetchOrCreateMany', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() - await db.manager.closeAll() }) group.each.teardown(async () => { await resetTables() }) - test('define custom connection', async ({ assert }) => { + test('define custom connection', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -697,18 +640,23 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => { assert.equal(total[0].total, 1) assert.equal(user.$options!.connection, 'secondary') - assert.deepEqual(user.$options!.profiler, app.profiler) }) - test('define custom connection when search fails', async ({ assert }) => { + test('define custom connection when search fails', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } const [user] = await User.fetchOrCreateMany('username', [{ username: 'virk' }], { @@ -719,62 +667,23 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => { assert.equal(total[0].total, 1) assert.equal(user.$options!.connection, 'secondary') - assert.deepEqual(user.$options!.profiler, app.profiler) - }) - - test('define custom profiler', async ({ assert }) => { - class User extends BaseModel { - public static $table = 'users' - - @column({ isPrimary: true }) - public id: number - - @column() - public username: string - } - - await db.insertQuery().table('users').insert({ username: 'virk' }) - const profiler = app.profiler - - const [user] = await User.fetchOrCreateMany('username', [{ username: 'virk' }], { profiler }) - - const total = await db.from('users').count('*', 'total') - - assert.equal(total[0].total, 1) - assert.equal(user.$options!.connection, 'primary') - assert.deepEqual(user.$options!.profiler, profiler) }) - test('define custom profiler when search fails', async ({ assert }) => { - class User extends BaseModel { - public static $table = 'users' - - @column({ isPrimary: true }) - public id: number - - @column() - public username: string - } - - const profiler = app.profiler - const [user] = await User.fetchOrCreateMany('username', [{ username: 'virk' }], { profiler }) - - const total = await db.from('users').count('*', 'total') + test('define custom client', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) - assert.equal(total[0].total, 1) - assert.equal(user.$options!.connection, 'primary') - assert.deepEqual(user.$options!.profiler, profiler) - }) - - test('define custom client', async ({ assert }) => { class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -785,19 +694,24 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => { const total = await db.from('users').count('*', 'total') assert.equal(total[0].total, 1) - assert.deepEqual(user.$options!.profiler, client.profiler) assert.deepEqual(user.$options!.connection, client.connectionName) }) - test('define custom client when search fails', async ({ assert }) => { + test('define custom client when search fails', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } const client = db.connection('secondary') @@ -807,24 +721,29 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => { const total = await db.from('users').count('*', 'total') assert.equal(total[0].total, 1) - assert.deepEqual(user.$options!.profiler, client.profiler) assert.deepEqual(user.$options!.connection, client.connectionName) }) - test('wrap create many calls inside a transaction', async ({ assert }) => { + test('wrap create many calls inside a transaction', async ({ assert, fs }) => { assert.plan(2) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string } try { @@ -841,18 +760,24 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => { assert.equal(total[0].total, 0) }) - test('use existing transaction when passed', async ({ assert }) => { + test('use existing transaction when passed', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string } const trx = await db.transaction() @@ -874,31 +799,32 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => { test.group('Model options | Model.updateOrCreateMany', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() - await db.manager.closeAll() }) group.each.teardown(async () => { await resetTables() }) - test('define custom connection', async ({ assert }) => { + test('define custom connection', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -911,19 +837,24 @@ test.group('Model options | Model.updateOrCreateMany', (group) => { assert.equal(total[0].total, 1) assert.equal(user.$options!.connection, 'secondary') - assert.isDefined(user.$options!.profiler) assert.isUndefined(user.$trx) }) - test('define custom connection when search fails', async ({ assert }) => { + test('define custom connection when search fails', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } const [user] = await User.updateOrCreateMany('username', [{ username: 'virk' }], { @@ -934,78 +865,24 @@ test.group('Model options | Model.updateOrCreateMany', (group) => { assert.equal(total[0].total, 1) assert.equal(user.$options!.connection, 'secondary') - assert.isDefined(user.$options!.profiler) - assert.isUndefined(user.$trx) - }) - - test('define custom profiler', async ({ assert }) => { - assert.plan(4) - - class User extends BaseModel { - public static $table = 'users' - - @column({ isPrimary: true }) - public id: number - - @column() - public username: string - } - - await db.insertQuery().table('users').insert({ username: 'virk' }) - const profiler = app.profiler - const originalCreate = profiler.create.bind(profiler) - profiler.create = function (label): any { - assert.equal(label, 'trx:begin') - return originalCreate(label) - } - - const [user] = await User.updateOrCreateMany('username', [{ username: 'virk' }], { profiler }) - - const total = await db.from('users').count('*', 'total') - - assert.equal(total[0].total, 1) - assert.equal(user.$options!.connection, 'primary') assert.isUndefined(user.$trx) }) - test('define custom profiler when search fails', async ({ assert }) => { - assert.plan(4) + test('define custom client', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string - } - - const profiler = app.profiler - const originalCreate = profiler.create.bind(profiler) - profiler.create = function (label): any { - assert.equal(label, 'trx:begin') - return originalCreate(label) - } - - const [user] = await User.updateOrCreateMany('username', [{ username: 'virk' }], { profiler }) - - const total = await db.from('users').count('*', 'total') - - assert.equal(total[0].total, 1) - assert.equal(user.$options!.connection, 'primary') - assert.isUndefined(user.$trx) - }) - - test('define custom client', async ({ assert }) => { - class User extends BaseModel { - public static $table = 'users' - - @column({ isPrimary: true }) - public id: number - - @column() - public username: string + declare username: string } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -1016,19 +893,24 @@ test.group('Model options | Model.updateOrCreateMany', (group) => { const total = await db.from('users').count('*', 'total') assert.equal(total[0].total, 1) - assert.isDefined(user.$options!.profiler) assert.deepEqual(user.$options!.connection, client.connectionName) }) - test('define custom client when search fails', async ({ assert }) => { + test('define custom client when search fails', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } const client = db.connection('secondary') @@ -1038,24 +920,29 @@ test.group('Model options | Model.updateOrCreateMany', (group) => { const total = await db.from('users').count('*', 'total') assert.equal(total[0].total, 1) - assert.isDefined(user.$options!.profiler) assert.deepEqual(user.$options!.connection, client.connectionName) }) - test('wrap update many calls inside a transaction', async ({ assert }) => { + test('wrap update many calls inside a transaction', async ({ assert, fs }) => { assert.plan(2) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string } try { @@ -1072,18 +959,24 @@ test.group('Model options | Model.updateOrCreateMany', (group) => { assert.equal(total[0].total, 0) }) - test('use existing transaction when passed', async ({ assert }) => { + test('use existing transaction when passed', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { - public static $table = 'users' + static$table = 'users' @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public email: string + declare email: string } const trx = await db.transaction() @@ -1105,43 +998,44 @@ test.group('Model options | Model.updateOrCreateMany', (group) => { test.group('Model options | Query Builder Preloads', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() - await db.manager.closeAll() }) group.each.teardown(async () => { await resetTables() }) - test('pass query options to preloaded models', async ({ assert }) => { + test('pass query options to preloaded models', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -1151,33 +1045,36 @@ test.group('Model options | Query Builder Preloads', (group) => { assert.lengthOf(users, 1) assert.equal(users[0].$options!.connection, 'secondary') - assert.deepEqual(users[0].$options!.profiler, app.profiler) - assert.equal(users[0].profile.$options!.connection, 'secondary') - assert.deepEqual(users[0].profile.$options!.profiler, app.profiler) }) - test('use transaction client to execute preload queries', async ({ assert }) => { + test('use transaction client to execute preload queries', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -1190,71 +1087,36 @@ test.group('Model options | Query Builder Preloads', (group) => { assert.lengthOf(users, 1) assert.equal(users[0].$options!.connection, 'primary') - assert.deepEqual(users[0].$options!.profiler, trx.profiler) - assert.equal(users[0].profile.$options!.connection, 'primary') - assert.deepEqual(users[0].profile.$options!.profiler, trx.profiler) }) - test('pass profiler to preload models', async ({ assert }) => { - class Profile extends BaseModel { - @column({ isPrimary: true }) - public id: number + test('pass sideloaded data to preloads', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) - @column() - public userId: number - - @column() - public displayName: string - } - - class User extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @column() - public username: string - - @hasOne(() => Profile) - public profile: HasOne - } - - await db.insertQuery().table('users').insert({ username: 'virk' }) - await db.insertQuery().table('profiles').insert({ user_id: 1, display_name: 'Virk' }) - - const profiler = app.profiler - const users = await User.query({ profiler }).preload('profile').exec() - - assert.lengthOf(users, 1) - - assert.equal(users[0].$options!.connection, 'primary') - assert.deepEqual(users[0].$options!.profiler, profiler) - - assert.equal(users[0].profile.$options!.connection, 'primary') - assert.deepEqual(users[0].profile.$options!.profiler, profiler) - }) - - test('pass sideloaded data to preloads', async ({ assert }) => { class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -1269,27 +1131,33 @@ test.group('Model options | Query Builder Preloads', (group) => { assert.deepEqual(users[0].profile.$sideloaded, { id: 1 }) }) - test('custom sideloaded data on preload query must win', async ({ assert }) => { + test('custom sideloaded data on preload query must win', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -1309,27 +1177,33 @@ test.group('Model options | Query Builder Preloads', (group) => { assert.deepEqual(users[0].profile.$sideloaded, { id: 2 }) }) - test('use transaction client to update preloaded rows', async ({ assert }) => { + test('use transaction client to update preloaded rows', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -1350,27 +1224,33 @@ test.group('Model options | Query Builder Preloads', (group) => { assert.equal(profiles[0].displayName, 'Virk') }) - test('cleanup transaction reference after commit or rollback', async ({ assert }) => { + test('cleanup transaction reference after commit or rollback', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -1396,43 +1276,44 @@ test.group('Model options | Query Builder Preloads', (group) => { test.group('Model options | Model Preloads', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { await cleanup() - await fs.cleanup() - await db.manager.closeAll() }) group.each.teardown(async () => { await resetTables() }) - test('pass query options to preloaded models', async ({ assert }) => { + test('pass query options to preloaded models', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -1444,68 +1325,35 @@ test.group('Model options | Model Preloads', (group) => { await user.load('profile') assert.equal(user.profile.$options!.connection, 'secondary') - assert.deepEqual(user.profile.$options!.profiler, app.profiler) }) - test('pass profiler to preload models', async ({ assert }) => { - class Profile extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @column() - public userId: number - - @column() - public displayName: string - } - - class User extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @column() - public username: string - - @hasOne(() => Profile) - public profile: HasOne - } - - await db.insertQuery().table('users').insert({ username: 'virk' }) - await db.insertQuery().table('profiles').insert({ user_id: 1, display_name: 'Virk' }) - - const profiler = app.profiler - const user = await User.query({ profiler }).firstOrFail() + test('pass sideloaded data to preloads', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) - assert.equal(user.$options!.connection, 'primary') - assert.deepEqual(user.$options!.profiler, profiler) - - await user.load('profile') - - assert.equal(user.profile.$options!.connection, 'primary') - assert.deepEqual(user.profile.$options!.profiler, profiler) - }) - - test('pass sideloaded data to preloads', async ({ assert }) => { class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -1518,27 +1366,33 @@ test.group('Model options | Model Preloads', (group) => { assert.deepEqual(user.profile.$sideloaded, { id: 1 }) }) - test('custom sideloaded data on preload query must win', async ({ assert }) => { + test('custom sideloaded data on preload query must win', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db.insertQuery().table('users').insert({ username: 'virk' }) diff --git a/test/orm/model-belongs-to.spec.ts b/test/orm/model_belongs_to.spec.ts similarity index 65% rename from test/orm/model-belongs-to.spec.ts rename to test/orm/model_belongs_to.spec.ts index 981f330f..722419cb 100644 --- a/test/orm/model-belongs-to.spec.ts +++ b/test/orm/model_belongs_to.spec.ts @@ -7,15 +7,12 @@ * file that was distributed with this source code. */ -/// - import { test } from '@japa/runner' -import type { BelongsTo } from '@ioc:Adonis/Lucid/Orm' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' +import type { BelongsTo } from '../../adonis-typings/relations.js' +import { scope } from '../../src/orm/base_model/index.js' -import { scope } from '../../src/Helpers/scope' -import { column, belongsTo } from '../../src/Orm/Decorators' -import { BelongsToQueryBuilder } from '../../src/Orm/Relations/BelongsTo/QueryBuilder' +import { column, belongsTo } from '../../src/orm/decorators/index.js' +import { BelongsToQueryBuilder } from '../../src/orm/relations/belongs_to/query_builder.js' import { ormAdapter, getBaseModel, @@ -23,64 +20,63 @@ import { cleanup, resetTables, getDb, - setupApplication, - fs, -} from '../../test-helpers' - -let db: ReturnType -let app: ApplicationContract -let BaseModel: ReturnType +} from '../../test-helpers/index.js' +import { AppFactory } from '@adonisjs/core/factories/app' test.group('Model | BelongsTo | Options', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) - test('raise error when localKey is missing', ({ assert }) => { + test('raise error when localKey is missing', async ({ fs, assert }) => { assert.plan(1) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + try { class User extends BaseModel {} User.boot() class Profile extends BaseModel { @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } Profile.boot() Profile.$getRelation('user')!.boot() } catch ({ message }) { - assert.equal( - message, - 'E_MISSING_MODEL_ATTRIBUTE: "Profile.user" expects "id" to exist on "User" model, but is missing' - ) + assert.equal(message, '"Profile.user" expects "id" to exist on "User" model, but is missing') } }) - test('raise error when foreignKey is missing', ({ assert }) => { + test('raise error when foreignKey is missing', async ({ fs, assert }) => { assert.plan(1) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + try { class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } User.boot() class Profile extends BaseModel { @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } Profile.boot() @@ -88,23 +84,29 @@ test.group('Model | BelongsTo | Options', (group) => { } catch ({ message }) { assert.equal( message, - 'E_MISSING_MODEL_ATTRIBUTE: "Profile.user" expects "userId" to exist on "Profile" model, but is missing' + '"Profile.user" expects "userId" to exist on "Profile" model, but is missing' ) } }) - test('use primary key is as the local key', ({ assert }) => { + test('use primary key is as the local key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } Profile.$getRelation('user')!.boot() @@ -112,21 +114,27 @@ test.group('Model | BelongsTo | Options', (group) => { assert.equal(Profile.$getRelation('user')!['localKey'], 'id') }) - test('use custom defined local key', ({ assert }) => { + test('use custom defined local key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column({ columnName: 'user_uid' }) - public uid: number + declare uid: number } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @belongsTo(() => User, { localKey: 'uid' }) - public user: BelongsTo + declare user: BelongsTo } Profile.$getRelation('user')!.boot() @@ -134,37 +142,49 @@ test.group('Model | BelongsTo | Options', (group) => { assert.equal(Profile.$getRelation('user')!['localKey'], 'uid') }) - test('compute foreign key from model name and primary key', ({ assert }) => { + test('compute foreign key from model name and primary key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } Profile.$getRelation('user')!.boot() - assert.equal(Profile.$getRelation('user')!['foreignKey'], 'userId') + assert.equal(Profile.$getRelation('user')['foreignKey'], 'userId') }) - test('use pre defined foreign key', ({ assert }) => { + test('use pre defined foreign key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column({ columnName: 'user_id' }) - public userUid: number + declare userUid: number @belongsTo(() => User, { foreignKey: 'userUid' }) - public user: BelongsTo + declare user: BelongsTo } Profile.$getRelation('user')!.boot() @@ -172,18 +192,24 @@ test.group('Model | BelongsTo | Options', (group) => { assert.equal(Profile.$getRelation('user')!['foreignKey'], 'userUid') }) - test('clone relationship instance with options', ({ assert }) => { + test('clone relationship instance with options', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class BaseProfile extends BaseModel { @column({ columnName: 'user_id' }) - public userUid: number + declare userUid: number @belongsTo(() => User, { foreignKey: 'userUid' }) - public user: BelongsTo + declare user: BelongsTo } class Profile extends BaseProfile {} @@ -199,30 +225,31 @@ test.group('Model | BelongsTo | Options', (group) => { test.group('Model | BelongsTo | Set Relations', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) - test('set related model instance', ({ assert }) => { + test('set related model instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } Profile.$getRelation('user')!.boot() @@ -237,18 +264,24 @@ test.group('Model | BelongsTo | Set Relations', (group) => { assert.deepEqual(profile.user, user) }) - test('push related model instance', ({ assert }) => { + test('push related model instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } Profile.$getRelation('user')!.boot() @@ -270,18 +303,24 @@ test.group('Model | BelongsTo | Set Relations', (group) => { assert.deepEqual(profile.user, user1) }) - test('set many of related instances', ({ assert }) => { + test('set many of related instances', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } Profile.$getRelation('user')!.boot() @@ -310,34 +349,35 @@ test.group('Model | BelongsTo | Set Relations', (group) => { test.group('Model | BelongsTo | bulk operations', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('generate correct sql for selecting related rows', async ({ assert }) => { + test('generate correct sql for selecting related rows', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } await db.table('profiles').insert({ user_id: 4, display_name: 'Hvirk' }) @@ -357,18 +397,24 @@ test.group('Model | BelongsTo | bulk operations', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('generate correct sql for selecting many related rows', async ({ assert }) => { + test('generate correct sql for selecting many related rows', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } await db.table('profiles').multiInsert([ @@ -393,18 +439,24 @@ test.group('Model | BelongsTo | bulk operations', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('generate correct sql for updating related row', async ({ assert }) => { + test('generate correct sql for updating related row', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } await db.table('profiles').insert({ user_id: 2, display_name: 'virk' }) @@ -430,18 +482,24 @@ test.group('Model | BelongsTo | bulk operations', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('generate correct sql for deleting related row', async ({ assert }) => { + test('generate correct sql for deleting related row', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } await db.table('profiles').insert({ user_id: 2, display_name: 'virk' }) @@ -464,43 +522,44 @@ test.group('Model | BelongsTo | bulk operations', (group) => { test.group('Model | BelongsTo | sub queries', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('generate correct sub query for selecting rows', async ({ assert }) => { + test('generate correct sub query for selecting rows', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } Profile.boot() @@ -518,27 +577,33 @@ test.group('Model | BelongsTo | sub queries', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('create aggregate query', async ({ assert }) => { + test('create aggregate query', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } Profile.boot() @@ -561,27 +626,33 @@ test.group('Model | BelongsTo | sub queries', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('allow selecting custom columns', async ({ assert }) => { + test('allow selecting custom columns', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } Profile.boot() @@ -604,19 +675,25 @@ test.group('Model | BelongsTo | sub queries', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('generate correct self relationship subquery', async ({ assert }) => { + test('generate correct self relationship subquery', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public username: string + declare username: string @belongsTo(() => User) - public child: BelongsTo + declare child: BelongsTo } User.boot() @@ -639,27 +716,33 @@ test.group('Model | BelongsTo | sub queries', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('raise exception when trying to execute the query', async ({ assert }) => { + test('raise exception when trying to execute the query', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } Profile.boot() @@ -681,32 +764,38 @@ test.group('Model | BelongsTo | sub queries', (group) => { assert.throws(firstOrFail, 'Cannot execute relationship subqueries') }) - test('run onQuery method when defined', async ({ assert }) => { + test('run onQuery method when defined', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User, { onQuery: (query) => query.where('isActive', false), }) - public user: BelongsTo + declare user: BelongsTo } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public isActive: boolean + declare isActive: boolean @column() - public username: string + declare username: string } Profile.boot() @@ -730,34 +819,35 @@ test.group('Model | BelongsTo | sub queries', (group) => { test.group('Model | BelongsTo | preload', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('preload relationship', async ({ assert }) => { + test('preload relationship', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -771,18 +861,24 @@ test.group('Model | BelongsTo | preload', (group) => { assert.equal(profiles[0].user.id, profiles[0].userId) }) - test('set property value to null when no preload rows were found', async ({ assert }) => { + test('set property value to null when no preload rows were found', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } await db.insertQuery().table('profiles').insert({ display_name: 'Hvirk', user_id: null }) @@ -795,18 +891,24 @@ test.group('Model | BelongsTo | preload', (group) => { assert.isNull(profiles[0].user) }) - test('set value to null when serializing', async ({ assert }) => { + test('set value to null when serializing', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } await db.insertQuery().table('profiles').insert({ display_name: 'Hvirk', user_id: null }) @@ -819,18 +921,24 @@ test.group('Model | BelongsTo | preload', (group) => { assert.isNull(profiles[0].toJSON().user) }) - test('preload relationship for many rows', async ({ assert }) => { + test('preload relationship for many rows', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -856,18 +964,24 @@ test.group('Model | BelongsTo | preload', (group) => { assert.equal(profiles[1].user.id, profiles[1].userId) }) - test('add runtime constraints to related query', async ({ assert }) => { + test('add runtime constraints to related query', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -895,21 +1009,27 @@ test.group('Model | BelongsTo | preload', (group) => { assert.isNull(profiles[1].user) }) - test('cherry pick columns during preload', async ({ assert }) => { + test('cherry pick columns during preload', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -938,21 +1058,27 @@ test.group('Model | BelongsTo | preload', (group) => { assert.deepEqual(profiles[1].user.$extras, {}) }) - test('do not repeat fk when already defined', async ({ assert }) => { + test('do not repeat fk when already defined', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -981,23 +1107,29 @@ test.group('Model | BelongsTo | preload', (group) => { assert.deepEqual(profiles[1].user.$extras, {}) }) - test('raise exception when local key is not selected', async ({ assert }) => { + test('raise exception when local key is not selected', async ({ assert, fs }) => { assert.plan(1) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -1030,24 +1162,30 @@ test.group('Model | BelongsTo | preload', (group) => { } }) - test('preload using model instance', async ({ assert }) => { + test('preload using model instance', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } await db @@ -1077,38 +1215,44 @@ test.group('Model | BelongsTo | preload', (group) => { assert.equal(profile.user.id, profile.userId) }) - test('preload nested relations', async ({ assert }) => { + test('preload nested relations', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } class Identity extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public profileId: number + declare profileId: number @column() - public identityName: string + declare identityName: string @belongsTo(() => Profile) - public profile: BelongsTo + declare profile: BelongsTo } await db @@ -1152,38 +1296,44 @@ test.group('Model | BelongsTo | preload', (group) => { assert.instanceOf(identity!.profile!.user, User) }) - test('preload nested relations using model instance', async ({ assert }) => { + test('preload nested relations using model instance', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } class Identity extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public profileId: number + declare profileId: number @column() - public identityName: string + declare identityName: string @belongsTo(() => Profile) - public profile: BelongsTo + declare profile: BelongsTo } await db @@ -1227,38 +1377,44 @@ test.group('Model | BelongsTo | preload', (group) => { assert.instanceOf(identity!.profile!.user, User) }) - test('pass main query options down the chain', async ({ assert }) => { + test('pass main query options down the chain', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } class Identity extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public profileId: number + declare profileId: number @column() - public identityName: string + declare identityName: string @belongsTo(() => Profile) - public profile: BelongsTo + declare profile: BelongsTo } await db @@ -1305,55 +1461,24 @@ test.group('Model | BelongsTo | preload', (group) => { assert.equal(identity!.profile.$options!.connection, 'secondary') assert.equal(identity!.profile.user.$options!.connection, 'secondary') }) + test('work fine when foreign key is null', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) - test('pass relationship metadata to the profiler', async ({ assert }) => { - assert.plan(1) - - class User extends BaseModel { - @column({ isPrimary: true }) - public id: number - } - - class Profile extends BaseModel { - @column() - public userId: number - - @belongsTo(() => User) - public user: BelongsTo - } - - const profiler = app.profiler - - let profilerPacketIndex = 0 - - profiler.process((packet) => { - profilerPacketIndex++ - if (profilerPacketIndex === 4) { - assert.deepEqual(packet.data.relation, { - model: 'Profile', - relatedModel: 'User', - type: 'belongsTo', - }) - } - }) - - await db.insertQuery().table('users').insert({ username: 'virk' }) - await db.insertQuery().table('profiles').insert({ display_name: 'Hvirk', user_id: 1 }) - await Profile.query({ profiler }).preload('user') - }) - - test('work fine when foreign key is null', async ({ assert }) => { class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } await db.insertQuery().table('profiles').insert({ display_name: 'Hvirk', user_id: null }) @@ -1366,18 +1491,24 @@ test.group('Model | BelongsTo | preload', (group) => { assert.isNull(profiles[0].user) }) - test('work fine during lazy load when foreign key is null', async ({ assert }) => { + test('work fine during lazy load when foreign key is null', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } await db.insertQuery().table('profiles').insert({ display_name: 'Hvirk', user_id: null }) @@ -1391,18 +1522,24 @@ test.group('Model | BelongsTo | preload', (group) => { assert.isNull(profiles[0].user) }) - test('do not run preload query when parent rows are empty', async ({ assert }) => { + test('do not run preload query when parent rows are empty', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } Profile.boot() @@ -1416,34 +1553,35 @@ test.group('Model | BelongsTo | preload', (group) => { test.group('Model | BelongsTo | withCount', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('get count of a relationship rows', async ({ assert }) => { + test('get count of a relationship rows', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -1457,21 +1595,27 @@ test.group('Model | BelongsTo | withCount', (group) => { assert.equal(profiles[0].$extras.user_count, 1) }) - test('allow cherry picking columns', async ({ assert }) => { + test('allow cherry picking columns', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -1485,21 +1629,27 @@ test.group('Model | BelongsTo | withCount', (group) => { assert.deepEqual(profiles[0].$attributes, { displayName: 'Hvirk' }) }) - test('lazy load relationship row', async ({ assert }) => { + test('lazy load relationship row', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } await db.insertQuery().table('users').insert({ username: 'virk' }) @@ -1516,34 +1666,35 @@ test.group('Model | BelongsTo | withCount', (group) => { test.group('Model | BelongsTo | has', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('limit rows to the existance of relationship', async ({ assert }) => { + test('limit rows to the existance of relationship', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } await db @@ -1565,37 +1716,38 @@ test.group('Model | BelongsTo | has', (group) => { test.group('Model | BelongsTo | whereHas', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('limit rows to the existance of relationship', async ({ assert }) => { + test('limit rows to the existance of relationship', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } await db @@ -1632,40 +1784,41 @@ test.group('Model | BelongsTo | whereHas', (group) => { test.group('Model | BelongsTo | associate', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('associate related instance', async ({ assert }) => { + test('associate related instance', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } const user = new User() @@ -1684,26 +1837,32 @@ test.group('Model | BelongsTo | associate', (group) => { assert.equal(profiles[0].user_id, user.id) }) - test('wrap associate call inside transaction', async ({ assert }) => { + test('wrap associate call inside transaction', async ({ assert, fs }) => { assert.plan(3) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } const user = new User() @@ -1726,43 +1885,44 @@ test.group('Model | BelongsTo | associate', (group) => { test.group('Model | BelongsTo | dissociate', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('dissociate relation', async ({ assert }) => { + test('dissociate relation', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } class Profile extends BaseModel { @column() - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } const [row] = await db @@ -1787,36 +1947,37 @@ test.group('Model | BelongsTo | dissociate', (group) => { test.group('Model | BelongsTo | bulk operations', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('disallow pagination', async ({ assert }) => { + test('disallow pagination', async ({ assert, fs }) => { assert.plan(1) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class Profile extends BaseModel { @column() - public userId: number + declare userId: number @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } await db.table('profiles').insert({ user_id: 4, display_name: 'Hvirk' }) @@ -1832,41 +1993,42 @@ test.group('Model | BelongsTo | bulk operations', (group) => { test.group('Model | BelongsTo | clone', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('clone related query builder', async ({ assert }) => { + test('clone related query builder', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() class Profile extends BaseModel { @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } Profile.boot() @@ -1882,31 +2044,32 @@ test.group('Model | BelongsTo | clone', (group) => { test.group('Model | BelongsTo | scopes', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('apply scopes during eagerload', async ({ assert }) => { + test('apply scopes during eagerload', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string - public static fromCountry = scope((query, countryId) => { + static fromCountry = scope((query, countryId) => { query.where('country_id', countryId) }) } @@ -1914,13 +2077,13 @@ test.group('Model | BelongsTo | scopes', (group) => { class Profile extends BaseModel { @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } Profile.boot() @@ -1938,15 +2101,21 @@ test.group('Model | BelongsTo | scopes', (group) => { assert.instanceOf(profileWithoutScope?.user, User) }) - test('apply scopes on related query', async ({ assert }) => { + test('apply scopes on related query', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string - public static fromCountry = scope((query, countryId) => { + static fromCountry = scope((query, countryId) => { query.where('country_id', countryId) }) } @@ -1954,13 +2123,13 @@ test.group('Model | BelongsTo | scopes', (group) => { class Profile extends BaseModel { @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } Profile.boot() @@ -1984,45 +2153,46 @@ test.group('Model | BelongsTo | scopes', (group) => { test.group('Model | BelongsTo | onQuery', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('invoke onQuery method when preloading relationship', async ({ assert }) => { + test('invoke onQuery method when preloading relationship', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() class Profile extends BaseModel { @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User, { onQuery: (builder) => { builder.where('country_id', 1) }, }) - public user: BelongsTo + declare user: BelongsTo } Profile.boot() @@ -2033,24 +2203,30 @@ test.group('Model | BelongsTo | onQuery', (group) => { assert.isNull(profile?.user) }) - test('do not run onQuery hook on subqueries', async ({ assert }) => { + test('do not run onQuery hook on subqueries', async ({ assert, fs }) => { assert.plan(2) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() class Profile extends BaseModel { @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User, { onQuery: (builder) => { @@ -2058,7 +2234,7 @@ test.group('Model | BelongsTo | onQuery', (group) => { builder.where('country_id', 1) }, }) - public user: BelongsTo + declare user: BelongsTo } Profile.boot() @@ -2074,29 +2250,35 @@ test.group('Model | BelongsTo | onQuery', (group) => { assert.isNull(profile?.user) }) - test('invoke onQuery method on related query builder', async ({ assert }) => { + test('invoke onQuery method on related query builder', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() class Profile extends BaseModel { @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User, { onQuery: (builder) => { builder.where('country_id', 1) }, }) - public user: BelongsTo + declare user: BelongsTo } Profile.boot() @@ -2107,29 +2289,35 @@ test.group('Model | BelongsTo | onQuery', (group) => { assert.isNull(user) }) - test('do not run onQuery hook on related query builder subqueries', async ({ assert }) => { + test('do not run onQuery hook on related query builder subqueries', async ({ assert, fs }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() class Profile extends BaseModel { @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User, { onQuery: (builder) => { builder.where('country_id', 1) }, }) - public user: BelongsTo + declare user: BelongsTo } Profile.boot() diff --git a/test/orm/model-has-many.spec.ts b/test/orm/model_has_many.spec.ts similarity index 74% rename from test/orm/model-has-many.spec.ts rename to test/orm/model_has_many.spec.ts index 314da789..83e9a113 100644 --- a/test/orm/model-has-many.spec.ts +++ b/test/orm/model_has_many.spec.ts @@ -7,17 +7,14 @@ * file that was distributed with this source code. */ -/// - import { test } from '@japa/runner' -import type { HasMany } from '@ioc:Adonis/Lucid/Orm' +import type { HasMany } from '../../adonis-typings/relations.js' -import { scope } from '../../src/Helpers/scope' -import { column, hasMany } from '../../src/Orm/Decorators' -import { HasManyQueryBuilder } from '../../src/Orm/Relations/HasMany/QueryBuilder' +import { scope } from '../../src/orm/base_model/index.js' +import { column, hasMany } from '../../src/orm/decorators/index.js' +import { HasManyQueryBuilder } from '../../src/orm/relations/has_many/query_builder.js' import { - fs, setup, getDb, cleanup, @@ -25,29 +22,25 @@ import { ormAdapter, resetTables, getBaseModel, - setupApplication, -} from '../../test-helpers' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -let db: ReturnType -let app: ApplicationContract -let BaseModel: ReturnType +} from '../../test-helpers/index.js' +import { AppFactory } from '@adonisjs/core/factories/app' test.group('Model | HasMany | Options', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) - test('raise error when localKey is missing', ({ assert }) => { + test('raise error when localKey is missing', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(1) try { @@ -55,20 +48,23 @@ test.group('Model | HasMany | Options', (group) => { class User extends BaseModel { @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } User.boot() User.$getRelation('posts')!.boot() } catch ({ message }) { - assert.equal( - message, - 'E_MISSING_MODEL_ATTRIBUTE: "User.posts" expects "id" to exist on "User" model, but is missing' - ) + assert.equal(message, '"User.posts" expects "id" to exist on "User" model, but is missing') } }) - test('raise error when foreignKey is missing', ({ assert }) => { + test('raise error when foreignKey is missing', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(1) try { @@ -77,10 +73,10 @@ test.group('Model | HasMany | Options', (group) => { class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -88,23 +84,29 @@ test.group('Model | HasMany | Options', (group) => { } catch ({ message }) { assert.equal( message, - 'E_MISSING_MODEL_ATTRIBUTE: "User.posts" expects "userId" to exist on "Post" model, but is missing' + '"User.posts" expects "userId" to exist on "Post" model, but is missing' ) } }) - test('use primary key as the local key', ({ assert }) => { + test('use primary key as the local key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -113,21 +115,27 @@ test.group('Model | HasMany | Options', (group) => { assert.equal(User.$getRelation('posts')!['localKey'], 'id') }) - test('use custom defined primary key', ({ assert }) => { + test('use custom defined primary key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column({ columnName: 'user_uid' }) - public uid: number + declare uid: number @hasMany(() => Post, { localKey: 'uid' }) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -136,18 +144,24 @@ test.group('Model | HasMany | Options', (group) => { assert.equal(User.$getRelation('posts')!['localKey'], 'uid') }) - test('compute foreign key from model name and primary key', ({ assert }) => { + test('compute foreign key from model name and primary key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -156,18 +170,24 @@ test.group('Model | HasMany | Options', (group) => { assert.equal(User.$getRelation('posts')!['foreignKey'], 'userId') }) - test('use pre defined foreign key', ({ assert }) => { + test('use pre defined foreign key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column({ columnName: 'user_id' }) - public userUid: number + declare userUid: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post, { foreignKey: 'userUid' }) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -176,18 +196,24 @@ test.group('Model | HasMany | Options', (group) => { assert.equal(User.$getRelation('posts')!['foreignKey'], 'userUid') }) - test('clone relationship instance with options', ({ assert }) => { + test('clone relationship instance with options', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column({ columnName: 'user_id' }) - public userUid: number + declare userUid: number } class BaseUser extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post, { foreignKey: 'userUid' }) - public posts: HasMany + declare posts: HasMany } class User extends BaseUser {} @@ -202,30 +228,31 @@ test.group('Model | HasMany | Options', (group) => { test.group('Model | HasMany | Set Relations', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) - test('set related model instance', ({ assert }) => { + test('set related model instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -241,18 +268,24 @@ test.group('Model | HasMany | Set Relations', (group) => { assert.deepEqual(user.posts, [post]) }) - test('push related model instance', ({ assert }) => { + test('push related model instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -273,18 +306,24 @@ test.group('Model | HasMany | Set Relations', (group) => { assert.deepEqual(user.posts, [post, post1]) }) - test('set many of related instances', ({ assert }) => { + test('set many of related instances', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -317,34 +356,35 @@ test.group('Model | HasMany | Set Relations', (group) => { test.group('Model | HasMany | bulk operations', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('generate correct sql for selecting related rows', async ({ assert }) => { + test('generate correct sql for selecting related rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -366,18 +406,24 @@ test.group('Model | HasMany | bulk operations', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('generate correct sql for selecting related many rows', async ({ assert }) => { + test('generate correct sql for selecting related many rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -401,18 +447,24 @@ test.group('Model | HasMany | bulk operations', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('generate correct sql for updating related rows', async ({ assert }) => { + test('generate correct sql for updating related rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -441,18 +493,24 @@ test.group('Model | HasMany | bulk operations', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('generate correct sql for deleting related row', async ({ assert }) => { + test('generate correct sql for deleting related row', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db.table('users').insert({ username: 'virk' }) @@ -472,18 +530,24 @@ test.group('Model | HasMany | bulk operations', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('generate correct sql with additional constraints', async ({ assert }) => { + test('generate correct sql with additional constraints', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -510,18 +574,27 @@ test.group('Model | HasMany | bulk operations', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('paginate with additional constraints using related query builder', async ({ assert }) => { + test('paginate with additional constraints using related query builder', async ({ + fs, + assert, + }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -550,37 +623,38 @@ test.group('Model | HasMany | bulk operations', (group) => { test.group('Model | HasMany | sub queries', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('generate correct sub query for selecting rows', async ({ assert }) => { + test('generate correct sub query for selecting rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -598,21 +672,27 @@ test.group('Model | HasMany | sub queries', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('create aggregate query', async ({ assert }) => { + test('create aggregate query', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -635,21 +715,27 @@ test.group('Model | HasMany | sub queries', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('allow selecting custom columns', async ({ assert }) => { + test('allow selecting custom columns', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -672,19 +758,25 @@ test.group('Model | HasMany | sub queries', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('generate correct self relationship subquery', async ({ assert }) => { + test('generate correct self relationship subquery', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public username: string + declare username: string @hasMany(() => User) - public parents: HasMany + declare parents: HasMany } User.boot() @@ -707,21 +799,27 @@ test.group('Model | HasMany | sub queries', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('raise exception when trying to execute the query', async ({ assert }) => { + test('raise exception when trying to execute the query', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -742,26 +840,32 @@ test.group('Model | HasMany | sub queries', (group) => { assert.throws(firstOrFail, 'Cannot execute relationship subqueries') }) - test('run onQuery method when defined', async ({ assert }) => { + test('run onQuery method when defined', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public isPublished: boolean + declare isPublished: boolean } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post, { onQuery: (query) => query.where('isPublished', true), }) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -785,34 +889,35 @@ test.group('Model | HasMany | sub queries', (group) => { test.group('Model | HasMany | aggregates', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('get total of all related rows', async ({ assert }) => { + test('get total of all related rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -833,34 +938,35 @@ test.group('Model | HasMany | aggregates', (group) => { test.group('Model | HasMany | preload', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('preload relationship', async ({ assert }) => { + test('preload relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -894,18 +1000,25 @@ test.group('Model | HasMany | preload', (group) => { test('set relationship property value to empty array when no related rows have been found', async ({ assert, + fs, }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -922,24 +1035,30 @@ test.group('Model | HasMany | preload', (group) => { assert.lengthOf(users[1].posts, 0) }) - test('preload relationship for many rows', async ({ assert }) => { + test('preload relationship for many rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -978,24 +1097,30 @@ test.group('Model | HasMany | preload', (group) => { assert.equal(users[1].posts[0].userId, users[1].id) }) - test('add constraints during preload', async ({ assert }) => { + test('add constraints during preload', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -1032,24 +1157,30 @@ test.group('Model | HasMany | preload', (group) => { assert.lengthOf(users[1].posts, 0) }) - test('cherry pick columns during preload', async ({ assert }) => { + test('cherry pick columns during preload', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -1085,24 +1216,30 @@ test.group('Model | HasMany | preload', (group) => { assert.deepEqual(users[1].posts[0].$extras, {}) }) - test('do not repeat fk when already defined', async ({ assert }) => { + test('do not repeat fk when already defined', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -1138,26 +1275,32 @@ test.group('Model | HasMany | preload', (group) => { assert.deepEqual(users[1].posts[0].$extras, {}) }) - test('raise exception when local key is not selected', async ({ assert }) => { + test('raise exception when local key is not selected', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(1) class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -1189,38 +1332,44 @@ test.group('Model | HasMany | preload', (group) => { } }) - test('preload nested relations', async ({ assert }) => { + test('preload nested relations', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Comment extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public postId: number + declare postId: number @column() - public body: string + declare body: string } class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string @hasMany(() => Comment) - public comments: HasMany + declare comments: HasMany } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -1265,38 +1414,44 @@ test.group('Model | HasMany | preload', (group) => { assert.equal(user!.posts[0].comments[0].postId, user!.posts[0].id) }) - test('preload nested relations using model instance', async ({ assert }) => { + test('preload nested relations using model instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Comment extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public postId: number + declare postId: number @column() - public body: string + declare body: string } class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string @hasMany(() => Comment) - public comments: HasMany + declare comments: HasMany } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -1350,38 +1505,44 @@ test.group('Model | HasMany | preload', (group) => { assert.equal(users[1].posts[0].comments[0].postId, users[1].posts[0].id) }) - test('pass main query options down the chain', async ({ assert }) => { + test('pass main query options down the chain', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Comment extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public postId: number + declare postId: number @column() - public body: string + declare body: string } class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string @hasMany(() => Comment) - public comments: HasMany + declare comments: HasMany } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -1430,72 +1591,24 @@ test.group('Model | HasMany | preload', (group) => { assert.equal(user!.posts[0].comments[0].$options!.connection, 'secondary') }) - test('pass relationship metadata to the profiler', async ({ assert }) => { - assert.plan(1) - - class Post extends BaseModel { - @column() - public userId: number - } - - class User extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @hasMany(() => Post) - public posts: HasMany - } - - await db - .insertQuery() - .table('users') - .insert([{ username: 'virk' }, { username: 'nikk' }]) - - const [user0, user1] = await db.query().from('users') - await db - .insertQuery() - .table('posts') - .insert([ - { - user_id: user0.id, - title: 'Adonis 101', - }, - { - user_id: user1.id, - title: 'Lucid 101', - }, - ]) - - const profiler = app.profiler - - let profilerPacketIndex = 0 - profiler.process((packet) => { - if (profilerPacketIndex === 1) { - assert.deepEqual(packet.data.relation, { - model: 'User', - relatedModel: 'Post', - type: 'hasMany', - }) - } - profilerPacketIndex++ - }) - - User.boot() - await User.query({ profiler }).preload('posts') - }) + test('do not run preload query when parent rows are empty', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) - test('do not run preload query when parent rows are empty', async ({ assert }) => { class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -1510,34 +1623,35 @@ test.group('Model | HasMany | preload', (group) => { test.group('Model | HasMany | withCount', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('get count of a relationship rows', async ({ assert }) => { + test('get count of a relationship rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -1573,18 +1687,24 @@ test.group('Model | HasMany | withCount', (group) => { assert.deepEqual(Number(users[1].$extras.posts_count), 1) }) - test('apply constraints to the withCount subquery', async ({ assert }) => { + test('apply constraints to the withCount subquery', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -1622,18 +1742,24 @@ test.group('Model | HasMany | withCount', (group) => { assert.deepEqual(Number(users[1].$extras.posts_count), 1) }) - test('allow subquery to have custom aggregates', async ({ assert }) => { + test('allow subquery to have custom aggregates', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -1671,21 +1797,27 @@ test.group('Model | HasMany | withCount', (group) => { assert.deepEqual(Number(users[1].$extras.postsCount), 1) }) - test('allow cherry picking columns', async ({ assert }) => { + test('allow cherry picking columns', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -1724,19 +1856,25 @@ test.group('Model | HasMany | withCount', (group) => { assert.deepEqual(Number(users[1].$extras.posts_count), 1) }) - test('get count of self relationship', async ({ assert }) => { + test('get count of self relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public parentId: number + declare parentId: number @column() - public username: string + declare username: string @hasMany(() => User, { foreignKey: 'parentId' }) - public parents: HasMany + declare parents: HasMany } User.boot() @@ -1777,18 +1915,24 @@ test.group('Model | HasMany | withCount', (group) => { assert.deepEqual(Number(users[1].$extras.parents_count), 1) }) - test('define custom alias for the count', async ({ assert }) => { + test('define custom alias for the count', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -1828,35 +1972,41 @@ test.group('Model | HasMany | withCount', (group) => { assert.deepEqual(Number(users[1].$extras.totalPosts), 1) }) - test('get count of a nested relationship', async ({ assert }) => { + test('get count of a nested relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Comment extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public postId: number + declare postId: number @column() - public body: string + declare body: string } class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @hasMany(() => Comment) - public comments: HasMany + declare comments: HasMany } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -1934,20 +2084,26 @@ test.group('Model | HasMany | withCount', (group) => { assert.deepEqual(Number(posts[1].$extras.comments_count), 1) }) - test('set count directly on the model when defined as a property', async ({ assert }) => { + test('set count directly on the model when defined as a property', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number - public postsCount: number = 0 + postsCount: number = 0 @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -1983,22 +2139,31 @@ test.group('Model | HasMany | withCount', (group) => { assert.deepEqual(Number(users[1].postsCount), 1) }) - test('do not set count directly on the model when defined as a getter', async ({ assert }) => { + test('do not set count directly on the model when defined as a getter', async ({ + fs, + assert, + }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number - public get postsCount(): number { + get postsCount(): number { return this.$extras.postsCount } @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -2036,21 +2201,27 @@ test.group('Model | HasMany | withCount', (group) => { assert.deepEqual(Number(users[1].$extras.postsCount), 1) }) - test('lazy load related rows count', async ({ assert }) => { + test('lazy load related rows count', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -2084,18 +2255,24 @@ test.group('Model | HasMany | withCount', (group) => { assert.deepEqual(Number(user.$extras.posts_count), 2) }) - test('apply constraints to the loadCount subquery', async ({ assert }) => { + test('apply constraints to the loadCount subquery', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -2131,34 +2308,35 @@ test.group('Model | HasMany | withCount', (group) => { test.group('Model | HasMany | has', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('limit rows to the existance of relationship', async ({ assert }) => { + test('limit rows to the existance of relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -2205,18 +2383,24 @@ test.group('Model | HasMany | has', (group) => { assert.lengthOf(users, 1) }) - test('define expected number of rows', async ({ assert }) => { + test('define expected number of rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -2270,18 +2454,24 @@ test.group('Model | HasMany | has', (group) => { assert.lengthOf(users, 1) }) - test('merge query existing bindings with the count query', async ({ assert }) => { + test('merge query existing bindings with the count query', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -2336,18 +2526,24 @@ test.group('Model | HasMany | has', (group) => { assert.lengthOf(users, 1) }) - test('define or clause in existance query', async ({ assert }) => { + test('define or clause in existance query', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -2402,21 +2598,27 @@ test.group('Model | HasMany | has', (group) => { assert.lengthOf(users, 2) }) - test('define not existance query', async ({ assert }) => { + test('define not existance query', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -2465,21 +2667,27 @@ test.group('Model | HasMany | has', (group) => { assert.equal(users[0].username, 'nikk') }) - test('define or not existance query', async ({ assert }) => { + test('define or not existance query', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -2539,34 +2747,35 @@ test.group('Model | HasMany | has', (group) => { test.group('Model | HasMany | whereHas', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('limit rows to the existance of relationship', async ({ assert }) => { + test('limit rows to the existance of relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -2623,18 +2832,24 @@ test.group('Model | HasMany | whereHas', (group) => { assert.lengthOf(users, 1) }) - test('define expected number of rows', async ({ assert }) => { + test('define expected number of rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -2706,21 +2921,27 @@ test.group('Model | HasMany | whereHas', (group) => { assert.lengthOf(users, 1) }) - test('define custom aggregates', async ({ assert }) => { + test('define custom aggregates', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -2786,18 +3007,24 @@ test.group('Model | HasMany | whereHas', (group) => { assert.equal(users[0].username, 'nikk') }) - test('define or clause', async ({ assert }) => { + test('define or clause', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -2883,21 +3110,27 @@ test.group('Model | HasMany | whereHas', (group) => { assert.lengthOf(users, 2) }) - test('define not clause', async ({ assert }) => { + test('define not clause', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -2985,21 +3218,27 @@ test.group('Model | HasMany | whereHas', (group) => { assert.equal(users[0].username, 'nikk') }) - test('define or not clause', async ({ assert }) => { + test('define or not clause', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -3091,40 +3330,41 @@ test.group('Model | HasMany | whereHas', (group) => { if (process.env.DB !== 'mysql_legacy') { test.group('Model | HasMany | Group Limit', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('apply group limit', async ({ assert }) => { + test('apply group limit', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string @column() - public createdAt: Date + declare createdAt: Date } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -3220,24 +3460,30 @@ if (process.env.DB !== 'mysql_legacy') { assert.exists(users[1].posts[1].createdAt) }) - test('apply group limit with additional constraints', async ({ assert }) => { + test('apply group limit with additional constraints', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string @column() - public createdAt: Date + declare createdAt: Date } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -3330,24 +3576,30 @@ if (process.env.DB !== 'mysql_legacy') { assert.exists(users[0].posts[1].createdAt) }) - test('apply group limit and select custom columns', async ({ assert }) => { + test('apply group limit and select custom columns', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string @column() - public createdAt: Date + declare createdAt: Date } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -3431,24 +3683,30 @@ if (process.env.DB !== 'mysql_legacy') { assert.isUndefined(users[1].posts[1].createdAt) }) - test('define custom order by clause', async ({ assert }) => { + test('define custom order by clause', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string @column() - public createdAt: Date + declare createdAt: Date } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -3546,24 +3804,30 @@ if (process.env.DB !== 'mysql_legacy') { assert.exists(users[1].posts[1].createdAt) }) - test('apply standard limit when not eagerloading', async ({ assert }) => { + test('apply standard limit when not eagerloading', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string @column() - public createdAt: Date + declare createdAt: Date } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -3621,24 +3885,30 @@ if (process.env.DB !== 'mysql_legacy') { assert.deepEqual(bindings, knexBindings) }) - test('apply standard order by when not eagerloading', async ({ assert }) => { + test('apply standard order by when not eagerloading', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string @column() - public createdAt: Date + declare createdAt: Date } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -3702,41 +3972,47 @@ if (process.env.DB !== 'mysql_legacy') { assert.deepEqual(bindings, knexBindings) }) - test('preload with group limit', async ({ assert }) => { + test('preload with group limit', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Comment extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public postId: number + declare postId: number @column() - public body: string + declare body: string } class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string @column() - public createdAt: Date + declare createdAt: Date @hasMany(() => Comment) - public comments: HasMany + declare comments: HasMany } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -3834,41 +4110,47 @@ if (process.env.DB !== 'mysql_legacy') { assert.lengthOf(users[1].posts[1].comments, 2) }) - test('pass sideloaded data after applying group limit', async ({ assert }) => { + test('pass sideloaded data after applying group limit', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Comment extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public postId: number + declare postId: number @column() - public body: string + declare body: string } class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string @column() - public createdAt: Date + declare createdAt: Date @hasMany(() => Comment) - public comments: HasMany + declare comments: HasMany } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } await db @@ -3974,43 +4256,44 @@ if (process.env.DB !== 'mysql_legacy') { test.group('Model | HasMany | save', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('save related instance', async ({ assert }) => { + test('save related instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } const user = new User() @@ -4035,43 +4318,44 @@ test.group('Model | HasMany | save', (group) => { test.group('Model | HasMany | saveMany', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('save many related instances', async ({ assert }) => { + test('save many related instances', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } const user = new User() @@ -4099,29 +4383,35 @@ test.group('Model | HasMany | saveMany', (group) => { assert.equal(totalPosts[0].total, 2) }) - test('wrap save many calls inside transaction', async ({ assert }) => { + test('wrap save many calls inside transaction', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(6) class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } const user = new User() @@ -4148,27 +4438,33 @@ test.group('Model | HasMany | saveMany', (group) => { assert.isUndefined(post1.$trx) }) - test('use parent model transaction when exists', async ({ assert }) => { + test('use parent model transaction when exists', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } const trx = await db.transaction() @@ -4200,43 +4496,44 @@ test.group('Model | HasMany | saveMany', (group) => { test.group('Model | HasMany | create', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('create related instance', async ({ assert }) => { + test('create related instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } const user = new User() @@ -4258,43 +4555,44 @@ test.group('Model | HasMany | create', (group) => { test.group('Model | HasMany | createMany', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('create many related instances', async ({ assert }) => { + test('create many related instances', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } const user = new User() @@ -4323,29 +4621,35 @@ test.group('Model | HasMany | createMany', (group) => { assert.equal(totalPosts[0].total, 2) }) - test('wrap create many calls inside transaction', async ({ assert }) => { + test('wrap create many calls inside transaction', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(4) class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } const user = new User() @@ -4365,27 +4669,33 @@ test.group('Model | HasMany | createMany', (group) => { assert.isUndefined(user.$trx) }) - test('use parent model transaction when already exists', async ({ assert }) => { + test('use parent model transaction when already exists', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } const trx = await db.transaction() @@ -4409,43 +4719,44 @@ test.group('Model | HasMany | createMany', (group) => { test.group('Model | HasMany | firstOrCreate', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test("create related instance when there isn't any existing row", async ({ assert }) => { + test("create related instance when there isn't any existing row", async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } const user = new User() @@ -4470,27 +4781,33 @@ test.group('Model | HasMany | firstOrCreate', (group) => { assert.equal(posts[1].user_id, user.id) }) - test('return existing instance vs creating one', async ({ assert }) => { + test('return existing instance vs creating one', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } const user = new User() @@ -4518,43 +4835,44 @@ test.group('Model | HasMany | firstOrCreate', (group) => { test.group('Model | HasMany | updateOrCreate', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test("create related instance when there isn't any existing row", async ({ assert }) => { + test("create related instance when there isn't any existing row", async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } const user = new User() @@ -4579,27 +4897,33 @@ test.group('Model | HasMany | updateOrCreate', (group) => { assert.equal(posts[1].user_id, user.id) }) - test('update existing instance vs creating one', async ({ assert }) => { + test('update existing instance vs creating one', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } const user = new User() @@ -4628,43 +4952,44 @@ test.group('Model | HasMany | updateOrCreate', (group) => { test.group('Model | HasMany | fetchOrCreateMany', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test("create related instance when there aren't any existing row", async ({ assert }) => { + test("create related instance when there aren't any existing row", async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } const user = new User() @@ -4689,27 +5014,33 @@ test.group('Model | HasMany | fetchOrCreateMany', (group) => { assert.equal(posts[1].user_id, user.id) }) - test('return existing instance vs creating one', async ({ assert }) => { + test('return existing instance vs creating one', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } const user = new User() @@ -4756,43 +5087,44 @@ test.group('Model | HasMany | fetchOrCreateMany', (group) => { test.group('Model | HasMany | fetchOrCreateMany', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test("create related instance when there aren't any existing row", async ({ assert }) => { + test("create related instance when there aren't any existing row", async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } const user = new User() @@ -4817,30 +5149,36 @@ test.group('Model | HasMany | fetchOrCreateMany', (group) => { assert.equal(posts[1].user_id, user.id) }) - test('update existing instance vs creating one', async ({ assert }) => { + test('update existing instance vs creating one', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string @column() - public isPublished: boolean + declare isPublished: boolean } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } const user = new User() @@ -4896,34 +5234,35 @@ test.group('Model | HasMany | fetchOrCreateMany', (group) => { test.group('Model | HasMany | paginate', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('paginate using related model query builder instance', async ({ assert }) => { + test('paginate using related model query builder instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -4963,20 +5302,26 @@ test.group('Model | HasMany | paginate', (group) => { }) }) - test('disallow paginate during preload', async ({ assert }) => { + test('disallow paginate during preload', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(1) class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -4996,34 +5341,35 @@ test.group('Model | HasMany | paginate', (group) => { test.group('Model | HasMany | clone', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('clone related model query builder', async ({ assert }) => { + test('clone related model query builder', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -5039,41 +5385,42 @@ test.group('Model | HasMany | clone', (group) => { test.group('Model | HasMany | scopes', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('apply scopes during eagerload', async ({ assert }) => { + test('apply scopes during eagerload', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string - public static adonisOnly = scope((query) => { + static adonisOnly = scope((query) => { query.where('title', 'Adonis 101') }) } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -5106,25 +5453,31 @@ test.group('Model | HasMany | scopes', (group) => { assert.equal(user.posts[0].title, 'Adonis 101') }) - test('apply scopes on related query', async ({ assert }) => { + test('apply scopes on related query', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string - public static adonisOnly = scope((query) => { + static adonisOnly = scope((query) => { query.where('title', 'Adonis 101') }) } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -5160,39 +5513,40 @@ test.group('Model | HasMany | scopes', (group) => { test.group('Model | HasMany | onQuery', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('invoke onQuery method when preloading relationship', async ({ assert }) => { + test('invoke onQuery method when preloading relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post, { onQuery: (query) => query.where('title', 'Adonis 101'), }) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -5217,20 +5571,26 @@ test.group('Model | HasMany | onQuery', (group) => { assert.equal(user.posts[0].title, 'Adonis 101') }) - test('do not invoke onQuery method on preloading subqueries', async ({ assert }) => { + test('do not invoke onQuery method on preloading subqueries', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(3) class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post, { onQuery: (query) => { @@ -5238,7 +5598,7 @@ test.group('Model | HasMany | onQuery', (group) => { query.where('title', 'Adonis 101') }, }) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -5264,23 +5624,29 @@ test.group('Model | HasMany | onQuery', (group) => { assert.equal(user.posts[0].title, 'Adonis 101') }) - test('invoke onQuery method on related query', async ({ assert }) => { + test('invoke onQuery method on related query', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post, { onQuery: (query) => query.where('title', 'Adonis 101'), }) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -5306,23 +5672,29 @@ test.group('Model | HasMany | onQuery', (group) => { assert.equal(posts[0].title, 'Adonis 101') }) - test('do not invoke onQuery method on related query subqueries', async ({ assert }) => { + test('do not invoke onQuery method on related query subqueries', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasMany(() => Post, { onQuery: (query) => query.where('title', 'Adonis 101'), }) - public posts: HasMany + declare posts: HasMany } User.boot() @@ -5369,43 +5741,44 @@ test.group('Model | HasMany | onQuery', (group) => { test.group('Model | HasMany | delete', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('delete related instance', async ({ assert }) => { + test('delete related instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } const user = new User() diff --git a/test/orm/model-has-many-through.spec.ts b/test/orm/model_has_many_through.spec.ts similarity index 74% rename from test/orm/model-has-many-through.spec.ts rename to test/orm/model_has_many_through.spec.ts index 3834d54f..320df360 100644 --- a/test/orm/model-has-many-through.spec.ts +++ b/test/orm/model_has_many_through.spec.ts @@ -7,47 +7,40 @@ * file that was distributed with this source code. */ -/// - import { test } from '@japa/runner' -import type { HasManyThrough } from '@ioc:Adonis/Lucid/Orm' +import type { HasManyThrough } from '../../adonis-typings/relations.js' -import { scope } from '../../src/Helpers/scope' -import { hasManyThrough, column } from '../../src/Orm/Decorators' -import { HasManyThroughQueryBuilder } from '../../src/Orm/Relations/HasManyThrough/QueryBuilder' +import { scope } from '../../src/orm/base_model/index.js' +import { hasManyThrough, column } from '../../src/orm/decorators/index.js' +import { HasManyThroughQueryBuilder } from '../../src/orm/relations/has_many_through/query_builder.js' import { - fs, ormAdapter, getBaseModel, setup, cleanup, resetTables, getDb, - setupApplication, -} from '../../test-helpers' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -let db: ReturnType -let app: ApplicationContract -let BaseModel: ReturnType +} from '../../test-helpers/index.js' +import { AppFactory } from '@adonisjs/core/factories/app' test.group('Model | Has Many Through | Options', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) - test('raise error when localKey is missing', ({ assert }) => { + test('raise error when localKey is missing', async ({ fs, assert }) => { assert.plan(1) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + try { class User extends BaseModel {} User.boot() @@ -57,7 +50,7 @@ test.group('Model | Has Many Through | Options', (group) => { class Country extends BaseModel { @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -70,9 +63,15 @@ test.group('Model | Has Many Through | Options', (group) => { } }) - test('raise error when foreignKey is missing', ({ assert }) => { + test('raise error when foreignKey is missing', async ({ fs, assert }) => { assert.plan(1) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + try { class User extends BaseModel {} User.boot() @@ -82,10 +81,10 @@ test.group('Model | Has Many Through | Options', (group) => { class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -98,13 +97,19 @@ test.group('Model | Has Many Through | Options', (group) => { } }) - test('raise error when through local key is missing', ({ assert }) => { + test('raise error when through local key is missing', async ({ fs, assert }) => { assert.plan(1) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + try { class User extends BaseModel { @column() - public countryId: number + declare countryId: number } User.boot() @@ -113,10 +118,10 @@ test.group('Model | Has Many Through | Options', (group) => { class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -129,16 +134,22 @@ test.group('Model | Has Many Through | Options', (group) => { } }) - test('raise error when through foreign key is missing', ({ assert }) => { + test('raise error when through foreign key is missing', async ({ fs, assert }) => { assert.plan(1) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + try { class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() @@ -147,10 +158,10 @@ test.group('Model | Has Many Through | Options', (group) => { class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -163,28 +174,34 @@ test.group('Model | Has Many Through | Options', (group) => { } }) - test('compute all required keys', ({ assert }) => { + test('compute all required keys', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column() - public userId: number + declare userId: number } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -205,25 +222,31 @@ test.group('Model | Has Many Through | Options', (group) => { assert.equal(relation['throughForeignKeyColumnName'], 'user_id') }) - test('compute custom keys', ({ assert }) => { + test('compute custom keys', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public uid: number + declare uid: number @column() - public countryUid: number + declare countryUid: number } User.boot() class Post extends BaseModel { @column() - public userUid: number + declare userUid: number } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public uid: number + declare uid: number @hasManyThrough([() => Post, () => User], { throughForeignKey: 'userUid', @@ -231,7 +254,7 @@ test.group('Model | Has Many Through | Options', (group) => { foreignKey: 'countryUid', localKey: 'uid', }) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -252,25 +275,31 @@ test.group('Model | Has Many Through | Options', (group) => { assert.equal(relation['throughForeignKeyColumnName'], 'user_uid') }) - test('clone relationship instance with options', ({ assert }) => { + test('clone relationship instance with options', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public uid: number + declare uid: number @column() - public countryUid: number + declare countryUid: number } User.boot() class Post extends BaseModel { @column() - public userUid: number + declare userUid: number } Post.boot() class BaseCountry extends BaseModel { @column({ isPrimary: true }) - public uid: number + declare uid: number @hasManyThrough([() => Post, () => User], { throughForeignKey: 'userUid', @@ -278,7 +307,7 @@ test.group('Model | Has Many Through | Options', (group) => { foreignKey: 'countryUid', localKey: 'uid', }) - public posts: HasManyThrough + declare posts: HasManyThrough } class Country extends BaseCountry {} @@ -305,40 +334,41 @@ test.group('Model | Has Many Through | Options', (group) => { test.group('Model | Has Many Through | Set Relations', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) - test('set related model instance', ({ assert }) => { + test('set related model instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column() - public userId: number + declare userId: number } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -351,28 +381,34 @@ test.group('Model | Has Many Through | Set Relations', (group) => { assert.deepEqual(country.posts, [post]) }) - test('push related model instance', ({ assert }) => { + test('push related model instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column() - public userId: number + declare userId: number } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -387,28 +423,34 @@ test.group('Model | Has Many Through | Set Relations', (group) => { assert.deepEqual(country.posts, [post, post1]) }) - test('set many of related instances', ({ assert }) => { + test('set many of related instances', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column() - public userId: number + declare userId: number } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -453,44 +495,45 @@ test.group('Model | Has Many Through | Set Relations', (group) => { test.group('Model | Has Many Through | bulk operations', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('generate correct sql for selecting related rows', async ({ assert }) => { + test('generate correct sql for selecting related rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column() - public userId: number + declare userId: number } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -512,28 +555,34 @@ test.group('Model | Has Many Through | bulk operations', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('generate correct sql for selecting many related rows', async ({ assert }) => { + test('generate correct sql for selecting many related rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column() - public userId: number + declare userId: number } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -558,28 +607,34 @@ test.group('Model | Has Many Through | bulk operations', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('generate correct sql for updating related rows', async ({ assert }) => { + test('generate correct sql for updating related rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column() - public userId: number + declare userId: number } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -610,28 +665,34 @@ test.group('Model | Has Many Through | bulk operations', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('generate correct sql for deleting related rows', async ({ assert }) => { + test('generate correct sql for deleting related rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column() - public userId: number + declare userId: number } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -657,44 +718,45 @@ test.group('Model | Has Many Through | bulk operations', (group) => { test.group('Model | HasMany | sub queries', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('generate correct sub query for selecting rows', async ({ assert }) => { + test('generate correct sub query for selecting rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column() - public userId: number + declare userId: number } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -713,28 +775,34 @@ test.group('Model | HasMany | sub queries', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('create aggregate query', async ({ assert }) => { + test('create aggregate query', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column() - public userId: number + declare userId: number } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -758,28 +826,34 @@ test.group('Model | HasMany | sub queries', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('allow selecting custom columns', async ({ assert }) => { + test('allow selecting custom columns', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column() - public userId: number + declare userId: number } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -803,28 +877,34 @@ test.group('Model | HasMany | sub queries', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('generate correct self relationship subquery', async ({ assert }) => { + test('generate correct self relationship subquery', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number /** * Funny relationship, but just ignore it */ @hasManyThrough([() => Country, () => User]) - public countries: HasManyThrough + declare countries: HasManyThrough } Country.boot() @@ -848,28 +928,34 @@ test.group('Model | HasMany | sub queries', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('raise exception when trying to execute the query', async ({ assert }) => { + test('raise exception when trying to execute the query', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column() - public userId: number + declare userId: number } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -891,33 +977,39 @@ test.group('Model | HasMany | sub queries', (group) => { assert.throws(firstOrFail, 'Cannot execute relationship subqueries') }) - test('run onQuery method when defined', async ({ assert }) => { + test('run onQuery method when defined', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public isPublished: boolean + declare isPublished: boolean } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User], { onQuery: (query) => query.where('isPublished', true), }) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -940,44 +1032,45 @@ test.group('Model | HasMany | sub queries', (group) => { test.group('Model | Has Many Through | aggregates', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('get total of all related rows', async ({ assert }) => { + test('get total of all related rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column() - public userId: number + declare userId: number } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -1007,28 +1100,34 @@ test.group('Model | Has Many Through | aggregates', (group) => { assert.deepEqual(Number(total[0].$extras.total), 2) }) - test('select extra columns with count', async ({ assert }) => { + test('select extra columns with count', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column() - public userId: number + declare userId: number } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -1071,50 +1170,51 @@ test.group('Model | Has Many Through | aggregates', (group) => { test.group('Model | Has Many Through | preload', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('preload through relationships', async ({ assert }) => { + test('preload through relationships', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -1153,34 +1253,40 @@ test.group('Model | Has Many Through | preload', (group) => { assert.equal(countries[0].posts[2].$extras.through_country_id, 1) }) - test('preload many relationships', async ({ assert }) => { + test('preload many relationships', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -1221,34 +1327,40 @@ test.group('Model | Has Many Through | preload', (group) => { assert.equal(countries[1].posts[0].$extras.through_country_id, 2) }) - test('preload many relationships using model instance', async ({ assert }) => { + test('preload many relationships using model instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -1293,34 +1405,40 @@ test.group('Model | Has Many Through | preload', (group) => { assert.equal(countries[1].posts[0].$extras.through_country_id, 2) }) - test('cherry pick columns during preload', async ({ assert }) => { + test('cherry pick columns during preload', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -1364,34 +1482,40 @@ test.group('Model | Has Many Through | preload', (group) => { assert.deepEqual(countries[1].posts[0].$extras, { through_country_id: 2 }) }) - test('raise error when local key is not selected', async ({ assert }) => { + test('raise error when local key is not selected', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -1424,107 +1548,40 @@ test.group('Model | Has Many Through | preload', (group) => { } }) - test('pass relationship metadata to the profiler', async ({ assert }) => { - assert.plan(1) - - class User extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @column() - public countryId: number - } - User.boot() - - class Post extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @column() - public userId: number - - @column() - public title: string - } - Post.boot() - - class Country extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough - } - Country.boot() - - await db - .insertQuery() - .table('countries') - .insert([{ name: 'India' }]) - - await db - .insertQuery() - .table('users') - .insert([ - { username: 'virk', country_id: 1 }, - { username: 'nikk', country_id: 1 }, - ]) - - await db - .insertQuery() - .table('posts') - .insert([ - { title: 'Adonis 101', user_id: 1 }, - { title: 'Lucid 101', user_id: 1 }, - { title: 'Adonis5', user_id: 2 }, - ]) - - const profiler = app.profiler - - let profilerPacketIndex = 0 - profiler.process((packet) => { - if (profilerPacketIndex === 1) { - assert.deepEqual(packet.data.relation, { - model: 'Country', - relatedModel: 'Post', - throughModel: 'User', - type: 'hasManyThrough', - }) - } - profilerPacketIndex++ - }) - - await Country.query({ profiler }).preload('posts') - }) + test('do not run preload query when parent rows are empty', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) - test('do not run preload query when parent rows are empty', async ({ assert }) => { class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -1537,50 +1594,51 @@ test.group('Model | Has Many Through | preload', (group) => { test.group('Model | Has Many Through | withCount', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('get count of a relationship rows', async ({ assert }) => { + test('get count of a relationship rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -1617,34 +1675,40 @@ test.group('Model | Has Many Through | withCount', (group) => { assert.equal(countries[1].$extras.posts_count, 2) }) - test('apply constraints to the withCount subquery', async ({ assert }) => { + test('apply constraints to the withCount subquery', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -1685,34 +1749,40 @@ test.group('Model | Has Many Through | withCount', (group) => { assert.equal(countries[1].$extras.posts_count, 1) }) - test('allow subquery to have custom aggregates', async ({ assert }) => { + test('allow subquery to have custom aggregates', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -1753,37 +1823,43 @@ test.group('Model | Has Many Through | withCount', (group) => { assert.equal(countries[1].$extras.postsCount, 2) }) - test('allow cherry picking columns', async ({ assert }) => { + test('allow cherry picking columns', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -1820,37 +1896,43 @@ test.group('Model | Has Many Through | withCount', (group) => { assert.deepEqual(countries[1].$attributes, { name: 'Switzerland' }) }) - test('define custom alias for the count', async ({ assert }) => { + test('define custom alias for the count', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -1892,34 +1974,40 @@ test.group('Model | Has Many Through | withCount', (group) => { assert.deepEqual(Number(countries[1].$extras.countryPosts), 2) }) - test('lazy load relationship rows', async ({ assert }) => { + test('lazy load relationship rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -1953,34 +2041,40 @@ test.group('Model | Has Many Through | withCount', (group) => { assert.equal(Number(country.$extras.posts_count), 3) }) - test('apply constraints to the loadCount subquery', async ({ assert }) => { + test('apply constraints to the loadCount subquery', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -2019,53 +2113,54 @@ test.group('Model | Has Many Through | withCount', (group) => { test.group('Model | Has Many Through | has', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('limit rows to the existance of relationship', async ({ assert }) => { + test('limit rows to the existance of relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -2099,37 +2194,43 @@ test.group('Model | Has Many Through | has', (group) => { assert.equal(countries[0].name, 'India') }) - test('define expected number of rows', async ({ assert }) => { + test('define expected number of rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -2168,53 +2269,54 @@ test.group('Model | Has Many Through | has', (group) => { test.group('Model | Has Many Through | whereHas', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('limit rows to the existance of relationship', async ({ assert }) => { + test('limit rows to the existance of relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -2254,37 +2356,43 @@ test.group('Model | Has Many Through | whereHas', (group) => { assert.equal(countries[0].name, 'India') }) - test('define expected number of rows', async ({ assert }) => { + test('define expected number of rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -2333,50 +2441,51 @@ test.group('Model | Has Many Through | whereHas', (group) => { if (process.env.DB !== 'mysql_legacy') { test.group('Model | Has Many Through | Group Limit', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('apply group limit', async ({ assert }) => { + test('apply group limit', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -2438,34 +2547,40 @@ if (process.env.DB !== 'mysql_legacy') { assert.equal(countries[1].posts[1].$extras.through_country_id, 2) }) - test('apply group limit with custom constraints', async ({ assert }) => { + test('apply group limit with custom constraints', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -2529,37 +2644,43 @@ if (process.env.DB !== 'mysql_legacy') { assert.equal(countries[1].posts[1].$extras.through_country_id, 2) }) - test('apply group limit and cherry pick fields', async ({ assert }) => { + test('apply group limit and cherry pick fields', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string @column() - public createdAt: Date + declare createdAt: Date } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -2627,37 +2748,43 @@ if (process.env.DB !== 'mysql_legacy') { assert.equal(countries[1].posts[1].$extras.through_country_id, 2) }) - test('apply group limit with custom order', async ({ assert }) => { + test('apply group limit with custom order', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string @column() - public createdAt: Date + declare createdAt: Date } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -2725,34 +2852,40 @@ if (process.env.DB !== 'mysql_legacy') { assert.equal(countries[1].posts[1].$extras.through_country_id, 2) }) - test('apply standard limit when not eagerloading', async ({ assert }) => { + test('apply standard limit when not eagerloading', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -2798,34 +2931,40 @@ if (process.env.DB !== 'mysql_legacy') { assert.deepEqual(bindings, knexBindings) }) - test('apply standard order by when not eagerloading', async ({ assert }) => { + test('apply standard order by when not eagerloading', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -2882,44 +3021,45 @@ if (process.env.DB !== 'mysql_legacy') { test.group('Model | Has Many Through | pagination', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('paginate using related model query builder instance', async ({ assert }) => { + test('paginate using related model query builder instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column() - public userId: number + declare userId: number } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -2986,30 +3126,36 @@ test.group('Model | Has Many Through | pagination', (group) => { }) }) - test('disallow paginate during preload', async ({ assert }) => { + test('disallow paginate during preload', async ({ fs, assert }) => { assert.plan(1) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column() - public userId: number + declare userId: number } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -3025,44 +3171,45 @@ test.group('Model | Has Many Through | pagination', (group) => { test.group('Model | Has Many Through | clone', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('clone related model query builder', async ({ assert }) => { + test('clone related model query builder', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column() - public userId: number + declare userId: number } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -3109,40 +3256,41 @@ test.group('Model | Has Many Through | clone', (group) => { test.group('Model | Has Many Through | scopes', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('apply scopes during eagerload', async ({ assert }) => { + test('apply scopes during eagerload', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string - public static adonisOnly = scope((query) => { + static adonisOnly = scope((query) => { query.where('title', 'Adonis 101') }) } @@ -3150,10 +3298,10 @@ test.group('Model | Has Many Through | scopes', (group) => { class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -3206,24 +3354,30 @@ test.group('Model | Has Many Through | scopes', (group) => { assert.equal(country.posts[0].title, 'Adonis 101') }) - test('apply scopes on related query', async ({ assert }) => { + test('apply scopes on related query', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string - public static adonisOnly = scope((query) => { + static adonisOnly = scope((query) => { query.where('title', 'Adonis 101') }) } @@ -3231,10 +3385,10 @@ test.group('Model | Has Many Through | scopes', (group) => { class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User]) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -3288,49 +3442,50 @@ test.group('Model | Has Many Through | scopes', (group) => { test.group('Model | Has Many Through | onQuery', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('invoke onQuery method when preloading relationship', async ({ assert }) => { + test('invoke onQuery method when preloading relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User], { onQuery: (query) => query.where('title', 'Adonis 101'), }) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -3374,30 +3529,36 @@ test.group('Model | Has Many Through | onQuery', (group) => { assert.equal(country.posts[0].title, 'Adonis 101') }) - test('do not invoke onQuery method on preloading subqueries', async ({ assert }) => { + test('do not invoke onQuery method on preloading subqueries', async ({ fs, assert }) => { assert.plan(3) + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User], { onQuery: (query) => { @@ -3405,7 +3566,7 @@ test.group('Model | Has Many Through | onQuery', (group) => { query.where('title', 'Adonis 101') }, }) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -3453,33 +3614,39 @@ test.group('Model | Has Many Through | onQuery', (group) => { assert.equal(country.posts[0].title, 'Adonis 101') }) - test('invoke onQuery method on related query builder', async ({ assert }) => { + test('invoke onQuery method on related query builder', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User], { onQuery: (query) => query.where('title', 'Adonis 101'), }) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() @@ -3525,33 +3692,42 @@ test.group('Model | Has Many Through | onQuery', (group) => { assert.equal(posts[0].title, 'Adonis 101') }) - test('do not invoke onQuery method on related query builder subqueries', async ({ assert }) => { + test('do not invoke onQuery method on related query builder subqueries', async ({ + fs, + assert, + }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public countryId: number + declare countryId: number } User.boot() class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasManyThrough([() => Post, () => User], { onQuery: (query) => query.where('title', 'Adonis 101'), }) - public posts: HasManyThrough + declare posts: HasManyThrough } Country.boot() diff --git a/test/orm/model-has-one.spec.ts b/test/orm/model_has_one.spec.ts similarity index 66% rename from test/orm/model-has-one.spec.ts rename to test/orm/model_has_one.spec.ts index 4e4c639e..ea40c7a8 100644 --- a/test/orm/model-has-one.spec.ts +++ b/test/orm/model_has_one.spec.ts @@ -7,45 +7,39 @@ * file that was distributed with this source code. */ -/// - import { test } from '@japa/runner' -import type { HasOne, BelongsTo } from '@ioc:Adonis/Lucid/Orm' +import type { HasOne, BelongsTo } from '../../adonis-typings/relations.js' + +import { scope } from '../../src/orm/base_model/index.js' +import { column, hasOne, belongsTo } from '../../src/orm/decorators/index.js' +import { HasOneQueryBuilder } from '../../src/orm/relations/has_one/query_builder.js' -import { scope } from '../../src/Helpers/scope' -import { hasOne, column, belongsTo } from '../../src/Orm/Decorators' -import { HasOneQueryBuilder } from '../../src/Orm/Relations/HasOne/QueryBuilder' import { - fs, getDb, getBaseModel, ormAdapter, setup, cleanup, resetTables, - setupApplication, -} from '../../test-helpers' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -let db: ReturnType -let app: ApplicationContract -let BaseModel: ReturnType +} from '../../test-helpers/index.js' +import { AppFactory } from '@adonisjs/core/factories/app' test.group('Model | HasOne | Options', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) - test('raise error when localKey is missing', ({ assert }) => { + test('raise error when localKey is missing', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(1) try { @@ -53,20 +47,23 @@ test.group('Model | HasOne | Options', (group) => { class User extends BaseModel { @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } User.boot() User.$getRelation('profile')!.boot() } catch ({ message }) { - assert.equal( - message, - 'E_MISSING_MODEL_ATTRIBUTE: "User.profile" expects "id" to exist on "User" model, but is missing' - ) + assert.equal(message, '"User.profile" expects "id" to exist on "User" model, but is missing') } }) - test('raise error when foreignKey is missing', ({ assert }) => { + test('raise error when foreignKey is missing', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(1) try { @@ -75,10 +72,10 @@ test.group('Model | HasOne | Options', (group) => { class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } User.boot() @@ -86,24 +83,30 @@ test.group('Model | HasOne | Options', (group) => { } catch ({ message }) { assert.equal( message, - 'E_MISSING_MODEL_ATTRIBUTE: "User.profile" expects "userId" to exist on "Profile" model, but is missing' + '"User.profile" expects "userId" to exist on "Profile" model, but is missing' ) } }) - test('use primary key is as the local key', ({ assert }) => { + test('use primary key is as the local key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public userId: number + declare userId: number } Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } User.boot() @@ -112,22 +115,28 @@ test.group('Model | HasOne | Options', (group) => { assert.equal(User.$getRelation('profile')!['localKey'], 'id') }) - test('use custom defined local key', ({ assert }) => { + test('use custom defined local key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public userId: number + declare userId: number } Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column({ columnName: 'user_uid' }) - public uid: number + declare uid: number @hasOne(() => Profile, { localKey: 'uid' }) - public profile: HasOne + declare profile: HasOne } User.boot() @@ -136,19 +145,25 @@ test.group('Model | HasOne | Options', (group) => { assert.equal(User.$getRelation('profile')!['localKey'], 'uid') }) - test('compute foreign key from model name and primary key', ({ assert }) => { + test('compute foreign key from model name and primary key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public userId: number + declare userId: number } Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } User.boot() @@ -157,19 +172,25 @@ test.group('Model | HasOne | Options', (group) => { assert.equal(User.$getRelation('profile')!['foreignKey'], 'userId') }) - test('use pre defined foreign key', ({ assert }) => { + test('use pre defined foreign key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ columnName: 'user_id' }) - public userUid: number + declare userUid: number } Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile, { foreignKey: 'userUid' }) - public profile: HasOne + declare profile: HasOne } User.boot() @@ -178,19 +199,25 @@ test.group('Model | HasOne | Options', (group) => { assert.equal(User.$getRelation('profile')!['foreignKey'], 'userUid') }) - test('clone relationship instance with options', ({ assert }) => { + test('clone relationship instance with options', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ columnName: 'user_id' }) - public userUid: number + declare userUid: number } Profile.boot() class BaseUser extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile, { foreignKey: 'userUid' }) - public profile: HasOne + declare profile: HasOne } class User extends BaseUser {} @@ -205,30 +232,31 @@ test.group('Model | HasOne | Options', (group) => { test.group('Model | HasOne | Set Relations', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) - test('set related model instance', ({ assert }) => { + test('set related model instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column() - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } User.boot() @@ -240,18 +268,24 @@ test.group('Model | HasOne | Set Relations', (group) => { assert.deepEqual(user.profile, profile) }) - test('push related model instance', ({ assert }) => { + test('push related model instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column() - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } User.boot() @@ -263,18 +297,24 @@ test.group('Model | HasOne | Set Relations', (group) => { assert.deepEqual(user.profile, profile) }) - test('set many of related instances', ({ assert }) => { + test('set many of related instances', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public userId: number + declare userId: number } class User extends BaseModel { @column() - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } User.boot() @@ -304,43 +344,44 @@ test.group('Model | HasOne | Set Relations', (group) => { test.group('Model | HasOne | bulk operations', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('generate correct sql for selecting related rows', async ({ assert }) => { + test('generate correct sql for selecting related rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db.table('users').insert({ username: 'virk' }) @@ -360,27 +401,33 @@ test.group('Model | HasOne | bulk operations', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('generate correct sql for selecting related many rows', async ({ assert }) => { + test('generate correct sql for selecting related many rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db.table('users').multiInsert([{ username: 'virk' }, { username: 'nikk' }]) @@ -402,27 +449,33 @@ test.group('Model | HasOne | bulk operations', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('generate correct sql for updating related row', async ({ assert }) => { + test('generate correct sql for updating related row', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db.table('users').insert({ username: 'virk' }) @@ -448,27 +501,33 @@ test.group('Model | HasOne | bulk operations', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('generate correct sql for deleting related row', async ({ assert }) => { + test('generate correct sql for deleting related row', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db.table('users').insert({ username: 'virk' }) @@ -491,43 +550,44 @@ test.group('Model | HasOne | bulk operations', (group) => { test.group('Model | HasOne | sub queries', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('generate correct subquery for selecting rows', async ({ assert }) => { + test('generate correct subquery for selecting rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } User.boot() @@ -545,27 +605,33 @@ test.group('Model | HasOne | sub queries', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('create aggregate query', async ({ assert }) => { + test('create aggregate query', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } User.boot() @@ -588,27 +654,33 @@ test.group('Model | HasOne | sub queries', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('allow selecting custom columns', async ({ assert }) => { + test('allow selecting custom columns', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } User.boot() @@ -631,19 +703,25 @@ test.group('Model | HasOne | sub queries', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('generate correct self relationship subquery', async ({ assert }) => { + test('generate correct self relationship subquery', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public username: string + declare username: string @hasOne(() => User) - public parent: HasOne + declare parent: HasOne } User.boot() @@ -666,27 +744,33 @@ test.group('Model | HasOne | sub queries', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('raise exception when trying to execute the query', async ({ assert }) => { + test('raise exception when trying to execute the query', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } User.boot() @@ -708,32 +792,38 @@ test.group('Model | HasOne | sub queries', (group) => { assert.throws(firstOrFail, 'Cannot execute relationship subqueries') }) - test('run onQuery method when defined', async ({ assert }) => { + test('run onQuery method when defined', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public accountType: string + declare accountType: string @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile, { onQuery: (query) => query.where('accountType', 'twitter'), }) - public profile: HasOne + declare profile: HasOne } User.boot() @@ -757,40 +847,41 @@ test.group('Model | HasOne | sub queries', (group) => { test.group('Model | HasOne | preload', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('preload relationship', async ({ assert }) => { + test('preload relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db @@ -824,24 +915,31 @@ test.group('Model | HasOne | preload', (group) => { test('set relationship property value to null when no related rows were found', async ({ assert, + fs, }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db @@ -858,38 +956,44 @@ test.group('Model | HasOne | preload', (group) => { assert.isNull(users[1].profile) }) - test('preload nested relations', async ({ assert }) => { + test('preload nested relations', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Identity extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public profileId: number + declare profileId: number @column() - public identityName: string + declare identityName: string } class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @hasOne(() => Identity) - public identity: HasOne + declare identity: HasOne } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db @@ -935,27 +1039,33 @@ test.group('Model | HasOne | preload', (group) => { assert.instanceOf(user!.profile!.identity, Identity) }) - test('preload self referenced relationship', async ({ assert }) => { + test('preload self referenced relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db @@ -987,24 +1097,30 @@ test.group('Model | HasOne | preload', (group) => { assert.deepEqual(users[1].profile.user.id, users[1].id) }) - test('add constraints during preload', async ({ assert }) => { + test('add constraints during preload', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db @@ -1038,24 +1154,30 @@ test.group('Model | HasOne | preload', (group) => { assert.isNull(users[1].profile) }) - test('cherry pick columns during preload', async ({ assert }) => { + test('cherry pick columns during preload', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db @@ -1089,24 +1211,30 @@ test.group('Model | HasOne | preload', (group) => { assert.deepEqual(users[1].profile.$extras, {}) }) - test('do not repeat fk when already defined', async ({ assert }) => { + test('do not repeat fk when already defined', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db @@ -1140,24 +1268,30 @@ test.group('Model | HasOne | preload', (group) => { assert.deepEqual(users[1].profile.$extras, {}) }) - test('pass sideloaded attributes to the relationship', async ({ assert }) => { + test('pass sideloaded attributes to the relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db @@ -1191,24 +1325,30 @@ test.group('Model | HasOne | preload', (group) => { assert.deepEqual(users[1].profile.$sideloaded, { id: 1 }) }) - test('preload using model instance', async ({ assert }) => { + test('preload using model instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db @@ -1241,26 +1381,32 @@ test.group('Model | HasOne | preload', (group) => { assert.equal(users[1].profile.userId, users[1].id) }) - test('raise exception when local key is not selected', async ({ assert }) => { + test('raise exception when local key is not selected', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(1) class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db @@ -1290,38 +1436,44 @@ test.group('Model | HasOne | preload', (group) => { } }) - test('preload nested relations using model instance', async ({ assert }) => { + test('preload nested relations using model instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Identity extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public profileId: number + declare profileId: number @column() - public identityName: string + declare identityName: string } class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @hasOne(() => Identity) - public identity: HasOne + declare identity: HasOne } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db @@ -1376,38 +1528,44 @@ test.group('Model | HasOne | preload', (group) => { assert.instanceOf(users[1].profile!.identity, Identity) }) - test('pass main query options down the chain', async ({ assert }) => { + test('pass main query options down the chain', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Identity extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public profileId: number + declare profileId: number @column() - public identityName: string + declare identityName: string } class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @hasOne(() => Identity) - public identity: HasOne + declare identity: HasOne } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db @@ -1457,84 +1615,30 @@ test.group('Model | HasOne | preload', (group) => { assert.equal(user!.profile.identity.$options!.connection, 'secondary') }) - test('pass relationship metadata to the profiler', async ({ assert }) => { - assert.plan(1) + test('do not run preload query when parent rows are empty', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne - } - - await db - .insertQuery() - .table('users') - .insert([{ username: 'virk' }, { username: 'nikk' }]) - - const [user0, user1] = await db.query().from('users') - await db - .insertQuery() - .table('profiles') - .insert([ - { - user_id: user0.id, - display_name: 'virk', - }, - { - user_id: user1.id, - display_name: 'nikk', - }, - ]) - - const profiler = app.profiler - - let profilerPacketIndex = 0 - profiler.process((packet) => { - if (profilerPacketIndex === 1) { - assert.deepEqual(packet.data.relation, { - model: 'User', - relatedModel: 'Profile', - type: 'hasOne', - }) - } - profilerPacketIndex++ - }) - - User.boot() - await User.query({ profiler }).preload('profile') - }) - - test('do not run preload query when parent rows are empty', async ({ assert }) => { - class Profile extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @column() - public userId: number - - @column() - public displayName: string - } - - class User extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } User.boot() @@ -1549,40 +1653,41 @@ test.group('Model | HasOne | preload', (group) => { test.group('Model | HasOne | withCount', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('get count of a relationship rows', async ({ assert }) => { + test('get count of a relationship rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db @@ -1614,27 +1719,33 @@ test.group('Model | HasOne | withCount', (group) => { assert.equal(users[1].$extras.profile_count, 1) }) - test('allow cherry picking columns', async ({ assert }) => { + test('allow cherry picking columns', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: number + declare username: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db @@ -1666,24 +1777,30 @@ test.group('Model | HasOne | withCount', (group) => { assert.deepEqual(users[1].$attributes, { username: 'nikk' }) }) - test('lazy load related count', async ({ assert }) => { + test('lazy load related count', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db @@ -1714,16 +1831,22 @@ test.group('Model | HasOne | withCount', (group) => { assert.deepEqual(Number(user.$extras.profile_count), 1) }) - test('lazy load count of self referenced relationship', async ({ assert }) => { + test('lazy load count of self referenced relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public parentId: number + declare parentId: number @hasOne(() => User, { foreignKey: 'parentId' }) - public manager: HasOne + declare manager: HasOne } await db @@ -1742,43 +1865,44 @@ test.group('Model | HasOne | withCount', (group) => { test.group('Model | HasOne | has', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('limit rows to the existance of relationship', async ({ assert }) => { + test('limit rows to the existance of relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db @@ -1808,43 +1932,44 @@ test.group('Model | HasOne | has', (group) => { test.group('Model | HasOne | whereHas', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('limit rows to the existance of relationship', async ({ assert }) => { + test('limit rows to the existance of relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db @@ -1887,43 +2012,44 @@ test.group('Model | HasOne | whereHas', (group) => { test.group('Model | HasOne | save', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('save related instance', async ({ assert }) => { + test('save related instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } const user = new User() @@ -1939,29 +2065,35 @@ test.group('Model | HasOne | save', (group) => { assert.equal(user.id, profile.userId) }) - test('wrap save calls inside a managed transaction', async ({ assert }) => { + test('wrap save calls inside a managed transaction', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(3) class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } const user = new User() @@ -1981,29 +2113,35 @@ test.group('Model | HasOne | save', (group) => { assert.lengthOf(profiles, 0) }) - test('use parent model transaction when its defined', async ({ assert }) => { + test('use parent model transaction when its defined', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(4) class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } const trx = await db.transaction() @@ -2031,43 +2169,44 @@ test.group('Model | HasOne | save', (group) => { test.group('Model | HasOne | create', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('create related instance', async ({ assert }) => { + test('create related instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } const user = new User() @@ -2082,29 +2221,35 @@ test.group('Model | HasOne | create', (group) => { assert.equal(user.id, profile.userId) }) - test('wrap create call inside a managed transaction', async ({ assert }) => { + test('wrap create call inside a managed transaction', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(3) class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } const user = new User() @@ -2123,27 +2268,33 @@ test.group('Model | HasOne | create', (group) => { assert.lengthOf(profiles, 0) }) - test('use parent model transaction during create', async ({ assert }) => { + test('use parent model transaction during create', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } const trx = await db.transaction() @@ -2169,43 +2320,44 @@ test.group('Model | HasOne | create', (group) => { test.group('Model | HasOne | firstOrCreate', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test("create related instance when there isn't any existing row", async ({ assert }) => { + test("create related instance when there isn't any existing row", async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } const user = new User() @@ -2225,27 +2377,33 @@ test.group('Model | HasOne | firstOrCreate', (group) => { assert.equal(profile.displayName, 'Hvirk') }) - test('return the existing row vs creating a new one', async ({ assert }) => { + test('return the existing row vs creating a new one', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } const user = new User() @@ -2272,43 +2430,44 @@ test.group('Model | HasOne | firstOrCreate', (group) => { test.group('Model | HasOne | updateOrCreate', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test("create related instance when there isn't any existing row", async ({ assert }) => { + test("create related instance when there isn't any existing row", async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } const user = new User() @@ -2332,27 +2491,33 @@ test.group('Model | HasOne | updateOrCreate', (group) => { assert.equal(profiles[0].display_name, 'Virk') }) - test('update the existing row vs creating a new one', async ({ assert }) => { + test('update the existing row vs creating a new one', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } const user = new User() @@ -2380,45 +2545,46 @@ test.group('Model | HasOne | updateOrCreate', (group) => { test.group('Model | HasOne | pagination', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('dis-allow pagination', async ({ assert }) => { + test('dis-allow pagination', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(1) class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db.table('users').insert({ username: 'virk' }) @@ -2434,45 +2600,46 @@ test.group('Model | HasOne | pagination', (group) => { test.group('Model | HasOne | clone', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('clone related query builder', async ({ assert }) => { + test('clone related query builder', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(1) class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } await db.table('users').insert({ username: 'virk' }) @@ -2485,47 +2652,48 @@ test.group('Model | HasOne | clone', (group) => { test.group('Model | HasOne | scopes', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('apply scopes during eagerload', async ({ assert }) => { + test('apply scopes during eagerload', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string - public static twitter = scope((query) => { + static twitter = scope((query) => { query.where('type', 'twitter') }) } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } const [row] = await db @@ -2549,31 +2717,37 @@ test.group('Model | HasOne | scopes', (group) => { assert.instanceOf(userWithScopes.profile, Profile) }) - test('apply scopes on related query', async ({ assert }) => { + test('apply scopes on related query', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string - public static twitter = scope((query) => { + static twitter = scope((query) => { query.where('type', 'twitter') }) } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } const [row] = await db @@ -2602,45 +2776,46 @@ test.group('Model | HasOne | scopes', (group) => { test.group('Model | HasOne | onQuery', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('invoke onQuery method when preloading relationship', async ({ assert }) => { + test('invoke onQuery method when preloading relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile, { onQuery: (query) => query.where('type', 'twitter'), }) - public profile: HasOne + declare profile: HasOne } const [row] = await db @@ -2657,26 +2832,32 @@ test.group('Model | HasOne | onQuery', (group) => { assert.isNull(user.profile) }) - test('do not invoke onQuery method on preloading subqueries', async ({ assert }) => { + test('do not invoke onQuery method on preloading subqueries', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(2) class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile, { onQuery: (query) => { @@ -2684,7 +2865,7 @@ test.group('Model | HasOne | onQuery', (group) => { query.where('type', 'twitter') }, }) - public profile: HasOne + declare profile: HasOne } const [row] = await db @@ -2703,29 +2884,35 @@ test.group('Model | HasOne | onQuery', (group) => { assert.isNull(user.profile) }) - test('invoke onQuery method on related query builder', async ({ assert }) => { + test('invoke onQuery method on related query builder', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile, { onQuery: (query) => query.where('type', 'twitter'), }) - public profile: HasOne + declare profile: HasOne } const [row] = await db @@ -2743,29 +2930,38 @@ test.group('Model | HasOne | onQuery', (group) => { assert.isNull(profile) }) - test('do not invoke onQuery method on related query builder subqueries', async ({ assert }) => { + test('do not invoke onQuery method on related query builder subqueries', async ({ + fs, + assert, + }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile, { onQuery: (query) => query.where('type', 'twitter'), }) - public profile: HasOne + declare profile: HasOne } const [row] = await db @@ -2806,43 +3002,44 @@ test.group('Model | HasOne | onQuery', (group) => { test.group('Model | HasOne | delete', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('delete related instance', async ({ assert }) => { + test('delete related instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } const user = new User() diff --git a/test/orm/model-many-to-many.spec.ts b/test/orm/model_many_to_many.spec.ts similarity index 73% rename from test/orm/model-many-to-many.spec.ts rename to test/orm/model_many_to_many.spec.ts index 5c7c7f0f..62b6f278 100644 --- a/test/orm/model-many-to-many.spec.ts +++ b/test/orm/model_many_to_many.spec.ts @@ -7,48 +7,43 @@ * file that was distributed with this source code. */ -/// - import { test } from '@japa/runner' -import type { ManyToMany } from '@ioc:Adonis/Lucid/Orm' +import type { ManyToMany } from '../../adonis-typings/relations.js' + +import { scope } from '../../src/orm/base_model/index.js' +import { column, manyToMany } from '../../src/orm/decorators/index.js' +import { ManyToManyQueryBuilder } from '../../src/orm/relations/many_to_many/query_builder.js' -import { scope } from '../../src/Helpers/scope' -import { manyToMany, column } from '../../src/Orm/Decorators' -import { ManyToManyQueryBuilder } from '../../src/Orm/Relations/ManyToMany/QueryBuilder' import { - fs, getDb, getBaseModel, ormAdapter, setup, resetTables, cleanup, - setupApplication, -} from '../../test-helpers' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' -import { DateTime } from 'luxon' +} from '../../test-helpers/index.js' -let db: ReturnType -let app: ApplicationContract -let BaseModel: ReturnType +import { DateTime } from 'luxon' +import { AppFactory } from '@adonisjs/core/factories/app' const sleep = (time: number) => new Promise((resolve) => setTimeout(resolve, time)) test.group('Model | ManyToMany | Options', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) - test('raise error when localKey is missing', ({ assert }) => { + test('raise error when localKey is missing', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(1) try { @@ -56,31 +51,34 @@ test.group('Model | ManyToMany | Options', (group) => { class User extends BaseModel { @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() User.$getRelation('skills')!.boot() } catch ({ message }) { - assert.equal( - message, - 'E_MISSING_MODEL_ATTRIBUTE: "User.skills" expects "id" to exist on "User" model, but is missing' - ) + assert.equal(message, '"User.skills" expects "id" to exist on "User" model, but is missing') } }) - test('use primary key as the local key', ({ assert }) => { + test('use primary key as the local key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.$getRelation('skills')!.boot() @@ -89,21 +87,27 @@ test.group('Model | ManyToMany | Options', (group) => { assert.equal(User.$getRelation('skills')!['localKeyColumnName'], 'id') }) - test('use custom defined local key', ({ assert }) => { + test('use custom defined local key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public uid: number + declare uid: number @manyToMany(() => Skill, { localKey: 'uid' }) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -113,7 +117,13 @@ test.group('Model | ManyToMany | Options', (group) => { assert.equal(User.$getRelation('skills')!['localKeyColumnName'], 'uid') }) - test('raise error when relatedKey is missing', ({ assert }) => { + test('raise error when relatedKey is missing', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(1) try { @@ -122,34 +132,37 @@ test.group('Model | ManyToMany | Options', (group) => { class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() User.$getRelation('skills')!.boot() } catch ({ message }) { - assert.equal( - message, - 'E_MISSING_MODEL_ATTRIBUTE: "User.skills" expects "id" to exist on "Skill" model, but is missing' - ) + assert.equal(message, '"User.skills" expects "id" to exist on "Skill" model, but is missing') } }) - test('use related model primary key as the related key', ({ assert }) => { + test('use related model primary key as the related key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.$getRelation('skills')!.boot() @@ -158,21 +171,27 @@ test.group('Model | ManyToMany | Options', (group) => { assert.equal(User.$getRelation('skills')!['relatedKeyColumnName'], 'id') }) - test('use custom defined related key', ({ assert }) => { + test('use custom defined related key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public uid: number + declare uid: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill, { relatedKey: 'uid' }) - public skills: ManyToMany + declare skills: ManyToMany } User.$getRelation('skills')!.boot() @@ -181,18 +200,24 @@ test.group('Model | ManyToMany | Options', (group) => { assert.equal(User.$getRelation('skills')!['relatedKeyColumnName'], 'uid') }) - test('compute pivotForeignKey from table name + primary key', ({ assert }) => { + test('compute pivotForeignKey from table name + primary key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.$getRelation('skills')!.boot() @@ -200,18 +225,24 @@ test.group('Model | ManyToMany | Options', (group) => { assert.equal(User.$getRelation('skills')!['pivotForeignKey'], 'user_id') }) - test('use custom defined pivotForeignKey', ({ assert }) => { + test('use custom defined pivotForeignKey', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill, { pivotForeignKey: 'user_uid' }) - public skills: ManyToMany + declare skills: ManyToMany } User.$getRelation('skills')!.boot() @@ -219,18 +250,27 @@ test.group('Model | ManyToMany | Options', (group) => { assert.equal(User.$getRelation('skills')!['pivotForeignKey'], 'user_uid') }) - test('compute relatedPivotForeignKey from related model name + primary key', ({ assert }) => { + test('compute relatedPivotForeignKey from related model name + primary key', async ({ + fs, + assert, + }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -239,18 +279,24 @@ test.group('Model | ManyToMany | Options', (group) => { assert.equal(User.$getRelation('skills')!['pivotRelatedForeignKey'], 'skill_id') }) - test('use custom defined relatedPivotForeignKey', ({ assert }) => { + test('use custom defined relatedPivotForeignKey', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill, { pivotRelatedForeignKey: 'skill_uid' }) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -259,18 +305,24 @@ test.group('Model | ManyToMany | Options', (group) => { assert.equal(User.$getRelation('skills')!['pivotRelatedForeignKey'], 'skill_uid') }) - test('clone relationship instance with options', ({ assert }) => { + test('clone relationship instance with options', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class BaseUser extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill, { pivotRelatedForeignKey: 'skill_uid' }) - public skills: ManyToMany + declare skills: ManyToMany } class User extends BaseUser {} @@ -284,30 +336,31 @@ test.group('Model | ManyToMany | Options', (group) => { test.group('Model | ManyToMany | Set Relations', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) - test('set related model instance', ({ assert }) => { + test('set related model instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.$getRelation('skills')!.boot() @@ -318,18 +371,24 @@ test.group('Model | ManyToMany | Set Relations', (group) => { assert.deepEqual(user.skills, [skill]) }) - test('push related model instance', ({ assert }) => { + test('push related model instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.$getRelation('skills')!.boot() @@ -343,21 +402,27 @@ test.group('Model | ManyToMany | Set Relations', (group) => { assert.deepEqual(user.skills, [skill, skill1]) }) - test('set many of related instances', ({ assert }) => { + test('set many of related instances', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => User) - public users: ManyToMany + declare users: ManyToMany } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.$getRelation('skills')!.boot() @@ -396,34 +461,35 @@ test.group('Model | ManyToMany | Set Relations', (group) => { test.group('Model | ManyToMany | bulk operations', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('generate correct sql for selecting related rows', async ({ assert }) => { + test('generate correct sql for selecting related rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } await db.table('users').insert({ username: 'virk' }) @@ -448,18 +514,24 @@ test.group('Model | ManyToMany | bulk operations', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('generate correct sql for selecting related for many rows', async ({ assert }) => { + test('generate correct sql for selecting related for many rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } await db.table('users').multiInsert([{ username: 'virk' }, { username: 'nikk' }]) @@ -487,20 +559,26 @@ test.group('Model | ManyToMany | bulk operations', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('select extra columns', async ({ assert }) => { + test('select extra columns', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill, { pivotColumns: ['score'], }) - public skills: ManyToMany + declare skills: ManyToMany } await db.table('users').insert({ username: 'virk' }) @@ -526,18 +604,24 @@ test.group('Model | ManyToMany | bulk operations', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('select extra columns at runtime', async ({ assert }) => { + test('select extra columns at runtime', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } await db.table('users').insert({ username: 'virk' }) @@ -563,18 +647,24 @@ test.group('Model | ManyToMany | bulk operations', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('generate correct sql for updating rows', async ({ assert }) => { + test('generate correct sql for updating rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } await db.table('users').insert({ username: 'virk' }) @@ -596,18 +686,24 @@ test.group('Model | ManyToMany | bulk operations', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('generate correct sql for deleting rows', async ({ assert }) => { + test('generate correct sql for deleting rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } await db.table('users').insert({ username: 'virk' }) @@ -627,23 +723,29 @@ test.group('Model | ManyToMany | bulk operations', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('convert timestamps instance of Luxon', async ({ assert }) => { + test('convert timestamps instance of Luxon', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill, { pivotTimestamps: true, }) - public skills: ManyToMany + declare skills: ManyToMany } await db @@ -680,34 +782,35 @@ test.group('Model | ManyToMany | bulk operations', (group) => { test.group('Model | ManyToMany | sub queries', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('generate correct sub query for selecting rows', async ({ assert }) => { + test('generate correct sub query for selecting rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -726,18 +829,24 @@ test.group('Model | ManyToMany | sub queries', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('create aggregate query', async ({ assert }) => { + test('create aggregate query', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -761,18 +870,24 @@ test.group('Model | ManyToMany | sub queries', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('allow selecting custom columns', async ({ assert }) => { + test('allow selecting custom columns', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -796,17 +911,23 @@ test.group('Model | ManyToMany | sub queries', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('generate correct self relationship subquery', async ({ assert }) => { + test('generate correct self relationship subquery', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => User, { pivotTable: 'follows', pivotForeignKey: 'user_id', pivotRelatedForeignKey: 'following_user_id', }) - public follows: ManyToMany + declare follows: ManyToMany } User.boot() @@ -826,17 +947,23 @@ test.group('Model | ManyToMany | sub queries', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add where pivot clause when self relationship subQuery', async ({ assert }) => { + test('add where pivot clause when self relationship subQuery', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => User, { pivotTable: 'follows', pivotForeignKey: 'user_id', pivotRelatedForeignKey: 'following_user_id', }) - public follows: ManyToMany + declare follows: ManyToMany } User.boot() @@ -864,18 +991,24 @@ test.group('Model | ManyToMany | sub queries', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('allow selecting custom pivot columns', async ({ assert }) => { + test('allow selecting custom pivot columns', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -899,23 +1032,29 @@ test.group('Model | ManyToMany | sub queries', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('run onQuery method when defined', async ({ assert }) => { + test('run onQuery method when defined', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill, { onQuery: (query) => query.where('name', 'Programming'), }) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -940,34 +1079,35 @@ test.group('Model | ManyToMany | sub queries', (group) => { test.group('Model | Many To Many | aggregates', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('get total of all related rows', async ({ assert }) => { + test('get total of all related rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } await db.table('users').insert({ username: 'virk' }) @@ -986,18 +1126,24 @@ test.group('Model | Many To Many | aggregates', (group) => { assert.deepEqual(Number(total[0].$extras.total), 2) }) - test('select extra columns with count', async ({ assert }) => { + test('select extra columns with count', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } await db.table('users').insert({ username: 'virk' }) @@ -1027,18 +1173,24 @@ test.group('Model | Many To Many | aggregates', (group) => { assert.equal(Number(total[1].$extras.total), 1) }) - test('select extra pivot columns with count', async ({ assert }) => { + test('select extra pivot columns with count', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } await db.table('users').insert({ username: 'virk' }) @@ -1072,37 +1224,38 @@ test.group('Model | Many To Many | aggregates', (group) => { test.group('Model | ManyToMany | preload', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('preload relation', async ({ assert }) => { + test('preload relation', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -1132,23 +1285,29 @@ test.group('Model | ManyToMany | preload', (group) => { assert.equal(users[0].skills[0].$extras.pivot_skill_id, 1) }) - test('convert dates to luxon datetime instance during preload', async ({ assert }) => { + test('convert dates to luxon datetime instance during preload', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill, { pivotTimestamps: true, }) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -1182,21 +1341,27 @@ test.group('Model | ManyToMany | preload', (group) => { assert.instanceOf(users[0].skills[0].$extras.pivot_updated_at, DateTime) }) - test('preload relation for many', async ({ assert }) => { + test('preload relation for many', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -1245,21 +1410,27 @@ test.group('Model | ManyToMany | preload', (group) => { assert.equal(users[1].skills[0].$extras.pivot_skill_id, 2) }) - test('preload relation using model instance', async ({ assert }) => { + test('preload relation using model instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -1314,23 +1485,30 @@ test.group('Model | ManyToMany | preload', (group) => { test('convert dates to luxon datetime instance when preload using model instance', async ({ assert, + fs, }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill, { pivotTimestamps: true, }) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -1366,24 +1544,30 @@ test.group('Model | ManyToMany | preload', (group) => { assert.instanceOf(users[0].skills[0].$extras.pivot_updated_at, DateTime) }) - test('select extra pivot columns', async ({ assert }) => { + test('select extra pivot columns', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string @column() - public proficiency: string + declare proficiency: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill, { pivotColumns: ['proficiency'] }) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -1438,24 +1622,30 @@ test.group('Model | ManyToMany | preload', (group) => { assert.equal(users[1].skills[0].$extras.pivot_proficiency, 'beginner') }) - test('select extra pivot columns at runtime', async ({ assert }) => { + test('select extra pivot columns at runtime', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string @column() - public proficiency: string + declare proficiency: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -1513,21 +1703,27 @@ test.group('Model | ManyToMany | preload', (group) => { assert.equal(users[1].skills[0].$extras.pivot_proficiency, 'beginner') }) - test('cherry pick columns during preload', async ({ assert }) => { + test('cherry pick columns during preload', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -1559,23 +1755,29 @@ test.group('Model | ManyToMany | preload', (group) => { assert.deepEqual(users[0].skills[0].$extras, { pivot_user_id: 1, pivot_skill_id: 1 }) }) - test('raise error when local key is not selected', async ({ assert }) => { + test('raise error when local key is not selected', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(1) class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -1613,21 +1815,27 @@ test.group('Model | ManyToMany | preload', (group) => { } }) - test('do not run preload query when parent rows are empty', async ({ assert }) => { + test('do not run preload query when parent rows are empty', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -1641,37 +1849,38 @@ test.group('Model | ManyToMany | preload', (group) => { test.group('Model | ManyToMany | withCount', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('get count of a relationship rows', async ({ assert }) => { + test('get count of a relationship rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -1710,21 +1919,27 @@ test.group('Model | ManyToMany | withCount', (group) => { assert.deepEqual(Number(users[1].$extras.skills_count), 1) }) - test('apply constraints to the withCount subquery', async ({ assert }) => { + test('apply constraints to the withCount subquery', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -1767,21 +1982,27 @@ test.group('Model | ManyToMany | withCount', (group) => { assert.deepEqual(Number(users[1].$extras.skills_count), 0) }) - test('allow subquery to have custom aggregates', async ({ assert }) => { + test('allow subquery to have custom aggregates', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -1824,24 +2045,30 @@ test.group('Model | ManyToMany | withCount', (group) => { assert.deepEqual(Number(users[1].$extras.skillsCount), 1) }) - test('allow cherry picking columns', async ({ assert }) => { + test('allow cherry picking columns', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -1880,17 +2107,23 @@ test.group('Model | ManyToMany | withCount', (group) => { assert.deepEqual(users[1].$attributes, { username: 'nikk' }) }) - test('get count of self relationship', async ({ assert }) => { + test('get count of self relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => User, { pivotTable: 'follows', pivotForeignKey: 'user_id', pivotRelatedForeignKey: 'following_user_id', }) - public follows: ManyToMany + declare follows: ManyToMany } User.boot() @@ -1932,24 +2165,30 @@ test.group('Model | ManyToMany | withCount', (group) => { assert.deepEqual(Number(users[3].$extras.follows_count), 0) }) - test('define custom alias for the count', async ({ assert }) => { + test('define custom alias for the count', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -1993,29 +2232,35 @@ test.group('Model | ManyToMany | withCount', (group) => { assert.deepEqual(Number(users[1].$extras.mySkills), 1) }) - test('get count of a nested relationship rows', async ({ assert }) => { + test('get count of a nested relationship rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } class Group extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => User) - public users: ManyToMany + declare users: ManyToMany } Group.boot() @@ -2102,21 +2347,27 @@ test.group('Model | ManyToMany | withCount', (group) => { assert.deepEqual(Number(users[1].$extras.skills_count), 1) }) - test('lazy load count of relationship rows', async ({ assert }) => { + test('lazy load count of relationship rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -2150,21 +2401,27 @@ test.group('Model | ManyToMany | withCount', (group) => { assert.deepEqual(Number(user.$extras.skills_count), 2) }) - test('apply constraints to the loadCount subquery', async ({ assert }) => { + test('apply constraints to the loadCount subquery', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -2203,40 +2460,41 @@ test.group('Model | ManyToMany | withCount', (group) => { test.group('Model | ManyToMany | has', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('limit rows to the existance of relationship', async ({ assert }) => { + test('limit rows to the existance of relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -2269,24 +2527,30 @@ test.group('Model | ManyToMany | has', (group) => { assert.deepEqual(users[0].username, 'virk') }) - test('define expected number of rows', async ({ assert }) => { + test('define expected number of rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -2326,40 +2590,41 @@ test.group('Model | ManyToMany | has', (group) => { test.group('Model | ManyToMany | whereHas', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('limit rows to the existance of relationship', async ({ assert }) => { + test('limit rows to the existance of relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -2404,24 +2669,30 @@ test.group('Model | ManyToMany | whereHas', (group) => { assert.deepEqual(users[0].username, 'virk') }) - test('define expected number of rows', async ({ assert }) => { + test('define expected number of rows', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -2474,37 +2745,38 @@ test.group('Model | ManyToMany | whereHas', (group) => { if (process.env.DB !== 'mysql_legacy') { test.group('Model | ManyToMany | Group Limit', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('apply group limit', async ({ assert }) => { + test('apply group limit', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -2569,21 +2841,27 @@ if (process.env.DB !== 'mysql_legacy') { assert.equal(users[1].skills[1].$extras.pivot_skill_id, 4) }) - test('apply group limit with extra constraints', async ({ assert }) => { + test('apply group limit with extra constraints', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -2692,21 +2970,27 @@ if (process.env.DB !== 'mysql_legacy') { assert.equal(users[1].skills[1].$extras.pivot_skill_id, 3) }) - test('apply group limit and select custom columns', async ({ assert }) => { + test('apply group limit and select custom columns', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -2823,21 +3107,27 @@ if (process.env.DB !== 'mysql_legacy') { assert.equal(users[1].skills[1].$extras.pivot_proficiency, 'Master') }) - test('define custom order by clause', async ({ assert }) => { + test('define custom order by clause', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -2955,21 +3245,27 @@ if (process.env.DB !== 'mysql_legacy') { assert.equal(users[1].skills[1].$extras.pivot_proficiency, 'Master') }) - test('apply standard limit when not eagerloading', async ({ assert }) => { + test('apply standard limit when not eagerloading', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -3022,21 +3318,27 @@ if (process.env.DB !== 'mysql_legacy') { assert.deepEqual(bindings, knexBindings) }) - test('apply standard order by when not eagerloading', async ({ assert }) => { + test('apply standard order by when not eagerloading', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() @@ -3100,37 +3402,38 @@ if (process.env.DB !== 'mysql_legacy') { test.group('Model | ManyToMany | wherePivot', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) - test('add where clause', async ({ assert }) => { + test('add where clause', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query.wherePivot('username', 'virk').toSQL() @@ -3145,25 +3448,31 @@ test.group('Model | ManyToMany | wherePivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add where wrapped clause', async ({ assert }) => { + test('add where wrapped clause', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query .where((builder) => builder.wherePivot('username', 'virk')) @@ -3180,25 +3489,31 @@ test.group('Model | ManyToMany | wherePivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add where clause with operator', async ({ assert }) => { + test('add where clause with operator', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query.wherePivot('age', '>', 22).toSQL() @@ -3213,25 +3528,31 @@ test.group('Model | ManyToMany | wherePivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add where clause as a raw query', async ({ assert }) => { + test('add where clause as a raw query', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query .wherePivot('age', '>', db.rawQuery('select min_age from ages limit 1;')) @@ -3252,25 +3573,31 @@ test.group('Model | ManyToMany | wherePivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add orWhere clause', async ({ assert }) => { + test('add orWhere clause', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query.wherePivot('age', '>', 22).orWherePivot('age', 18).toSQL() @@ -3286,25 +3613,31 @@ test.group('Model | ManyToMany | wherePivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add orWhere wrapped clause', async ({ assert }) => { + test('add orWhere wrapped clause', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query .wherePivot('age', '>', 22) @@ -3326,97 +3659,42 @@ test.group('Model | ManyToMany | wherePivot', (group) => { assert.equal(sql, knexSql) assert.deepEqual(bindings, knexBindings) }) - - test('pass relationship metadata to the profiler', async ({ assert }) => { - assert.plan(1) - - class Skill extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @column() - public name: string - } - - class User extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @manyToMany(() => Skill) - public skills: ManyToMany - } - - User.boot() - await db - .insertQuery() - .table('users') - .insert([{ username: 'virk' }]) - await db - .insertQuery() - .table('skills') - .insert([{ name: 'Programming' }, { name: 'Dancing' }]) - await db - .insertQuery() - .table('skill_user') - .insert([ - { - user_id: 1, - skill_id: 1, - }, - ]) - - const profiler = app.profiler - - let profilerPacketIndex = 0 - profiler.process((packet) => { - if (profilerPacketIndex === 1) { - assert.deepEqual(packet.data.relation, { - model: 'User', - relatedModel: 'Skill', - pivotTable: 'skill_user', - type: 'manyToMany', - }) - } - profilerPacketIndex++ - }) - - await User.query({ profiler }).preload('skills') - }) }) test.group('Model | ManyToMany | whereNotPivot', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) - test('add where no clause', async ({ assert }) => { + test('add where no clause', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query.whereNotPivot('username', 'virk').toSQL() const { sql: knexSql, bindings: knexBindings } = db @@ -3430,25 +3708,31 @@ test.group('Model | ManyToMany | whereNotPivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add where not clause with operator', async ({ assert }) => { + test('add where not clause with operator', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query.whereNotPivot('age', '>', 22).toSQL() @@ -3463,25 +3747,31 @@ test.group('Model | ManyToMany | whereNotPivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add where not clause as a raw query', async ({ assert }) => { + test('add where not clause as a raw query', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query .whereNotPivot('age', '>', db.rawQuery('select min_age from ages limit 1;')) @@ -3502,25 +3792,31 @@ test.group('Model | ManyToMany | whereNotPivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add orWhereNot clause', async ({ assert }) => { + test('add orWhereNot clause', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query.whereNotPivot('age', '>', 22).orWhereNotPivot('age', 18).toSQL() @@ -3539,37 +3835,38 @@ test.group('Model | ManyToMany | whereNotPivot', (group) => { test.group('Model | ManyToMany | whereInPivot', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) - test('add whereIn clause', async ({ assert }) => { + test('add whereIn clause', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query.whereInPivot('username', ['virk', 'nikk']).toSQL() @@ -3584,25 +3881,31 @@ test.group('Model | ManyToMany | whereInPivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add whereIn as a query callback', async ({ assert }) => { + test('add whereIn as a query callback', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query .whereInPivot('username', (builder) => { @@ -3623,25 +3926,31 @@ test.group('Model | ManyToMany | whereInPivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add whereIn as a subquery', async ({ assert }) => { + test('add whereIn as a subquery', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query .whereInPivot('username', db.query().select('id').from('accounts')) @@ -3661,27 +3970,33 @@ test.group('Model | ManyToMany | whereInPivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add whereIn as a rawquery', async ({ assert }) => { + test('add whereIn as a rawquery', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + const ref = db.connection().getWriteClient().ref.bind(db.connection().getWriteClient()) class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query .whereInPivot('username', [db.rawQuery(`select ${ref('id')} from ${ref('accounts')}`)]) @@ -3703,25 +4018,31 @@ test.group('Model | ManyToMany | whereInPivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add whereIn as a subquery with array of keys', async ({ assert }) => { + test('add whereIn as a subquery with array of keys', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query .whereInPivot(['username', 'email'], db.query().select('username', 'email').from('accounts')) @@ -3741,25 +4062,31 @@ test.group('Model | ManyToMany | whereInPivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add whereIn as a 2d array', async ({ assert }) => { + test('add whereIn as a 2d array', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query.whereInPivot(['username', 'email'], [['foo', 'bar']]).toSQL() @@ -3774,25 +4101,31 @@ test.group('Model | ManyToMany | whereInPivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add orWhereIn clause', async ({ assert }) => { + test('add orWhereIn clause', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query .whereInPivot('username', ['virk', 'nikk']) @@ -3811,25 +4144,31 @@ test.group('Model | ManyToMany | whereInPivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add orWhereIn as a query callback', async ({ assert }) => { + test('add orWhereIn as a query callback', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query .whereInPivot('username', (builder) => { @@ -3859,37 +4198,38 @@ test.group('Model | ManyToMany | whereInPivot', (group) => { test.group('Model | ManyToMany | whereNotInPivot', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) - test('add whereNotIn clause', async ({ assert }) => { + test('add whereNotIn clause', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query.whereNotInPivot('username', ['virk', 'nikk']).toSQL() @@ -3904,25 +4244,31 @@ test.group('Model | ManyToMany | whereNotInPivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add whereNotIn as a query callback', async ({ assert }) => { + test('add whereNotIn as a query callback', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query .whereNotInPivot('username', (builder) => { @@ -3943,25 +4289,31 @@ test.group('Model | ManyToMany | whereNotInPivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add whereNotIn as a sub query', async ({ assert }) => { + test('add whereNotIn as a sub query', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query .whereNotInPivot('username', db.query().select('username').from('accounts')) @@ -3981,25 +4333,31 @@ test.group('Model | ManyToMany | whereNotInPivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add whereNotIn as a 2d array', async ({ assert }) => { + test('add whereNotIn as a 2d array', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query.whereNotInPivot(['username', 'email'], [['foo', 'bar']]).toSQL() @@ -4014,25 +4372,31 @@ test.group('Model | ManyToMany | whereNotInPivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add orWhereNotIn clause', async ({ assert }) => { + test('add orWhereNotIn clause', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query .whereNotInPivot('username', ['virk', 'nikk']) @@ -4051,25 +4415,31 @@ test.group('Model | ManyToMany | whereNotInPivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add orWhereNotIn as a subquery', async ({ assert }) => { + test('add orWhereNotIn as a subquery', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query .whereNotInPivot('username', (builder) => { @@ -4099,37 +4469,38 @@ test.group('Model | ManyToMany | whereNotInPivot', (group) => { test.group('Model | ManyToMany | whereNullPivot', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) - test('add where null clause', async ({ assert }) => { + test('add where null clause', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query.whereNullPivot('deleted_at').toSQL() @@ -4144,25 +4515,31 @@ test.group('Model | ManyToMany | whereNullPivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add where null wrapped clause', async ({ assert }) => { + test('add where null wrapped clause', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query .where((builder) => builder.whereNullPivot('deleted_at')) @@ -4179,25 +4556,31 @@ test.group('Model | ManyToMany | whereNullPivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add orWhere null clause', async ({ assert }) => { + test('add orWhere null clause', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query .whereNullPivot('deleted_at') @@ -4216,25 +4599,31 @@ test.group('Model | ManyToMany | whereNullPivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add orWhere null wrapped clause', async ({ assert }) => { + test('add orWhere null wrapped clause', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query .whereNullPivot('deleted_at') @@ -4260,37 +4649,38 @@ test.group('Model | ManyToMany | whereNullPivot', (group) => { test.group('Model | ManyToMany | whereNotNullPivot', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) - test('add where not null clause', async ({ assert }) => { + test('add where not null clause', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query.whereNotNullPivot('deleted_at').toSQL() @@ -4305,25 +4695,31 @@ test.group('Model | ManyToMany | whereNotNullPivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add where not null wrapped clause', async ({ assert }) => { + test('add where not null wrapped clause', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query .where((builder) => builder.whereNotNullPivot('deleted_at')) @@ -4340,25 +4736,31 @@ test.group('Model | ManyToMany | whereNotNullPivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add orWhere not null clause', async ({ assert }) => { + test('add orWhere not null clause', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query .whereNotNullPivot('deleted_at') @@ -4377,25 +4779,31 @@ test.group('Model | ManyToMany | whereNotNullPivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('add orWhere not null wrapped clause', async ({ assert }) => { + test('add orWhere not null wrapped clause', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } User.boot() const user = new User() const query = user!.related('skills').query() - query['appliedConstraints'] = true + ;(query as any)['appliedConstraints'] = true const { sql, bindings } = query .whereNotNullPivot('deleted_at') @@ -4421,40 +4829,41 @@ test.group('Model | ManyToMany | whereNotNullPivot', (group) => { test.group('Model | ManyToMany | save', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('save related instance', async ({ assert }) => { + test('save related instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -4483,24 +4892,30 @@ test.group('Model | ManyToMany | save', (group) => { assert.isUndefined(skill.$trx) }) - test('save related instance with pivot attributes', async ({ assert }) => { + test('save related instance with pivot attributes', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -4532,24 +4947,30 @@ test.group('Model | ManyToMany | save', (group) => { assert.isUndefined(skill.$trx) }) - test('do not attach duplicates when save is called more than once', async ({ assert }) => { + test('do not attach duplicates when save is called more than once', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -4580,24 +5001,30 @@ test.group('Model | ManyToMany | save', (group) => { assert.isUndefined(skill.$trx) }) - test('perform update with different pivot attributes', async ({ assert }) => { + test('perform update with different pivot attributes', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -4635,24 +5062,31 @@ test.group('Model | ManyToMany | save', (group) => { test('attach duplicates when save is called more than once with with checkExisting = false', async ({ assert, + fs, }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -4688,24 +5122,31 @@ test.group('Model | ManyToMany | save', (group) => { test('attach duplicates with different pivot attributes and with checkExisting = false', async ({ assert, + fs, }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -4747,24 +5188,31 @@ test.group('Model | ManyToMany | save', (group) => { test('attach when related pivot entry exists but for a different parent @sanityCheck', async ({ assert, + fs, }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -4802,26 +5250,32 @@ test.group('Model | ManyToMany | save', (group) => { assert.isUndefined(skill.$trx) }) - test('save related instance with timestamps', async ({ assert }) => { + test('save related instance with timestamps', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill, { pivotTimestamps: true, }) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -4852,26 +5306,32 @@ test.group('Model | ManyToMany | save', (group) => { assert.isUndefined(skill.$trx) }) - test('do not set created_at on update', async ({ assert }) => { + test('do not set created_at on update', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill, { pivotTimestamps: true, }) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -4908,21 +5368,27 @@ test.group('Model | ManyToMany | save', (group) => { assert.isUndefined(skill.$trx) }) - test('do not set updated_at when disabled', async ({ assert }) => { + test('do not set updated_at when disabled', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill, { pivotTimestamps: { @@ -4930,7 +5396,7 @@ test.group('Model | ManyToMany | save', (group) => { updatedAt: false, }, }) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -4961,21 +5427,27 @@ test.group('Model | ManyToMany | save', (group) => { assert.isUndefined(skill.$trx) }) - test('do not set created_at when disabled', async ({ assert }) => { + test('do not set created_at when disabled', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill, { pivotTimestamps: { @@ -4983,7 +5455,7 @@ test.group('Model | ManyToMany | save', (group) => { updatedAt: true, }, }) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -5014,24 +5486,30 @@ test.group('Model | ManyToMany | save', (group) => { assert.isUndefined(skill.$trx) }) - test('do not set timestamps when disabled', async ({ assert }) => { + test('do not set timestamps when disabled', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -5065,40 +5543,41 @@ test.group('Model | ManyToMany | save', (group) => { test.group('Model | ManyToMany | saveMany', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('save many of related instance', async ({ assert }) => { + test('save many of related instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -5134,24 +5613,30 @@ test.group('Model | ManyToMany | saveMany', (group) => { assert.isUndefined(skill1.$trx) }) - test('save many of related instance with pivot attributes', async ({ assert }) => { + test('save many of related instance with pivot attributes', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -5197,24 +5682,30 @@ test.group('Model | ManyToMany | saveMany', (group) => { assert.isUndefined(skill1.$trx) }) - test('allow pivot rows without custom pivot attributes', async ({ assert }) => { + test('allow pivot rows without custom pivot attributes', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -5258,24 +5749,33 @@ test.group('Model | ManyToMany | saveMany', (group) => { assert.isUndefined(skill1.$trx) }) - test('do not attach duplicates when saveMany is called more than once', async ({ assert }) => { + test('do not attach duplicates when saveMany is called more than once', async ({ + fs, + assert, + }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -5312,24 +5812,30 @@ test.group('Model | ManyToMany | saveMany', (group) => { assert.isUndefined(skill1.$trx) }) - test('update pivot row when saveMany is called more than once', async ({ assert }) => { + test('update pivot row when saveMany is called more than once', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -5385,24 +5891,31 @@ test.group('Model | ManyToMany | saveMany', (group) => { test('attach duplicates when saveMany is called more than once with checkExisting = false', async ({ assert, + fs, }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -5446,24 +5959,31 @@ test.group('Model | ManyToMany | saveMany', (group) => { test('attach when related pivot entry exists but for a different parent @sanityCheck', async ({ assert, + fs, }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -5509,24 +6029,30 @@ test.group('Model | ManyToMany | saveMany', (group) => { assert.isUndefined(skill1.$trx) }) - test('wrap saveMany inside a custom transaction', async ({ assert }) => { + test('wrap saveMany inside a custom transaction', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const trx = await db.transaction() @@ -5567,40 +6093,41 @@ test.group('Model | ManyToMany | saveMany', (group) => { test.group('Model | ManyToMany | create', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('create related instance', async ({ assert }) => { + test('create related instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -5626,24 +6153,30 @@ test.group('Model | ManyToMany | create', (group) => { assert.isUndefined(skill.$trx) }) - test('create related instance with pivot attributes', async ({ assert }) => { + test('create related instance with pivot attributes', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -5675,24 +6208,30 @@ test.group('Model | ManyToMany | create', (group) => { assert.isUndefined(skill.$trx) }) - test('wrap create inside a custom transaction', async ({ assert }) => { + test('wrap create inside a custom transaction', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const trx = await db.transaction() @@ -5726,40 +6265,41 @@ test.group('Model | ManyToMany | create', (group) => { test.group('Model | ManyToMany | createMany', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('create many of related instance', async ({ assert }) => { + test('create many of related instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -5793,24 +6333,30 @@ test.group('Model | ManyToMany | createMany', (group) => { assert.isUndefined(skill1.$trx) }) - test('create many of related instance with pivot attributes', async ({ assert }) => { + test('create many of related instance with pivot attributes', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -5849,24 +6395,30 @@ test.group('Model | ManyToMany | createMany', (group) => { assert.isUndefined(skill1.$trx) }) - test('allow pivot entries without custom attributes', async ({ assert }) => { + test('allow pivot entries without custom attributes', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -5905,24 +6457,30 @@ test.group('Model | ManyToMany | createMany', (group) => { assert.isUndefined(skill1.$trx) }) - test('wrap create many inside a custom transaction', async ({ assert }) => { + test('wrap create many inside a custom transaction', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const trx = await db.transaction() @@ -5954,40 +6512,41 @@ test.group('Model | ManyToMany | createMany', (group) => { test.group('Model | ManyToMany | attach', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('attach one or more ids to the pivot table', async ({ assert }) => { + test('attach one or more ids to the pivot table', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -6013,24 +6572,30 @@ test.group('Model | ManyToMany | attach', (group) => { assert.equal(skillUsers[1].skill_id, 2) }) - test('attach with extra attributes', async ({ assert }) => { + test('attach with extra attributes', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -6068,40 +6633,41 @@ test.group('Model | ManyToMany | attach', (group) => { test.group('Model | ManyToMany | detach', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('detach one or more ids from the pivot table', async ({ assert }) => { + test('detach one or more ids from the pivot table', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -6138,24 +6704,30 @@ test.group('Model | ManyToMany | detach', (group) => { assert.equal(skillUsers[0].skill_id, 2) }) - test('scope detach self to @sanityCheck', async ({ assert }) => { + test('scope detach self to @sanityCheck', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -6198,40 +6770,41 @@ test.group('Model | ManyToMany | detach', (group) => { test.group('Model | ManyToMany | sync', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test("sync ids by dropping only the missing one's", async ({ assert }) => { + test("sync ids by dropping only the missing one's", async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -6278,24 +6851,30 @@ test.group('Model | ManyToMany | sync', (group) => { assert.equal(skillUsers[1].skill_id, 1) }) - test('keep duplicates of the id under sync', async ({ assert }) => { + test('keep duplicates of the id under sync', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -6342,24 +6921,30 @@ test.group('Model | ManyToMany | sync', (group) => { assert.equal(skillUsers[1].skill_id, 1) }) - test('update pivot rows when additional properties are changed', async ({ assert }) => { + test('update pivot rows when additional properties are changed', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -6412,24 +6997,30 @@ test.group('Model | ManyToMany | sync', (group) => { assert.equal(skillUsers[1].proficiency, 'Master') }) - test('do not update pivot row when no extra properties are defined', async ({ assert }) => { + test('do not update pivot row when no extra properties are defined', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -6478,24 +7069,30 @@ test.group('Model | ManyToMany | sync', (group) => { assert.equal(skillUsers[1].proficiency, 'Master') }) - test('do not remove rows when detach = false', async ({ assert }) => { + test('do not remove rows when detach = false', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -6549,24 +7146,30 @@ test.group('Model | ManyToMany | sync', (group) => { assert.equal(skillUsers[2].proficiency, 'Master') }) - test('do not remove rows when nothing has changed', async ({ assert }) => { + test('do not remove rows when nothing has changed', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -6620,24 +7223,30 @@ test.group('Model | ManyToMany | sync', (group) => { assert.equal(skillUsers[2].proficiency, 'Master') }) - test('use custom transaction', async ({ assert }) => { + test('use custom transaction', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() @@ -6708,34 +7317,35 @@ test.group('Model | ManyToMany | sync', (group) => { test.group('Model | ManyToMany | pagination', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('paginate using related model query builder instance', async ({ assert }) => { + test('paginate using related model query builder instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } await db.table('users').insert({ username: 'virk' }) @@ -6786,20 +7396,26 @@ test.group('Model | ManyToMany | pagination', (group) => { }) }) - test('disallow paginate during preload', async ({ assert }) => { + test('disallow paginate during preload', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(1) class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } await db.table('users').insert({ username: 'virk' }) @@ -6833,34 +7449,35 @@ test.group('Model | ManyToMany | pagination', (group) => { test.group('Model | ManyToMany | clone', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('clone related model query builder', async ({ assert }) => { + test('clone related model query builder', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } await db.table('users').insert({ username: 'virk' }) @@ -6890,41 +7507,42 @@ test.group('Model | ManyToMany | clone', (group) => { test.group('Model | ManyToMany | scopes', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('apply scopes during eagerload', async ({ assert }) => { + test('apply scopes during eagerload', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string - public static programmingOnly = scope((query) => { + static programmingOnly = scope((query) => { query.where('name', 'Programming') }) } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } await db.table('users').insert({ username: 'virk' }) @@ -6959,25 +7577,31 @@ test.group('Model | ManyToMany | scopes', (group) => { assert.equal(user.skills[0].name, 'Programming') }) - test('apply scopes on related query', async ({ assert }) => { + test('apply scopes on related query', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string - public static programmingOnly = scope((query) => { + static programmingOnly = scope((query) => { query.where('name', 'Programming') }) } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } await db.table('users').insert({ username: 'virk' }) @@ -7014,39 +7638,40 @@ test.group('Model | ManyToMany | scopes', (group) => { test.group('Model | ManyToMany | onQuery', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('invoke onQuery method when preloading relationship', async ({ assert }) => { + test('invoke onQuery method when preloading relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill, { onQuery: (query) => query.where('name', 'Programming'), }) - public skills: ManyToMany + declare skills: ManyToMany } await db.table('users').insert({ username: 'virk' }) @@ -7073,20 +7698,26 @@ test.group('Model | ManyToMany | onQuery', (group) => { assert.equal(user.skills[0].name, 'Programming') }) - test('do not invoke onQuery method during preloading subqueries', async ({ assert }) => { + test('do not invoke onQuery method during preloading subqueries', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(3) class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill, { onQuery: (query) => { @@ -7094,7 +7725,7 @@ test.group('Model | ManyToMany | onQuery', (group) => { query.where('name', 'Programming') }, }) - public skills: ManyToMany + declare skills: ManyToMany } await db.table('users').insert({ username: 'virk' }) @@ -7126,23 +7757,29 @@ test.group('Model | ManyToMany | onQuery', (group) => { assert.equal(user.skills[0].name, 'Programming') }) - test('invoke onQuery method on related query builder', async ({ assert }) => { + test('invoke onQuery method on related query builder', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill, { onQuery: (query) => query.where('name', 'Programming'), }) - public skills: ManyToMany + declare skills: ManyToMany } await db.table('users').insert({ username: 'virk' }) @@ -7170,27 +7807,33 @@ test.group('Model | ManyToMany | onQuery', (group) => { assert.equal(skills[0].name, 'Programming') }) - test('invoke onQuery method on pivot query builder', async ({ assert }) => { + test('invoke onQuery method on pivot query builder', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(4) class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @manyToMany(() => Skill, { onQuery: (query) => { assert.isTrue('isPivotOnlyQuery' in query) }, }) - public skills: ManyToMany + declare skills: ManyToMany } await db.table('users').insert({ username: 'virk' }) @@ -7224,40 +7867,41 @@ test.group('Model | ManyToMany | onQuery', (group) => { test.group('Model | ManyToMany | delete', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('delete related instance', async ({ assert }) => { + test('delete related instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } const user = new User() diff --git a/test/orm/model-query-builder.spec.ts b/test/orm/model_query_builder.spec.ts similarity index 58% rename from test/orm/model-query-builder.spec.ts rename to test/orm/model_query_builder.spec.ts index a1cf4843..bc374a98 100644 --- a/test/orm/model-query-builder.spec.ts +++ b/test/orm/model_query_builder.spec.ts @@ -7,79 +7,85 @@ * file that was distributed with this source code. */ -/// - import { test } from '@japa/runner' -import { column } from '../../src/Orm/Decorators' -import { scope } from '../../src/Helpers/scope' -import { ModelQueryBuilder } from '../../src/Orm/QueryBuilder' +import { AppFactory } from '@adonisjs/core/factories/app' + +import { column } from '../../src/orm/decorators/index.js' +import { scope } from '../../src/orm/base_model/index.js' +import { ModelQueryBuilder } from '../../src/orm/query_builder/index.js' import { - fs, getDb, setup, cleanup, ormAdapter, resetTables, getBaseModel, - setupApplication, -} from '../../test-helpers' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -let db: ReturnType -let app: ApplicationContract -let BaseModel: ReturnType +} from '../../test-helpers/index.js' test.group('Model query builder', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('get instance of query builder for the given model', async ({ assert }) => { + test('get instance of query builder for the given model', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() assert.instanceOf(User.query(), ModelQueryBuilder) }) - test('pre select the table for the query builder instance', async ({ assert }) => { + test('pre select the table for the query builder instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() - assert.equal(User.query().knexQuery['_single'].table, 'users') + assert.equal((User.query().knexQuery as any)['_single'].table, 'users') }) - test('execute select queries', async ({ assert }) => { + test('execute select queries', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() @@ -94,13 +100,19 @@ test.group('Model query builder', (group) => { assert.deepEqual(users[0].$attributes, { id: 1, username: 'virk' }) }) - test('pass custom connection to the model instance', async ({ assert }) => { + test('pass custom connection to the model instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() @@ -116,13 +128,19 @@ test.group('Model query builder', (group) => { assert.deepEqual(users[0].$options!.connection, 'secondary') }) - test('pass sideloaded attributes to the model instance', async ({ assert }) => { + test('pass sideloaded attributes to the model instance', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() @@ -141,36 +159,19 @@ test.group('Model query builder', (group) => { assert.deepEqual(users[0].$sideloaded, { loggedInUser: { id: 1 } }) }) - test('pass custom profiler to the model instance', async ({ assert }) => { - class User extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @column() - public username: string - } + test('perform update using model query builder', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) - User.boot() - await db - .insertQuery() - .table('users') - .insert([{ username: 'virk' }, { username: 'nikk' }]) - - const profiler = app.profiler - const users = await User.query({ profiler }).where('username', 'virk') - assert.lengthOf(users, 1) - assert.instanceOf(users[0], User) - assert.deepEqual(users[0].$attributes, { id: 1, username: 'virk' }) - assert.deepEqual(users[0].$options!.profiler, profiler) - }) - - test('perform update using model query builder', async ({ assert }) => { class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() @@ -187,13 +188,19 @@ test.group('Model query builder', (group) => { assert.equal(user!.username, 'hvirk') }) - test('perform increment using model query builder', async ({ assert }) => { + test('perform increment using model query builder', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() @@ -210,13 +217,19 @@ test.group('Model query builder', (group) => { assert.equal(user!.points, 2) }) - test('perform decrement using model query builder', async ({ assert }) => { + test('perform decrement using model query builder', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() @@ -233,13 +246,19 @@ test.group('Model query builder', (group) => { assert.equal(user!.points, 2) }) - test('delete in bulk', async ({ assert }) => { + test('delete in bulk', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() @@ -256,13 +275,19 @@ test.group('Model query builder', (group) => { assert.isNull(user) }) - test('clone query builder', async ({ assert }) => { + test('clone query builder', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() @@ -272,13 +297,19 @@ test.group('Model query builder', (group) => { assert.instanceOf(clonedQuery, ModelQueryBuilder) }) - test('clone query builder with internal flags', async ({ assert }) => { + test('clone query builder with internal flags', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() @@ -288,13 +319,19 @@ test.group('Model query builder', (group) => { assert.isTrue(clonedQuery.hasGroupBy) }) - test('pass sideloaded data to cloned query', async ({ assert }) => { + test('pass sideloaded data to cloned query', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() @@ -308,15 +345,21 @@ test.group('Model query builder', (group) => { assert.deepEqual(user.$sideloaded, { username: 'virk' }) }) - test('apply scopes', async ({ assert }) => { + test('apply scopes', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string - public static active = scope((query) => { + static active = scope((query) => { query.where('is_active', true) }) } @@ -339,15 +382,21 @@ test.group('Model query builder', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('apply scopes inside a sub query', async ({ assert }) => { + test('apply scopes inside a sub query', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string - public static active = scope((query) => { + static active = scope((query) => { query.where('is_active', true) }) } @@ -370,13 +419,19 @@ test.group('Model query builder', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('make aggregate queries with the model query builder', async ({ assert }) => { + test('make aggregate queries with the model query builder', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string } User.boot() From 2ecaac6ea04ec4555d09a50ae6e8e721775450dc Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Tue, 19 Sep 2023 10:39:00 +0530 Subject: [PATCH 07/70] refactor: migrate factories codebase --- adonis-typings/factory.ts | 36 +- .../factory_builder.ts} | 73 +- .../factory_context.ts} | 6 +- .../factory_model.ts} | 142 ++- src/{Factory => factory}/index.ts | 21 +- .../Base.ts => factory/relations/base.ts} | 20 +- .../relations/belongs_to.ts} | 13 +- .../relations/has_many.ts} | 13 +- .../relations/has_one.ts} | 13 +- .../relations/many_to_many.ts} | 23 +- test-helpers/index.ts | 13 - ...{belongs-to.spec.ts => belongs_to.spec.ts} | 309 +++-- test/factory/factory-model.spec.ts | 270 ----- ...uilder.spec.ts => factory_builder.spec.ts} | 1046 +++++++++-------- test/factory/factory_model.spec.ts | 305 +++++ .../{has-many.spec.ts => has_many.spec.ts} | 494 ++++---- .../{has-one.spec.ts => has_one.spec.ts} | 270 ++--- ...y-to-many.spec.ts => many_to_many.spec.ts} | 345 +++--- 18 files changed, 1774 insertions(+), 1638 deletions(-) rename src/{Factory/FactoryBuilder.ts => factory/factory_builder.ts} (86%) rename src/{Factory/FactoryContext.ts => factory/factory_context.ts} (71%) rename src/{Factory/FactoryModel.ts => factory/factory_model.ts} (53%) rename src/{Factory => factory}/index.ts (58%) rename src/{Factory/Relations/Base.ts => factory/relations/base.ts} (71%) rename src/{Factory/Relations/BelongsTo.ts => factory/relations/belongs_to.ts} (72%) rename src/{Factory/Relations/HasMany.ts => factory/relations/has_many.ts} (75%) rename src/{Factory/Relations/HasOne.ts => factory/relations/has_one.ts} (75%) rename src/{Factory/Relations/ManyToMany.ts => factory/relations/many_to_many.ts} (74%) rename test/factory/{belongs-to.spec.ts => belongs_to.spec.ts} (59%) delete mode 100644 test/factory/factory-model.spec.ts rename test/factory/{factory-builder.spec.ts => factory_builder.spec.ts} (56%) create mode 100644 test/factory/factory_model.spec.ts rename test/factory/{has-many.spec.ts => has_many.spec.ts} (58%) rename test/factory/{has-one.spec.ts => has_one.spec.ts} (56%) rename test/factory/{many-to-many.spec.ts => many_to_many.spec.ts} (60%) diff --git a/adonis-typings/factory.ts b/adonis-typings/factory.ts index b6d686b8..a8bfd24c 100644 --- a/adonis-typings/factory.ts +++ b/adonis-typings/factory.ts @@ -191,17 +191,19 @@ export interface FactoryBuilderContract< /** * Define custom database connection */ - connection(connection: string): this + connection(connection: string): FactoryBuilderContract /** * Define custom query client */ - client(client: QueryClientContract): this + client(client: QueryClientContract): FactoryBuilderContract /** * Apply pre-defined state */ - apply(...states: K[]): this + apply( + ...states: K[] + ): FactoryBuilderContract /** * Create/make relationships for explicitly defined related factories @@ -219,14 +221,16 @@ export interface FactoryBuilderContract< } : never ) => void - ): this + ): FactoryBuilderContract /** * Define pivot attributes when persisting a many to many * relationship. Results in a noop, when not called * for a many to many relationship */ - pivotAttributes(attributes: ModelObject | ModelObject[]): this + pivotAttributes( + attributes: ModelObject | ModelObject[] + ): FactoryBuilderContract /** * Merge custom set of attributes. They are passed to the merge method of @@ -235,13 +239,15 @@ export interface FactoryBuilderContract< * For `createMany` and `makeMany`, you can pass an array of attributes mapped * according to the array index. */ - merge(attributes: OneOrMany>): this + merge( + attributes: OneOrMany> + ): FactoryBuilderContract /** * Merge custom set of attributes with the correct factory builder * model and all of its relationships as well */ - mergeRecursive(attributes: any): this + mergeRecursive(attributes: any): FactoryBuilderContract /** * Define custom runtime context. This method is usually called by @@ -251,7 +257,7 @@ export interface FactoryBuilderContract< * Do not define a custom context, unless you know what you are really * doing. */ - useCtx(ctx: FactoryContextContract): this + useCtx(ctx: FactoryContextContract): FactoryBuilderContract /** * Tap into the persistence layer of factory builder. Allows one @@ -262,9 +268,9 @@ export interface FactoryBuilderContract< callback: ( row: InstanceType, ctx: FactoryContextContract, - builder: this + builder: FactoryBuilderContract ) => void - ): this + ): FactoryBuilderContract /** * Make model instance without persitance. The make method @@ -356,6 +362,11 @@ export interface FactoryModelContract { callback: StateCallback ): this & { states: { [P in K]: StateCallback } } + /** + * Returns state callback + */ + getState(state: keyof this['states']): StateCallback + /** * Define a relationship on another factory */ @@ -364,6 +375,11 @@ export interface FactoryModelContract { callback: Relation ): this & { relations: { [P in K]: Relation } } + /** + * Returns registered relationship for a factory + */ + getRelation(relation: keyof this['relations']): FactoryRelationContract + /** * Define before hooks. Only `create` event is invoked * during the before lifecycle diff --git a/src/Factory/FactoryBuilder.ts b/src/factory/factory_builder.ts similarity index 86% rename from src/Factory/FactoryBuilder.ts rename to src/factory/factory_builder.ts index 1d4f9bda..ec7d12d6 100644 --- a/src/Factory/FactoryBuilder.ts +++ b/src/factory/factory_builder.ts @@ -7,22 +7,29 @@ * file that was distributed with this source code. */ -import { QueryClientContract } from '@ioc:Adonis/Lucid/Database' -import { LucidRow, LucidModel, ModelAdapterOptions, ModelObject } from '@ioc:Adonis/Lucid/Orm' +import { QueryClientContract } from '../../adonis-typings/database.js' +import { + LucidRow, + LucidModel, + ModelAdapterOptions, + ModelObject, +} from '../../adonis-typings/model.js' import { FactoryModelContract, FactoryContextContract, FactoryBuilderContract, FactoryRelationContract, -} from '@ioc:Adonis/Lucid/Factory' +} from '../../adonis-typings/factory.js' -import { FactoryModel } from './FactoryModel' -import { FactoryContext } from './FactoryContext' +import { FactoryModel } from './factory_model.js' +import { FactoryContext } from './factory_context.js' /** * Factory builder exposes the API to create/persist factory model instances. */ -export class FactoryBuilder implements FactoryBuilderContract> { +export class FactoryBuilder + implements FactoryBuilderContract> +{ /** * Relationships to setup. Do note: It is possible to load one relationship * twice. A practical use case is to apply different states. For example: @@ -102,7 +109,7 @@ export class FactoryBuilder implements FactoryBuilderContract void): this { + with(name: string, count?: number, callback?: (factory: never) => void): this { const relation = this.factory.getRelation(name) if (relation.relation.type === 'belongsTo') { - this.withBelongsToRelations.push({ name, count, callback }) + this.withBelongsToRelations.push({ name, count, callback: callback as any }) return this } - this.withRelations.push({ name, count, callback }) + this.withRelations.push({ name, count, callback: callback as any }) return this } @@ -345,7 +352,7 @@ export class FactoryBuilder implements FactoryBuilderContract this.appliedStates.add(state)) return this } @@ -354,7 +361,7 @@ export class FactoryBuilder implements FactoryBuilderContract void - ): this { + tap(callback: (row: LucidRow, state: FactoryContextContract, builder: this) => void): this { this.tapCallbacks.push(callback) return this } @@ -393,17 +398,17 @@ export class FactoryBuilder implements FactoryBuilderContract i) @@ -419,15 +424,15 @@ export class FactoryBuilder implements FactoryBuilderContract i) @@ -461,7 +466,7 @@ export class FactoryBuilder implements FactoryBuilderContract implements FactoryModelContr * Method to instantiate a new model instance. This method can be * overridden using the `newUp` public method. */ - public newUpModelInstance: NewUpCallback> = ( + newUpModelInstance: NewUpCallback> = ( attributes, _, model @@ -63,24 +61,27 @@ export class FactoryModel implements FactoryModelContr * Method to merge runtime attributes with the model instance. This method * can be overridden using the `merge` method. */ - public mergeAttributes: MergeCallback> = (model, attributes) => { + mergeAttributes: MergeCallback> = ( + model, + attributes + ) => { model.merge(attributes) } /** * A collection of factory states */ - public states: { [key: string]: StateCallback } = {} + states: { [key: string]: StateCallback } = {} /** * A collection of factory relations */ - public relations: { [relation: string]: FactoryRelationContract } = {} + relations: { [relation: string]: FactoryRelationContract } = {} /** * A set of registered hooks */ - public hooks = new Hooks() + hooks = new Hooks() constructor( public model: Model, @@ -91,16 +92,16 @@ export class FactoryModel implements FactoryModelContr /** * Register a before event hook */ - public before(event: EventsList, handler: HooksHandler): this { - this.hooks.add('before', event, handler) + before(event: 'makeStubbed' | 'create', handler: HooksHandler): this { + this.hooks.add(`before:${event}`, handler) return this } /** * Register an after event hook */ - public after(event: EventsList, handler: HooksHandler): this { - this.hooks.add('after', event, handler) + after(event: EventsList, handler: HooksHandler): this { + this.hooks.add(`after:${event}`, handler) return this } @@ -108,7 +109,7 @@ export class FactoryModel implements FactoryModelContr * Returns state callback defined on the model factory. Raises an * exception, when state is not registered */ - public getState(state: string): StateCallback { + getState(state: string): StateCallback { const stateCallback = this.states[state] if (!stateCallback) { throw new Error(`Cannot apply undefined state "${state}". Double check the model factory`) @@ -121,11 +122,13 @@ export class FactoryModel implements FactoryModelContr * Returns the pre-registered relationship factory function, along with * the original model relation. */ - public getRelation(relation: string): FactoryRelationContract { - const relationship = this.relations[relation] + getRelation(relation: keyof this['relations']): FactoryRelationContract { + const relationship = this.relations[relation as string] if (!relationship) { throw new Error( - `Cannot reference "${relation}" relationship. Make sure to setup the relationship within the factory` + `Cannot reference "${String( + relation + )}" relationship. Make sure to setup the relationship within the factory` ) } @@ -136,18 +139,21 @@ export class FactoryModel implements FactoryModelContr * Define custom state for the factory. When executing the factory, * you can apply the pre-defined states */ - public state(state: string, callback: StateCallback): any { + state( + state: K, + callback: StateCallback + ): this & { states: { [P in K]: StateCallback } } { this.states[state] = callback - return this + return this as this & { states: { [P in K]: StateCallback } } } /** * Define a relationship on another factory */ - public relation>>( - relation: Extract, - callback: any - ): any { + relation>, Relation>( + relation: K, + callback: Relation + ): this & { relations: { [P in K]: Relation } } { const modelRelation = this.model.$getRelation(relation) as RelationshipsContract /** @@ -156,7 +162,7 @@ export class FactoryModel implements FactoryModelContr if (!modelRelation) { throw new Error( [ - `Cannot define "${relation}" relationship.`, + `Cannot define "${String(relation)}" relationship.`, `The relationship must exist on the "${this.model.name}" model first`, ].join(' ') ) @@ -164,33 +170,33 @@ export class FactoryModel implements FactoryModelContr switch (modelRelation.type) { case 'belongsTo': - this.relations[relation] = new BelongsTo(modelRelation, callback) + this.relations[relation as string] = new BelongsTo(modelRelation, callback as any) break case 'hasOne': - this.relations[relation] = new HasOne(modelRelation, callback) + this.relations[relation as string] = new HasOne(modelRelation, callback as any) break case 'hasMany': - this.relations[relation] = new HasMany(modelRelation, callback) + this.relations[relation as string] = new HasMany(modelRelation, callback as any) break case 'manyToMany': - this.relations[relation] = new ManyToMany(modelRelation, callback) + this.relations[relation as string] = new ManyToMany(modelRelation, callback as any) break case 'hasManyThrough': throw new Error( [ - `Cannot define "${relation}" relationship.`, + `Cannot define "${String(relation)}" relationship.`, '"hasManyThrough" relationship does not have any persistance API', ].join(' ') ) } - return this + return this as this & { relations: { [P in K]: Relation } } } /** * Define a custom `newUp` method */ - public newUp(callback: NewUpCallback): this { + newUp(callback: NewUpCallback): this { this.newUpModelInstance = callback return this } @@ -198,7 +204,7 @@ export class FactoryModel implements FactoryModelContr /** * Define a custom `merge` method */ - public merge(callback: MergeCallback): this { + merge(callback: MergeCallback): this { this.mergeAttributes = callback return this } @@ -207,29 +213,36 @@ export class FactoryModel implements FactoryModelContr * Build factory model and return factory builder. The builder is then * used to make/create model instances */ - public build() { + build() { /** * Return a build object, which proxies all of the factory builder * method and invokes them with a fresh instance. */ - const builder = { - factory: this, - query(options?: ModelAdapterOptions, viaRelation?: FactoryRelationContract) { - return new FactoryBuilder(this.factory, options, viaRelation) + const builder: FactoryBuilderQueryContract> = { + factory: this as FactoryModelContract, + query( + options?: ModelAdapterOptions, + viaRelation?: FactoryRelationContract + ): FactoryBuilderContract> { + return new FactoryBuilder( + this.factory as unknown as FactoryModel, + options, + viaRelation + ) as unknown as FactoryBuilderContract> }, tap(callback) { return this.query().tap(callback) }, - client(...args: any[]) { + client(...args) { return this.query().client(...args) }, - connection(...args: any[]) { + connection(...args) { return this.query().connection(...args) }, - apply(...args: any[]) { + apply(...args) { return this.query().apply(...args) }, - with(relation, ...args: any[]) { + with(relation, ...args) { return this.query().with(relation, ...args) }, merge(attributes) { @@ -241,23 +254,26 @@ export class FactoryModel implements FactoryModelContr useCtx(ctx) { return this.query().useCtx(ctx) }, - make(callback) { - return this.query().make(callback) + make() { + return this.query().make() + }, + makeStubbed() { + return this.query().makeStubbed() }, - makeStubbed(callback) { - return this.query().makeStubbed(callback) + create() { + return this.query().create() }, - create(callback) { - return this.query().create(callback) + makeMany(count) { + return this.query().makeMany(count) }, - makeMany(count, callback) { - return this.query().makeMany(count, callback) + makeStubbedMany(count) { + return this.query().makeStubbedMany(count) }, - makeStubbedMany(count, callback) { - return this.query().makeStubbedMany(count, callback) + createMany(count) { + return this.query().createMany(count) }, - createMany(count, callback) { - return this.query().createMany(count, callback) + pivotAttributes(attributes) { + return this.query().pivotAttributes(attributes) }, } diff --git a/src/Factory/index.ts b/src/factory/index.ts similarity index 58% rename from src/Factory/index.ts rename to src/factory/index.ts index 7d0cd4ca..fad645a8 100644 --- a/src/Factory/index.ts +++ b/src/factory/index.ts @@ -7,35 +7,42 @@ * file that was distributed with this source code. */ -import { LucidModel, LucidRow } from '@ioc:Adonis/Lucid/Orm' -import { FactoryManagerContract, DefineCallback, StubIdCallback } from '@ioc:Adonis/Lucid/Factory' -import { FactoryModel } from './FactoryModel' +import { LucidModel, LucidRow } from '../../adonis-typings/model.js' +import { + DefineCallback, + FactoryModelContract, + StubIdCallback, +} from '../../adonis-typings/factory.js' +import { FactoryModel } from './factory_model.js' /** * Factory manager exposes the API to register factories. */ -export class FactoryManager implements FactoryManagerContract { +export class FactoryManager { private stubCounter = 1 private stubIdCallback: StubIdCallback = (counter) => counter /** * Returns the next id */ - public getNextId(model: LucidRow) { + getNextId(model: LucidRow) { return this.stubIdCallback(this.stubCounter++, model) } /** * Define a factory model */ - public define(model: Model, callback: DefineCallback) { + define( + model: Model, + callback: DefineCallback + ): FactoryModelContract { return new FactoryModel(model, callback, this) } /** * Define custom callback to generate stub ids */ - public stubId(callback: StubIdCallback) { + stubId(callback: StubIdCallback): void { this.stubIdCallback = callback } } diff --git a/src/Factory/Relations/Base.ts b/src/factory/relations/base.ts similarity index 71% rename from src/Factory/Relations/Base.ts rename to src/factory/relations/base.ts index 562c75bd..da4760c6 100644 --- a/src/Factory/Relations/Base.ts +++ b/src/factory/relations/base.ts @@ -7,26 +7,26 @@ * file that was distributed with this source code. */ -import { LucidModel, LucidRow } from '@ioc:Adonis/Lucid/Orm' +import { LucidModel, LucidRow } from '../../../adonis-typings/model.js' import { RelationCallback, FactoryModelContract, FactoryContextContract, FactoryBuilderQueryContract, FactoryRelationContract, -} from '@ioc:Adonis/Lucid/Factory' +} from '../../../adonis-typings/factory.js' /** * Base relation to be extended by other factory relations */ export abstract class BaseRelation { - protected ctx: FactoryContextContract + protected ctx?: FactoryContextContract private attributes: any = {} - public parent: LucidRow + declare parent: LucidRow constructor( - private factory: () => FactoryBuilderQueryContract> + private factory: () => FactoryBuilderQueryContract> ) {} /** @@ -43,14 +43,18 @@ export abstract class BaseRelation { callback(builder) } - builder.useCtx(this.ctx).mergeRecursive(this.attributes) + if (this.ctx) { + builder.useCtx(this.ctx) + } + + builder.mergeRecursive(this.attributes) return builder } /** * Merge attributes with the relationship and its children */ - public merge(attributes: any) { + merge(attributes: any) { this.attributes = attributes return this } @@ -59,7 +63,7 @@ export abstract class BaseRelation { * Use custom ctx. This must always be called by the factory, otherwise * `make` and `create` calls will fail. */ - public useCtx(ctx: FactoryContextContract): this { + useCtx(ctx: FactoryContextContract): this { this.ctx = ctx return this } diff --git a/src/Factory/Relations/BelongsTo.ts b/src/factory/relations/belongs_to.ts similarity index 72% rename from src/Factory/Relations/BelongsTo.ts rename to src/factory/relations/belongs_to.ts index c620a205..ffdfcd49 100644 --- a/src/Factory/Relations/BelongsTo.ts +++ b/src/factory/relations/belongs_to.ts @@ -7,15 +7,16 @@ * file that was distributed with this source code. */ -import { LucidModel, LucidRow, BelongsToRelationContract } from '@ioc:Adonis/Lucid/Orm' +import { LucidModel, LucidRow } from '../../../adonis-typings/model.js' +import { BelongsToRelationContract } from '../../../adonis-typings/relations.js' import { RelationCallback, FactoryModelContract, FactoryRelationContract, FactoryBuilderQueryContract, -} from '@ioc:Adonis/Lucid/Factory' +} from '../../../adonis-typings/factory.js' -import { BaseRelation } from './Base' +import { BaseRelation } from './base.js' /** * A belongs to factory relation @@ -23,7 +24,7 @@ import { BaseRelation } from './Base' export class BelongsTo extends BaseRelation implements FactoryRelationContract { constructor( public relation: BelongsToRelationContract, - factory: () => FactoryBuilderQueryContract> + factory: () => FactoryBuilderQueryContract> ) { super(factory) this.relation.boot() @@ -32,7 +33,7 @@ export class BelongsTo extends BaseRelation implements FactoryRelationContract { /** * Make relationship and set it on the parent model instance */ - public async make(parent: LucidRow, callback?: RelationCallback) { + async make(parent: LucidRow, callback?: RelationCallback) { const factory = this.compile(this, parent, callback) const related = await factory.makeStubbed() @@ -43,7 +44,7 @@ export class BelongsTo extends BaseRelation implements FactoryRelationContract { /** * Persist relationship and set it on the parent model instance */ - public async create(parent: LucidRow, callback?: RelationCallback) { + async create(parent: LucidRow, callback?: RelationCallback) { const factory = this.compile(this, parent, callback) const related = await factory.create() diff --git a/src/Factory/Relations/HasMany.ts b/src/factory/relations/has_many.ts similarity index 75% rename from src/Factory/Relations/HasMany.ts rename to src/factory/relations/has_many.ts index 34badece..e411e2e4 100644 --- a/src/Factory/Relations/HasMany.ts +++ b/src/factory/relations/has_many.ts @@ -7,15 +7,16 @@ * file that was distributed with this source code. */ -import { LucidModel, LucidRow, HasManyRelationContract } from '@ioc:Adonis/Lucid/Orm' +import { LucidModel, LucidRow } from '../../../adonis-typings/model.js' +import { HasManyRelationContract } from '../../../adonis-typings/relations.js' import { RelationCallback, FactoryModelContract, FactoryRelationContract, FactoryBuilderQueryContract, -} from '@ioc:Adonis/Lucid/Factory' +} from '../../../adonis-typings/factory.js' -import { BaseRelation } from './Base' +import { BaseRelation } from './base.js' /** * Has many to factory relation @@ -23,7 +24,7 @@ import { BaseRelation } from './Base' export class HasMany extends BaseRelation implements FactoryRelationContract { constructor( public relation: HasManyRelationContract, - factory: () => FactoryBuilderQueryContract> + factory: () => FactoryBuilderQueryContract> ) { super(factory) this.relation.boot() @@ -32,7 +33,7 @@ export class HasMany extends BaseRelation implements FactoryRelationContract { /** * Make relationship and set it on the parent model instance */ - public async make(parent: LucidRow, callback?: RelationCallback, count?: number) { + async make(parent: LucidRow, callback?: RelationCallback, count?: number) { const factory = this.compile(this, parent, callback) const customAttributes = {} @@ -50,7 +51,7 @@ export class HasMany extends BaseRelation implements FactoryRelationContract { /** * Persist relationship and set it on the parent model instance */ - public async create(parent: LucidRow, callback?: RelationCallback, count?: number) { + async create(parent: LucidRow, callback?: RelationCallback, count?: number) { const factory = this.compile(this, parent, callback) const customAttributes = {} diff --git a/src/Factory/Relations/HasOne.ts b/src/factory/relations/has_one.ts similarity index 75% rename from src/Factory/Relations/HasOne.ts rename to src/factory/relations/has_one.ts index 0271b8a5..7b057d5a 100644 --- a/src/Factory/Relations/HasOne.ts +++ b/src/factory/relations/has_one.ts @@ -7,15 +7,16 @@ * file that was distributed with this source code. */ -import { LucidModel, LucidRow, HasOneRelationContract } from '@ioc:Adonis/Lucid/Orm' +import { LucidModel, LucidRow } from '../../../adonis-typings/model.js' +import { HasOneRelationContract } from '../../../adonis-typings/relations.js' import { RelationCallback, FactoryModelContract, FactoryRelationContract, FactoryBuilderQueryContract, -} from '@ioc:Adonis/Lucid/Factory' +} from '../../../adonis-typings/factory.js' -import { BaseRelation } from './Base' +import { BaseRelation } from './base.js' /** * Has one to factory relation @@ -23,7 +24,7 @@ import { BaseRelation } from './Base' export class HasOne extends BaseRelation implements FactoryRelationContract { constructor( public relation: HasOneRelationContract, - factory: () => FactoryBuilderQueryContract> + factory: () => FactoryBuilderQueryContract> ) { super(factory) this.relation.boot() @@ -32,7 +33,7 @@ export class HasOne extends BaseRelation implements FactoryRelationContract { /** * Make relationship and set it on the parent model instance */ - public async make(parent: LucidRow, callback?: RelationCallback) { + async make(parent: LucidRow, callback?: RelationCallback) { const factory = this.compile(this, parent, callback) const customAttributes = {} this.relation.hydrateForPersistance(parent, customAttributes) @@ -44,7 +45,7 @@ export class HasOne extends BaseRelation implements FactoryRelationContract { /** * Persist relationship and set it on the parent model instance */ - public async create(parent: LucidRow, callback?: RelationCallback) { + async create(parent: LucidRow, callback?: RelationCallback) { const factory = this.compile(this, parent, callback) const customAttributes = {} diff --git a/src/Factory/Relations/ManyToMany.ts b/src/factory/relations/many_to_many.ts similarity index 74% rename from src/Factory/Relations/ManyToMany.ts rename to src/factory/relations/many_to_many.ts index 6cd1d2a1..a72e0354 100644 --- a/src/Factory/Relations/ManyToMany.ts +++ b/src/factory/relations/many_to_many.ts @@ -7,20 +7,17 @@ * file that was distributed with this source code. */ -import { - ManyToManyRelationContract, - LucidModel, - LucidRow, - ModelObject, -} from '@ioc:Adonis/Lucid/Orm' +import { LucidModel, LucidRow, ModelObject } from '../../../adonis-typings/model.js' +import { ManyToManyRelationContract } from '../../../adonis-typings/relations.js' + import { RelationCallback, FactoryModelContract, FactoryRelationContract, FactoryBuilderQueryContract, -} from '@ioc:Adonis/Lucid/Factory' +} from '../../../adonis-typings/factory.js' -import { BaseRelation } from './Base' +import { BaseRelation } from './base.js' /** * Many to many factory relation @@ -30,7 +27,7 @@ export class ManyToMany extends BaseRelation implements FactoryRelationContract constructor( public relation: ManyToManyRelationContract, - factory: () => FactoryBuilderQueryContract> + factory: () => FactoryBuilderQueryContract> ) { super(factory) this.relation.boot() @@ -39,7 +36,7 @@ export class ManyToMany extends BaseRelation implements FactoryRelationContract /** * Make relationship and set it on the parent model instance */ - public async make(parent: LucidRow, callback?: RelationCallback, count?: number) { + async make(parent: LucidRow, callback?: RelationCallback, count?: number) { const builder = this.compile(this, parent, callback) const instances = await builder.makeStubbedMany(count || 1) parent.$setRelated(this.relation.relationName, instances) @@ -48,7 +45,7 @@ export class ManyToMany extends BaseRelation implements FactoryRelationContract /** * Define pivot attributes */ - public pivotAttributes(attributes: ModelObject | ModelObject[]) { + pivotAttributes(attributes: ModelObject | ModelObject[]) { this.attributesForPivotTable = attributes return this } @@ -56,7 +53,7 @@ export class ManyToMany extends BaseRelation implements FactoryRelationContract /** * Persist relationship and set it on the parent model instance */ - public async create(parent: LucidRow, callback?: RelationCallback, count?: number) { + async create(parent: LucidRow, callback?: RelationCallback, count?: number) { const builder = this.compile(this, parent, callback) const instances = await builder.createMany(count || 1) @@ -79,7 +76,7 @@ export class ManyToMany extends BaseRelation implements FactoryRelationContract /** * Make pivot insert query */ - await this.relation.client(parent, this.ctx.$trx!).attach(relatedForeignKeyValues) + await this.relation.client(parent, this.ctx?.$trx!).attach(relatedForeignKeyValues) /** * Setup in-memory relationship diff --git a/test-helpers/index.ts b/test-helpers/index.ts index 26c8f2f5..7e492e7d 100644 --- a/test-helpers/index.ts +++ b/test-helpers/index.ts @@ -439,19 +439,6 @@ export function getBaseModel(adapter: AdapterContract, application: Application< return BaseModel } -/** - * Returns the factory model - */ -export function getFactoryModel() { - return FactoryModel as { - new ( - model: Model, - callback: DefineCallback, - manager: FactoryManagerContract - ): FactoryModelContract - } -} - /** * Fake adapter implementation */ diff --git a/test/factory/belongs-to.spec.ts b/test/factory/belongs_to.spec.ts similarity index 59% rename from test/factory/belongs-to.spec.ts rename to test/factory/belongs_to.spec.ts index be5b52b3..9456ea05 100644 --- a/test/factory/belongs-to.spec.ts +++ b/test/factory/belongs_to.spec.ts @@ -7,97 +7,84 @@ * file that was distributed with this source code. */ -/// - import { test } from '@japa/runner' -import type { BelongsTo } from '@ioc:Adonis/Lucid/Orm' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' +import type { BelongsTo } from '../../adonis-typings/relations.js' -import { FactoryManager } from '../../src/Factory/index' -import { column, belongsTo } from '../../src/Orm/Decorators' +import { FactoryManager } from '../../src/factory/index.js' +import { column, belongsTo } from '../../src/orm/decorators/index.js' import { - fs, setup, getDb, cleanup, ormAdapter, resetTables, getBaseModel, - setupApplication, - getFactoryModel, -} from '../../test-helpers' - -let db: ReturnType -let app: ApplicationContract -let BaseModel: ReturnType -const FactoryModel = getFactoryModel() +} from '../../test-helpers/index.js' +import { AppFactory } from '@adonisjs/core/factories/app' + const factoryManager = new FactoryManager() test.group('Factory | BelongTo | make', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('make stubbed model with relationship', async ({ assert }) => { + test('make stubbed model with relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 } - const profileFactory = new FactoryModel( - Profile, - () => { + const profileFactory = factoryManager + .define(Profile, () => { return { displayName: 'virk', } - }, - factoryManager - ) + }) .relation('user', () => factory) .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ).build() + }) + .build() const profile = await profileFactory.with('user').makeStubbed() assert.exists(profile.id) @@ -109,54 +96,55 @@ test.group('Factory | BelongTo | make', (group) => { assert.equal(profile.user.id, profile.userId) }) - test('pass custom attributes to the relationship', async ({ assert }) => { + test('pass custom attributes to the relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 } - const profileFactory = new FactoryModel( - Profile, - () => { + const profileFactory = factoryManager + .define(Profile, () => { return { displayName: 'virk', } - }, - factoryManager - ) + }) .relation('user', () => factory) .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { points: 0, } - }, - factoryManager - ).build() + }) + .build() const profile = await profileFactory .with('user', 1, (related) => related.merge({ points: 10 })) @@ -172,55 +160,55 @@ test.group('Factory | BelongTo | make', (group) => { assert.equal(profile.user.points, 10) }) - test('invoke make hook on the related factory during make stubbed', async ({ assert }) => { + test('invoke make hook on the related factory during make stubbed', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 } User.boot() - const profileFactory = new FactoryModel( - Profile, - () => { + const profileFactory = factoryManager + .define(Profile, () => { return { displayName: 'virk', } - }, - factoryManager - ) + }) .relation('user', () => factory) .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { points: 0, } - }, - factoryManager - ) + }) .after('make', (_, user) => { user.id = 100 }) @@ -244,65 +232,61 @@ test.group('Factory | BelongTo | make', (group) => { test.group('Factory | BelongTo | create', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('create model with relationship', async ({ assert }) => { + test('create model with relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 } - const profileFactory = new FactoryModel( - Profile, - () => { + const profileFactory = factoryManager + .define(Profile, () => { return { displayName: 'virk', } - }, - factoryManager - ) + }) .relation('user', () => factory) .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ).build() + }) + .build() const profile = await profileFactory.with('user').create() @@ -319,51 +303,52 @@ test.group('Factory | BelongTo | create', (group) => { assert.equal(profiles[0].user_id, users[0].id) }) - test('pass custom attributes to the relationship', async ({ assert }) => { + test('pass custom attributes to the relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 } - const profileFactory = new FactoryModel( - Profile, - () => { + const profileFactory = factoryManager + .define(Profile, () => { return { displayName: 'virk', } - }, - factoryManager - ) + }) .relation('user', () => factory) .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { points: 0, } - }, - factoryManager - ).build() + }) + .build() const profile = await profileFactory .with('user', 1, (related) => related.merge({ points: 10 })) @@ -376,51 +361,52 @@ test.group('Factory | BelongTo | create', (group) => { assert.equal(profile.user.points, 10) }) - test('create model with custom foreign key', async ({ assert }) => { + test('create model with custom foreign key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ columnName: 'user_id' }) - public authorId: number + declare authorId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User, { foreignKey: 'authorId' }) - public user: BelongsTo + declare user: BelongsTo } Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 } - const profileFactory = new FactoryModel( - Profile, - () => { + const profileFactory = factoryManager + .define(Profile, () => { return { displayName: 'virk', } - }, - factoryManager - ) + }) .relation('user', () => factory) .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { points: 0, } - }, - factoryManager - ).build() + }) + .build() const profile = await profileFactory .with('user', 1, (related) => related.merge({ points: 10 })) @@ -433,41 +419,44 @@ test.group('Factory | BelongTo | create', (group) => { assert.equal(profile.user.points, 10) }) - test('rollback changes on error', async ({ assert }) => { + test('rollback changes on error', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(3) class Profile extends BaseModel { @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string @belongsTo(() => User) - public user: BelongsTo + declare user: BelongsTo } Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 } - const profileFactory = new FactoryModel( - Profile, - () => { + const profileFactory = factoryManager + .define(Profile, () => { return { displayName: 'virk', } - }, - factoryManager - ) + }) .relation('user', () => factory) .build() @@ -480,15 +469,13 @@ test.group('Factory | BelongTo | create', (group) => { */ await db.table('users').insert({ username: 'virk' }) - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { username: 'virk', } - }, - factoryManager - ).build() + }) + .build() try { await profileFactory.with('user').create() diff --git a/test/factory/factory-model.spec.ts b/test/factory/factory-model.spec.ts deleted file mode 100644 index 7d505383..00000000 --- a/test/factory/factory-model.spec.ts +++ /dev/null @@ -1,270 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -/// - -import { test } from '@japa/runner' - -import type { HasOne } from '@ioc:Adonis/Lucid/Orm' -import { column, hasOne } from '../../src/Orm/Decorators' -import { FactoryManager } from '../../src/Factory/index' -import { FactoryModel } from '../../src/Factory/FactoryModel' -import { HasOne as FactoryHasOne } from '../../src/Factory/Relations/HasOne' - -import { - fs, - setup, - getDb, - cleanup, - ormAdapter, - resetTables, - getBaseModel, - setupApplication, -} from '../../test-helpers' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -let db: ReturnType -let app: ApplicationContract -let BaseModel: ReturnType -const factoryManager = new FactoryManager() - -test.group('Factory | Factory Model', (group) => { - group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) - await setup() - }) - - group.teardown(async () => { - await db.manager.closeAll() - await cleanup() - await fs.cleanup() - }) - - group.each.teardown(async () => { - await resetTables() - }) - - test('define model factory', async ({ assert }) => { - class User extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @column() - public username: string - } - - const factory = new FactoryModel(User, () => new User(), factoryManager) - assert.instanceOf(factory, FactoryModel) - }) - - test('define factory state', async ({ assert }) => { - class User extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @column() - public username: string - } - - function stateFn() {} - const factory = new FactoryModel(User, () => new User(), factoryManager).state( - 'active', - stateFn - ) - assert.deepEqual(factory.states, { active: stateFn }) - }) - - test('define factory relation', async ({ assert }) => { - class Profile extends BaseModel { - @column() - public userId: number - } - Profile.boot() - - class User extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @column() - public username: string - - @hasOne(() => Profile) - public profile: HasOne - } - User.boot() - - function relatedFn() {} - const factory = new FactoryModel(User, () => new User(), factoryManager).relation( - 'profile', - relatedFn - ) - assert.property(factory.relations, 'profile') - assert.instanceOf(factory.relations.profile, FactoryHasOne) - }) - - test('get pre-registered state', async ({ assert }) => { - class User extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @column() - public username: string - } - - function stateFn() {} - const factory = new FactoryModel(User, () => new User(), factoryManager).state( - 'active', - stateFn - ) - assert.deepEqual(factory.getState('active'), stateFn) - }) - - test('raise exception when state is not registered', async ({ assert }) => { - class User extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @column() - public username: string - } - - const factory = new FactoryModel(User, () => new User(), factoryManager) - assert.throws( - () => factory.getState('active'), - 'Cannot apply undefined state "active". Double check the model factory' - ) - }) - - test('get pre-registered relationship', async ({ assert }) => { - class Profile extends BaseModel { - @column() - public userId: number - } - Profile.boot() - - class User extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @column() - public username: string - - @hasOne(() => Profile) - public profile: HasOne - } - User.boot() - - const profileFactory = new FactoryModel(Profile, () => new Profile(), factoryManager).build() - function relatedFn() { - return profileFactory - } - - const factory = new FactoryModel(User, () => new User(), factoryManager).relation( - 'profile', - relatedFn - ) - assert.instanceOf(factory.getRelation('profile'), FactoryHasOne) - assert.deepEqual(factory.getRelation('profile').relation, User.$getRelation('profile')!) - }) - - test('raise exception when relation is not defined', async ({ assert }) => { - class Profile extends BaseModel {} - Profile.boot() - - class User extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @column() - public username: string - - @hasOne(() => Profile) - public profile: HasOne - } - - const factory = new FactoryModel(User, () => new User(), factoryManager) - assert.throws( - () => factory.getRelation('profile'), - 'Cannot reference "profile" relationship. Make sure to setup the relationship within the factory' - ) - }) - - test('do not allow registering relationships not defined on the model', async ({ assert }) => { - class User extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @column() - public username: string - } - - const factory = () => - new FactoryModel(User, () => new User(), factoryManager).relation('profile' as any, () => {}) - assert.throws( - factory, - 'Cannot define "profile" relationship. The relationship must exist on the "User" model first' - ) - }) - - test('build factory', async ({ assert }) => { - class Profile extends BaseModel {} - Profile.boot() - - class User extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @column() - public username: string - - @hasOne(() => Profile) - public profile: HasOne - } - - const factory = new FactoryModel( - User, - () => { - return {} - }, - factoryManager - ).build() - - const user = await factory.make() - assert.instanceOf(user, User) - }) - - test('return model instance from the factory callback', async ({ assert }) => { - class Profile extends BaseModel {} - Profile.boot() - - class User extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @column() - public username: string - - @hasOne(() => Profile) - public profile: HasOne - } - - const factory = new FactoryModel( - User, - () => { - return new User() - }, - factoryManager - ).build() - - const user = await factory.make() - assert.instanceOf(user, User) - }) -}) diff --git a/test/factory/factory-builder.spec.ts b/test/factory/factory_builder.spec.ts similarity index 56% rename from test/factory/factory-builder.spec.ts rename to test/factory/factory_builder.spec.ts index 5cd24110..c668dcd5 100644 --- a/test/factory/factory-builder.spec.ts +++ b/test/factory/factory_builder.spec.ts @@ -7,71 +7,61 @@ * file that was distributed with this source code. */ -/// - import { test } from '@japa/runner' -import { randomUUID } from 'crypto' -import { column } from '../../src/Orm/Decorators' -import { FactoryManager } from '../../src/Factory/index' -import { FactoryContext } from '../../src/Factory/FactoryContext' -import { FactoryBuilder } from '../../src/Factory/FactoryBuilder' +import { randomUUID } from 'node:crypto' + +import { column } from '../../src/orm/decorators/index.js' +import { FactoryManager } from '../../src/factory/index.js' +import { FactoryContext } from '../../src/factory/factory_context.js' +import { FactoryBuilder } from '../../src/factory/factory_builder.js' import { - fs, setup, getDb, cleanup, ormAdapter, resetTables, getBaseModel, - getFactoryModel, - setupApplication, -} from '../../test-helpers' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -let db: ReturnType -let app: ApplicationContract -let BaseModel: ReturnType -const FactoryModel = getFactoryModel() +} from '../../test-helpers/index.js' +import { AppFactory } from '@adonisjs/core/factories/app' + const factoryManager = new FactoryManager() test.group('Factory | Factory Builder | make', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('apply factory model state', async ({ assert }) => { + test('apply factory model state', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .state('withPoints', (user) => (user.points = 10)) .build() @@ -81,25 +71,28 @@ test.group('Factory | Factory Builder | make', (group) => { assert.isFalse(user.$isPersisted) }) - test('applying a state twice must be a noop', async ({ assert }) => { + test('applying a state twice must be a noop', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .state('withPoints', (user) => { user.points += 10 }) @@ -112,25 +105,28 @@ test.group('Factory | Factory Builder | make', (group) => { assert.isFalse(user.$isPersisted) }) - test('pass instance of builder to the state callback', async ({ assert }) => { + test('pass instance of builder to the state callback', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .state('withPoints', (user, __, builder) => { assert.instanceOf(builder, FactoryBuilder) user.merge({ points: 10 }) @@ -143,27 +139,31 @@ test.group('Factory | Factory Builder | make', (group) => { assert.isFalse(user.$isPersisted) }) - test('merge custom attributes', async ({ assert }) => { + test('merge custom attributes', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { username: 'virk', } - }, - factoryManager - ).build() + }) + .build() const user = await factory.merge({ username: 'nikk' }).makeStubbed() assert.equal(user.username, 'nikk') @@ -171,27 +171,30 @@ test.group('Factory | Factory Builder | make', (group) => { assert.isFalse(user.$isPersisted) }) - test('define custom merge function', async ({ assert }) => { + test('define custom merge function', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { username: 'virk', } - }, - factoryManager - ) + }) .merge(() => {}) .build() @@ -201,27 +204,30 @@ test.group('Factory | Factory Builder | make', (group) => { assert.isFalse(user.$isPersisted) }) - test('pass builder to custom merge function', async ({ assert }) => { + test('pass builder to custom merge function', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { username: 'virk', } - }, - factoryManager - ) + }) .merge((_, __, ___, builder) => { assert.instanceOf(builder, FactoryBuilder) }) @@ -233,27 +239,30 @@ test.group('Factory | Factory Builder | make', (group) => { assert.isFalse(user.$isPersisted) }) - test('define custom newUp function', async ({ assert }) => { + test('define custom newUp function', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { username: 'virk', } - }, - factoryManager - ) + }) .newUp((attributes) => { const user = new User() user.fill(attributes) @@ -270,27 +279,30 @@ test.group('Factory | Factory Builder | make', (group) => { assert.isFalse(user.$isPersisted) }) - test('pass model to custom newUp function', async ({ assert }) => { + test('pass model to custom newUp function', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { username: 'virk', } - }, - factoryManager - ) + }) .newUp((attributes) => { const user = new User() user.fill(attributes) @@ -307,27 +319,30 @@ test.group('Factory | Factory Builder | make', (group) => { assert.isFalse(user.$isPersisted) }) - test('pass factory builder to custom newUp function', async ({ assert }) => { + test('pass factory builder to custom newUp function', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { username: 'virk', } - }, - factoryManager - ) + }) .newUp((attributes, _, __, builder) => { assert.instanceOf(builder, FactoryBuilder) @@ -346,27 +361,31 @@ test.group('Factory | Factory Builder | make', (group) => { assert.isFalse(user.$isPersisted) }) - test('use 0 index elements when attributes are defined as an array', async ({ assert }) => { + test('use 0 index elements when attributes are defined as an array', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { username: 'virk', } - }, - factoryManager - ).build() + }) + .build() const user = await factory.merge([{ username: 'nikk' }, { username: 'romain' }]).makeStubbed() assert.equal(user.username, 'nikk') @@ -374,29 +393,32 @@ test.group('Factory | Factory Builder | make', (group) => { assert.isFalse(user.$isPersisted) }) - test('invoke after make hook', async ({ assert }) => { + test('invoke after make hook', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(6) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { username: 'virk', } - }, - factoryManager - ) + }) .after('make', (_, user, ctx) => { assert.instanceOf(_, FactoryBuilder) assert.instanceOf(user, User) @@ -410,29 +432,32 @@ test.group('Factory | Factory Builder | make', (group) => { assert.isFalse(user.$isPersisted) }) - test('invoke after makeStubbed hook', async ({ assert }) => { + test('invoke after makeStubbed hook', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(6) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { username: 'virk', } - }, - factoryManager - ) + }) .after('makeStubbed', (_, user, ctx) => { assert.instanceOf(_, FactoryBuilder) assert.instanceOf(user, User) @@ -446,29 +471,32 @@ test.group('Factory | Factory Builder | make', (group) => { assert.isFalse(user.$isPersisted) }) - test('define custom id inside make hook', async ({ assert }) => { + test('define custom id inside make hook', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(3) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { username: 'virk', } - }, - factoryManager - ) + }) .after('make', (_, user, ctx) => { if (ctx.isStubbed) { user.id = 100 @@ -482,27 +510,31 @@ test.group('Factory | Factory Builder | make', (group) => { assert.isFalse(user.$isPersisted) }) - test('tap into model persistence before makeStubbed', async ({ assert }) => { + test('tap into model persistence before makeStubbed', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { username: 'virk', } - }, - factoryManager - ).build() + }) + .build() const user = await factory .tap(($user, ctx) => { @@ -517,27 +549,31 @@ test.group('Factory | Factory Builder | make', (group) => { assert.isFalse(user.$isPersisted) }) - test('tap into model persistence before make', async ({ assert }) => { + test('tap into model persistence before make', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { username: 'virk', } - }, - factoryManager - ).build() + }) + .build() const user = await factory .tap(($user) => { @@ -549,27 +585,30 @@ test.group('Factory | Factory Builder | make', (group) => { assert.isFalse(user.$isPersisted) }) - test('bubble erros when makeStubbed fails', async ({ assert }) => { + test('bubble erros when makeStubbed fails', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { username: 'virk', } - }, - factoryManager - ) + }) .state('foo', () => { throw new Error('boom') }) @@ -578,27 +617,30 @@ test.group('Factory | Factory Builder | make', (group) => { await assert.rejects(async () => await factory.apply('foo').makeStubbed(), 'boom') }) - test('bubble erros when make fails', async ({ assert }) => { + test('bubble erros when make fails', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { username: 'virk', } - }, - factoryManager - ) + }) .state('foo', () => { throw new Error('boom') }) @@ -610,41 +652,39 @@ test.group('Factory | Factory Builder | make', (group) => { test.group('Factory | Factory Builder | makeMany', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('apply factory model state', async ({ assert }) => { + test('apply factory model state', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .state('withPoints', (user) => (user.points = 10)) .build() @@ -659,25 +699,28 @@ test.group('Factory | Factory Builder | makeMany', (group) => { assert.isFalse(users[1].$isPersisted) }) - test('applying a state twice must be a noop', async ({ assert }) => { + test('applying a state twice must be a noop', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .state('withPoints', (user) => (user.points += 10)) .build() @@ -693,27 +736,31 @@ test.group('Factory | Factory Builder | makeMany', (group) => { assert.isFalse(users[1].$isPersisted) }) - test('define custom attributes accepted by the newUp method', async ({ assert }) => { + test('define custom attributes accepted by the newUp method', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { username: 'virk', } - }, - factoryManager - ).build() + }) + .build() const users = await factory.merge({ username: 'nikk' }).makeStubbedMany(2) assert.lengthOf(users, 2) @@ -727,27 +774,31 @@ test.group('Factory | Factory Builder | makeMany', (group) => { assert.isFalse(users[1].$isPersisted) }) - test('define index specific attributes for makeMany', async ({ assert }) => { + test('define index specific attributes for makeMany', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { username: 'virk', } - }, - factoryManager - ).build() + }) + .build() const users = await factory .merge([{ username: 'nikk' }, { username: 'romain' }]) @@ -763,27 +814,30 @@ test.group('Factory | Factory Builder | makeMany', (group) => { assert.isFalse(users[1].$isPersisted) }) - test('run makeStubbed hook for all the model instances', async ({ assert }) => { + test('run makeStubbed hook for all the model instances', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(15) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .after('makeStubbed', (_, user, ctx) => { assert.instanceOf(_, FactoryBuilder) assert.instanceOf(user, User) @@ -804,27 +858,30 @@ test.group('Factory | Factory Builder | makeMany', (group) => { assert.isFalse(users[1].$isPersisted) }) - test('run make hook for all the model instances', async ({ assert }) => { + test('run make hook for all the model instances', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(15) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .after('make', (_, user, ctx) => { assert.instanceOf(_, FactoryBuilder) assert.instanceOf(user, User) @@ -845,27 +902,30 @@ test.group('Factory | Factory Builder | makeMany', (group) => { assert.isFalse(users[1].$isPersisted) }) - test('tap into model persistence before makeStubbedMany', async ({ assert }) => { + test('tap into model persistence before makeStubbedMany', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(15) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .state('withPoints', (user) => (user.points = 10)) .build() @@ -889,27 +949,30 @@ test.group('Factory | Factory Builder | makeMany', (group) => { assert.isFalse(users[1].$isPersisted) }) - test('tap into model persistence before makeMany', async ({ assert }) => { + test('tap into model persistence before makeMany', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(13) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .state('withPoints', (user) => (user.points = 10)) .build() @@ -931,25 +994,28 @@ test.group('Factory | Factory Builder | makeMany', (group) => { assert.isFalse(users[1].$isPersisted) }) - test('bubble errors when makeStubbedMany fails', async ({ assert }) => { + test('bubble errors when makeStubbedMany fails', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .merge(() => { throw new Error('boom') }) @@ -961,25 +1027,28 @@ test.group('Factory | Factory Builder | makeMany', (group) => { ) }) - test('bubble errors when makeMany fails', async ({ assert }) => { + test('bubble errors when makeMany fails', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .merge(() => { throw new Error('boom') }) @@ -991,41 +1060,39 @@ test.group('Factory | Factory Builder | makeMany', (group) => { test.group('Factory | Factory Builder | create', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('apply factory model state', async ({ assert }) => { + test('apply factory model state', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .state('withPoints', (user) => (user.points = 10)) .build() @@ -1034,25 +1101,28 @@ test.group('Factory | Factory Builder | create', (group) => { assert.isTrue(user.$isPersisted) }) - test('applying a state twice must be a noop', async ({ assert }) => { + test('applying a state twice must be a noop', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .state('withPoints', (user) => (user.points += 10)) .build() @@ -1061,81 +1131,92 @@ test.group('Factory | Factory Builder | create', (group) => { assert.isTrue(user.$isPersisted) }) - test('define custom attributes accepted by the newUp method', async ({ assert }) => { + test('define custom attributes accepted by the newUp method', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { username: 'virk', } - }, - factoryManager - ).build() + }) + .build() const user = await factory.merge({ username: 'nikk' }).create() assert.equal(user.username, 'nikk') assert.isTrue(user.$isPersisted) }) - test('use index 0 elements when attributes are defined as an array', async ({ assert }) => { + test('use index 0 elements when attributes are defined as an array', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { username: 'virk', } - }, - factoryManager - ).build() + }) + .build() const user = await factory.merge([{ username: 'nikk' }, { username: 'romain' }]).create() assert.equal(user.username, 'nikk') assert.isTrue(user.$isPersisted) }) - test('invoke before and after create hook', async ({ assert }) => { + test('invoke before and after create hook', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(4) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .before('create', (_, user) => { assert.isFalse(user.$isPersisted) }) @@ -1150,28 +1231,31 @@ test.group('Factory | Factory Builder | create', (group) => { assert.isTrue(user.$isPersisted) }) - test('invoke after make hook', async ({ assert }) => { + test('invoke after make hook', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(6) const stack: string[] = [] class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .before('create', (_, user) => { stack.push('beforeCreate') assert.isFalse(user.$isPersisted) @@ -1193,27 +1277,30 @@ test.group('Factory | Factory Builder | create', (group) => { assert.deepEqual(stack, ['afterMake', 'beforeCreate', 'afterCreate']) }) - test('define custom connection', async ({ assert }) => { + test('define custom connection', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(3) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .state('withPoints', (user) => (user.points = 10)) .build() @@ -1229,27 +1316,30 @@ test.group('Factory | Factory Builder | create', (group) => { assert.isTrue(user.$isPersisted) }) - test('define custom query client', async ({ assert }) => { + test('define custom query client', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(3) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .state('withPoints', (user) => (user.points = 10)) .build() @@ -1267,27 +1357,30 @@ test.group('Factory | Factory Builder | create', (group) => { assert.isTrue(user.$isPersisted) }) - test('invoke tap callback before persisting the model', async ({ assert }) => { + test('invoke tap callback before persisting the model', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(6) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .state('withPoints', (user) => (user.points = 10)) .build() @@ -1308,25 +1401,28 @@ test.group('Factory | Factory Builder | create', (group) => { assert.isTrue(user.$isPersisted) }) - test('bubble errors when create fails', async ({ assert }) => { + test('bubble errors when create fails', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .state('withPoints', () => { throw new Error('boo') }) @@ -1339,41 +1435,39 @@ test.group('Factory | Factory Builder | create', (group) => { test.group('Factory | Factory Builder | createMany', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('apply factory model state', async ({ assert }) => { + test('apply factory model state', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .state('withPoints', (user) => (user.points = 10)) .build() @@ -1385,25 +1479,28 @@ test.group('Factory | Factory Builder | createMany', (group) => { assert.isTrue(users[1].$isPersisted) }) - test('applying a state twice must be a noop', async ({ assert }) => { + test('applying a state twice must be a noop', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .state('withPoints', (user) => (user.points += 10)) .build() @@ -1415,28 +1512,32 @@ test.group('Factory | Factory Builder | createMany', (group) => { assert.isTrue(users[1].$isPersisted) }) - test('define custom attributes accepted by the newUp method', async ({ assert }) => { + test('define custom attributes accepted by the newUp method', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { username: randomUUID(), points: 0, } - }, - factoryManager - ).build() + }) + .build() const users = await factory.merge({ points: 10 }).createMany(2) assert.lengthOf(users, 2) @@ -1446,27 +1547,31 @@ test.group('Factory | Factory Builder | createMany', (group) => { assert.isTrue(users[1].$isPersisted) }) - test('define index specific attributes for makeMany', async ({ assert }) => { + test('define index specific attributes for makeMany', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { username: 'virk', } - }, - factoryManager - ).build() + }) + .build() const users = await factory.merge([{ username: 'nikk' }, { username: 'romain' }]).createMany(2) assert.lengthOf(users, 2) @@ -1476,29 +1581,33 @@ test.group('Factory | Factory Builder | createMany', (group) => { assert.isTrue(users[1].$isPersisted) }) - test('invoke tap before persisting all models', async ({ assert }) => { + test('invoke tap before persisting all models', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(11) class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { username: 'virk', } - }, - factoryManager - ).build() + }) + .build() const users = await factory .merge([{ username: 'nikk' }, { username: 'romain' }]) @@ -1516,29 +1625,32 @@ test.group('Factory | Factory Builder | createMany', (group) => { assert.isTrue(users[1].$isPersisted) }) - test('bubble errors when createMany fails', async ({ assert }) => { + test('bubble errors when createMany fails', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + let index = 0 class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number + declare points: number } - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return { username: 'virk', } - }, - factoryManager - ) + }) .merge(() => { index++ if (index === 2) { diff --git a/test/factory/factory_model.spec.ts b/test/factory/factory_model.spec.ts new file mode 100644 index 00000000..49558722 --- /dev/null +++ b/test/factory/factory_model.spec.ts @@ -0,0 +1,305 @@ +/* + * @adonisjs/lucid + * + * (c) Harminder Virk + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import { test } from '@japa/runner' + +import { FactoryManager } from '../../src/factory/index.js' +import type { HasOne } from '../../adonis-typings/relations.js' +import { column, hasOne } from '../../src/orm/decorators/index.js' +import { FactoryModel } from '../../src/factory/factory_model.js' +import { HasOne as FactoryHasOne } from '../../src/factory/relations/has_one.js' + +import { + setup, + getDb, + cleanup, + ormAdapter, + resetTables, + getBaseModel, +} from '../../test-helpers/index.js' +import { AppFactory } from '@adonisjs/core/factories/app' + +const factoryManager = new FactoryManager() + +test.group('Factory | Factory Model', (group) => { + group.setup(async () => { + await setup() + }) + + group.teardown(async () => { + await cleanup() + }) + + group.each.teardown(async () => { + await resetTables() + }) + + test('define model factory', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + + class User extends BaseModel { + @column({ isPrimary: true }) + declare id: number + + @column() + declare username: string + } + + const factory = factoryManager.define(User, () => new User()) + assert.instanceOf(factory, FactoryModel) + }) + + test('define factory state', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + + class User extends BaseModel { + @column({ isPrimary: true }) + declare id: number + + @column() + declare username: string + } + + function stateFn() {} + const factory = factoryManager.define(User, () => new User()).state('active', stateFn) + assert.deepEqual(factory.states, { active: stateFn }) + }) + + test('define factory relation', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + + class Profile extends BaseModel { + @column() + declare userId: number + } + Profile.boot() + + class User extends BaseModel { + @column({ isPrimary: true }) + declare id: number + + @column() + declare username: string + + @hasOne(() => Profile) + declare profile: HasOne + } + User.boot() + + function relatedFn() {} + const factory = factoryManager.define(User, () => new User()).relation('profile', relatedFn) + assert.property(factory.relations, 'profile') + assert.instanceOf(factory.relations.profile, FactoryHasOne) + }) + + test('get pre-registered state', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + + class User extends BaseModel { + @column({ isPrimary: true }) + declare id: number + + @column() + declare username: string + } + + function stateFn() {} + const factory = factoryManager.define(User, () => new User()).state('active', stateFn) + assert.deepEqual(factory.getState('active'), stateFn) + }) + + test('raise exception when state is not registered', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + + class User extends BaseModel { + @column({ isPrimary: true }) + declare id: number + + @column() + declare username: string + } + + const factory = factoryManager.define(User, () => new User()) + assert.throws( + () => factory.getState('active' as never), + 'Cannot apply undefined state "active". Double check the model factory' + ) + }) + + test('get pre-registered relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + + class Profile extends BaseModel { + @column() + declare userId: number + } + Profile.boot() + + class User extends BaseModel { + @column({ isPrimary: true }) + declare id: number + + @column() + declare username: string + + @hasOne(() => Profile) + declare profile: HasOne + } + User.boot() + + const profileFactory = factoryManager.define(Profile, () => new Profile()).build() + function relatedFn() { + return profileFactory + } + + const factory = factoryManager.define(User, () => new User()).relation('profile', relatedFn) + assert.instanceOf(factory.getRelation('profile'), FactoryHasOne) + assert.deepEqual(factory.getRelation('profile').relation, User.$getRelation('profile')!) + }) + + test('raise exception when relation is not defined', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + + class Profile extends BaseModel {} + Profile.boot() + + class User extends BaseModel { + @column({ isPrimary: true }) + declare id: number + + @column() + declare username: string + + @hasOne(() => Profile) + declare profile: HasOne + } + + const factory = factoryManager.define(User, () => new User()) + assert.throws( + () => factory.getRelation('profile' as never), + 'Cannot reference "profile" relationship. Make sure to setup the relationship within the factory' + ) + }) + + test('do not allow registering relationships not defined on the model', async ({ + fs, + assert, + }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + + class User extends BaseModel { + @column({ isPrimary: true }) + declare id: number + + @column() + declare username: string + } + + const factory = () => + factoryManager.define(User, () => new User()).relation('profile' as any, () => {}) + assert.throws( + factory, + 'Cannot define "profile" relationship. The relationship must exist on the "User" model first' + ) + }) + + test('build factory', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + + class Profile extends BaseModel {} + Profile.boot() + + class User extends BaseModel { + @column({ isPrimary: true }) + declare id: number + + @column() + declare username: string + + @hasOne(() => Profile) + declare profile: HasOne + } + + const factory = factoryManager + .define(User, () => { + return {} + }) + .build() + + const user = await factory.make() + assert.instanceOf(user, User) + }) + + test('return model instance from the factory callback', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + + class Profile extends BaseModel {} + Profile.boot() + + class User extends BaseModel { + @column({ isPrimary: true }) + declare id: number + + @column() + declare username: string + + @hasOne(() => Profile) + declare profile: HasOne + } + + const factory = factoryManager + .define(User, () => { + return new User() + }) + .build() + + const user = await factory.make() + assert.instanceOf(user, User) + }) +}) diff --git a/test/factory/has-many.spec.ts b/test/factory/has_many.spec.ts similarity index 58% rename from test/factory/has-many.spec.ts rename to test/factory/has_many.spec.ts index f103adba..130556f0 100644 --- a/test/factory/has-many.spec.ts +++ b/test/factory/has_many.spec.ts @@ -7,94 +7,82 @@ * file that was distributed with this source code. */ -/// - import { test } from '@japa/runner' -import type { HasMany } from '@ioc:Adonis/Lucid/Orm' -import { FactoryManager } from '../../src/Factory/index' -import { column, hasMany } from '../../src/Orm/Decorators' +import type { HasMany } from '../../adonis-typings/relations.js' + +import { FactoryManager } from '../../src/factory/index.js' +import { column, hasMany } from '../../src/orm/decorators/index.js' import { - fs, setup, getDb, cleanup, ormAdapter, resetTables, getBaseModel, - getFactoryModel, - setupApplication, -} from '../../test-helpers' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -let db: ReturnType -let app: ApplicationContract -let BaseModel: ReturnType -const FactoryModel = getFactoryModel() +} from '../../test-helpers/index.js' +import { AppFactory } from '@adonisjs/core/factories/app' + const factoryManager = new FactoryManager() test.group('Factory | HasMany | make', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('makeStubbed model with relationship', async ({ assert }) => { + test('makeStubbed model with relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } - const postFactory = new FactoryModel( - Post, - () => { + const postFactory = factoryManager + .define(Post, () => { return { title: 'Adonis 101', } - }, - factoryManager - ).build() + }) + .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .relation('posts', () => postFactory) .build() @@ -110,47 +98,48 @@ test.group('Factory | HasMany | make', (group) => { assert.equal(user.posts[0].userId, user.id) }) - test('pass custom attributes to relationship', async ({ assert }) => { + test('pass custom attributes to relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } - const postFactory = new FactoryModel( - Post, - () => { + const postFactory = factoryManager + .define(Post, () => { return { title: 'Adonis 101', } - }, - factoryManager - ).build() + }) + .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .relation('posts', () => postFactory) .build() @@ -166,47 +155,48 @@ test.group('Factory | HasMany | make', (group) => { assert.equal(user.posts[0].title, 'Lucid 101') }) - test('make many relationship', async ({ assert }) => { + test('make many relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } - const postFactory = new FactoryModel( - Post, - () => { + const postFactory = factoryManager + .define(Post, () => { return { title: 'Adonis 101', } - }, - factoryManager - ).build() + }) + .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .relation('posts', () => postFactory) .build() @@ -225,53 +215,54 @@ test.group('Factory | HasMany | make', (group) => { assert.equal(user.posts[1].title, 'Lucid 101') }) - test('merge attributes with the relationship', async ({ assert }) => { + test('merge attributes with the relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public tenantId: string + declare tenantId: string @column() - public title: string + declare title: string } Post.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public tenantId: string + declare tenantId: string @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } - const postFactory = new FactoryModel( - Post, - () => { + const postFactory = factoryManager + .define(Post, () => { return { title: 'Adonis 101', } - }, - factoryManager - ).build() + }) + .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .relation('posts', () => postFactory) .build() @@ -297,63 +288,59 @@ test.group('Factory | HasMany | make', (group) => { test.group('Factory | HasMany | create', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('create model with relationship', async ({ assert }) => { + test('create model with relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } - const postFactory = new FactoryModel( - Post, - () => { + const postFactory = factoryManager + .define(Post, () => { return { title: 'Adonis 101', } - }, - factoryManager - ).build() + }) + .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .relation('posts', () => postFactory) .build() @@ -373,47 +360,48 @@ test.group('Factory | HasMany | create', (group) => { assert.equal(posts[0].user_id, users[0].id) }) - test('pass custom attributes to relationship', async ({ assert }) => { + test('pass custom attributes to relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } - const postFactory = new FactoryModel( - Post, - () => { + const postFactory = factoryManager + .define(Post, () => { return { title: 'Adonis 101', } - }, - factoryManager - ).build() + }) + .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .relation('posts', () => postFactory) .build() @@ -429,47 +417,48 @@ test.group('Factory | HasMany | create', (group) => { assert.equal(user.posts[0].title, 'Lucid 101') }) - test('create many relationship', async ({ assert }) => { + test('create many relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } - const postFactory = new FactoryModel( - Post, - () => { + const postFactory = factoryManager + .define(Post, () => { return { title: 'Adonis 101', } - }, - factoryManager - ).build() + }) + .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .relation('posts', () => postFactory) .build() @@ -489,47 +478,48 @@ test.group('Factory | HasMany | create', (group) => { assert.equal(user.posts[1].title, 'Lucid 101') }) - test('create relationship with custom foreign key', async ({ assert }) => { + test('create relationship with custom foreign key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column({ columnName: 'user_id' }) - public authorId: number + declare authorId: number @column() - public title: string + declare title: string } Post.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 @hasMany(() => Post, { foreignKey: 'authorId' }) - public posts: HasMany + declare posts: HasMany } - const postFactory = new FactoryModel( - Post, - () => { + const postFactory = factoryManager + .define(Post, () => { return { title: 'Adonis 101', } - }, - factoryManager - ).build() + }) + .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .relation('posts', () => postFactory) .build() @@ -545,47 +535,48 @@ test.group('Factory | HasMany | create', (group) => { assert.equal(user.posts[0].title, 'Lucid 101') }) - test('rollback changes on error', async ({ assert }) => { + test('rollback changes on error', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(3) class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public title: string + declare title: string } Post.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } - const postFactory = new FactoryModel( - Post, - () => { + const postFactory = factoryManager + .define(Post, () => { return {} - }, - factoryManager - ).build() + }) + .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .relation('posts', () => postFactory) .build() @@ -602,53 +593,54 @@ test.group('Factory | HasMany | create', (group) => { assert.lengthOf(posts, 0) }) - test('pass custom attributes to relationship', async ({ assert }) => { + test('pass custom attributes to relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Post extends BaseModel { @column() - public userId: number + declare userId: number @column() - public tenantId: string + declare tenantId: string @column() - public title: string + declare title: string } Post.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public tenantId: string + declare tenantId: string @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } - const postFactory = new FactoryModel( - Post, - () => { + const postFactory = factoryManager + .define(Post, () => { return { title: 'Adonis 101', } - }, - factoryManager - ).build() + }) + .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .relation('posts', () => postFactory) .build() @@ -667,83 +659,81 @@ test.group('Factory | HasMany | create', (group) => { assert.equal(user.posts[0].title, 'Lucid 101') }) - test('pass custom attributes to deep nested relationship', async ({ assert }) => { + test('pass custom attributes to deep nested relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Comment extends BaseModel { @column() - public postId: number + declare postId: number @column() - public tenantId: string + declare tenantId: string @column() - public body: string + declare body: string } Comment.boot() class Post extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public tenantId: string + declare tenantId: string @column() - public title: string + declare title: string @hasMany(() => Comment) - public comments: HasMany + declare comments: HasMany } Post.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public tenantId: string + declare tenantId: string @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 @hasMany(() => Post) - public posts: HasMany + declare posts: HasMany } - const commentFactory = new FactoryModel( - Comment, - () => { + const commentFactory = factoryManager + .define(Comment, () => { return { body: 'Nice post', } - }, - factoryManager - ).build() + }) + .build() - const postFactory = new FactoryModel( - Post, - () => { + const postFactory = factoryManager + .define(Post, () => { return { title: 'Adonis 101', } - }, - factoryManager - ) + }) .relation('comments', () => commentFactory) .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .relation('posts', () => postFactory) .build() diff --git a/test/factory/has-one.spec.ts b/test/factory/has_one.spec.ts similarity index 56% rename from test/factory/has-one.spec.ts rename to test/factory/has_one.spec.ts index ff5074da..592498ad 100644 --- a/test/factory/has-one.spec.ts +++ b/test/factory/has_one.spec.ts @@ -7,94 +7,82 @@ * file that was distributed with this source code. */ -/// - import { test } from '@japa/runner' -import type { HasOne } from '@ioc:Adonis/Lucid/Orm' -import { FactoryManager } from '../../src/Factory/index' -import { column, hasOne } from '../../src/Orm/Decorators' +import type { HasOne } from '../../adonis-typings/relations.js' + +import { FactoryManager } from '../../src/factory/index.js' +import { column, hasOne } from '../../src/orm/decorators/index.js' import { - fs, setup, getDb, cleanup, ormAdapter, resetTables, getBaseModel, - getFactoryModel, - setupApplication, -} from '../../test-helpers' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -let db: ReturnType -let app: ApplicationContract -let BaseModel: ReturnType -const FactoryModel = getFactoryModel() +} from '../../test-helpers/index.js' +import { AppFactory } from '@adonisjs/core/factories/app' + const factoryManager = new FactoryManager() test.group('Factory | HasOne | make', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('make model with relationship', async ({ assert }) => { + test('make model with relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } - const profileFactory = new FactoryModel( - Profile, - () => { + const profileFactory = factoryManager + .define(Profile, () => { return { displayName: 'virk', } - }, - factoryManager - ).build() + }) + .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .relation('profile', () => profileFactory) .build() @@ -109,50 +97,51 @@ test.group('Factory | HasOne | make', (group) => { assert.equal(user.profile.userId, user.id) }) - test('pass custom attributes to relationship', async ({ assert }) => { + test('pass custom attributes to relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public id: number + declare id: number @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } - const profileFactory = new FactoryModel( - Profile, - () => { + const profileFactory = factoryManager + .define(Profile, () => { return { displayName: 'virk', } - }, - factoryManager - ).build() + }) + .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .relation('profile', () => profileFactory) .build() @@ -172,63 +161,59 @@ test.group('Factory | HasOne | make', (group) => { test.group('Factory | HasOne | create', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('create model with relationship', async ({ assert }) => { + test('create model with relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } - const profileFactory = new FactoryModel( - Profile, - () => { + const profileFactory = factoryManager + .define(Profile, () => { return { displayName: 'virk', } - }, - factoryManager - ).build() + }) + .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .relation('profile', () => profileFactory) .build() @@ -247,47 +232,48 @@ test.group('Factory | HasOne | create', (group) => { assert.equal(profiles[0].user_id, users[0].id) }) - test('pass custom attributes to relationship', async ({ assert }) => { + test('pass custom attributes to relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } - const profileFactory = new FactoryModel( - Profile, - () => { + const profileFactory = factoryManager + .define(Profile, () => { return { displayName: 'virk', } - }, - factoryManager - ).build() + }) + .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .relation('profile', () => profileFactory) .build() @@ -302,47 +288,48 @@ test.group('Factory | HasOne | create', (group) => { assert.equal(user.profile.userId, user.id) }) - test('create model with custom foreign key', async ({ assert }) => { + test('create model with custom foreign key', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Profile extends BaseModel { @column({ columnName: 'user_id' }) - public authorId: number + declare authorId: number @column() - public displayName: string + declare displayName: string } Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 @hasOne(() => Profile, { foreignKey: 'authorId' }) - public profile: HasOne + declare profile: HasOne } - const profileFactory = new FactoryModel( - Profile, - () => { + const profileFactory = factoryManager + .define(Profile, () => { return { displayName: 'virk', } - }, - factoryManager - ).build() + }) + .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .relation('profile', () => profileFactory) .build() @@ -354,47 +341,48 @@ test.group('Factory | HasOne | create', (group) => { assert.equal(user.profile.authorId, user.id) }) - test('rollback changes on error', async ({ assert }) => { + test('rollback changes on error', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(3) class Profile extends BaseModel { @column() - public userId: number + declare userId: number @column() - public displayName: string + declare displayName: string } Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 @hasOne(() => Profile) - public profile: HasOne + declare profile: HasOne } - const profileFactory = new FactoryModel( - Profile, - () => { + const profileFactory = factoryManager + .define(Profile, () => { return {} - }, - factoryManager - ).build() + }) + .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .relation('profile', () => profileFactory) .build() diff --git a/test/factory/many-to-many.spec.ts b/test/factory/many_to_many.spec.ts similarity index 60% rename from test/factory/many-to-many.spec.ts rename to test/factory/many_to_many.spec.ts index 4ca8941f..d7b800c4 100644 --- a/test/factory/many-to-many.spec.ts +++ b/test/factory/many_to_many.spec.ts @@ -6,92 +6,79 @@ * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ - -/// - import { test } from '@japa/runner' -import type { ManyToMany } from '@ioc:Adonis/Lucid/Orm' -import { FactoryManager } from '../../src/Factory/index' -import { column, manyToMany } from '../../src/Orm/Decorators' +import type { ManyToMany } from '../../adonis-typings/relations.js' + +import { FactoryManager } from '../../src/factory/index.js' +import { column, manyToMany } from '../../src/orm/decorators/index.js' import { - fs, setup, getDb, cleanup, ormAdapter, resetTables, getBaseModel, - getFactoryModel, - setupApplication, -} from '../../test-helpers' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -let db: ReturnType -let app: ApplicationContract -let BaseModel: ReturnType -const FactoryModel = getFactoryModel() +} from '../../test-helpers/index.js' +import { AppFactory } from '@adonisjs/core/factories/app' + const factoryManager = new FactoryManager() test.group('Factory | ManyToMany | make', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('make model with relationship', async ({ assert }) => { + test('make model with relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } Skill.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } - const postFactory = new FactoryModel( - Skill, - () => { + const postFactory = factoryManager + .define(Skill, () => { return { name: 'Programming', } - }, - factoryManager - ).build() + }) + .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .relation('skills', () => postFactory) .build() @@ -107,47 +94,48 @@ test.group('Factory | ManyToMany | make', (group) => { assert.isFalse(user.skills[0].$isPersisted) }) - test('pass custom attributes to relationship', async ({ assert }) => { + test('pass custom attributes to relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } Skill.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } - const postFactory = new FactoryModel( - Skill, - () => { + const postFactory = factoryManager + .define(Skill, () => { return { name: 'Programming', } - }, - factoryManager - ).build() + }) + .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .relation('skills', () => postFactory) .build() @@ -164,47 +152,48 @@ test.group('Factory | ManyToMany | make', (group) => { assert.equal(user.skills[0].name, 'Dancing') }) - test('make many relationship', async ({ assert }) => { + test('make many relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } Skill.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } - const postFactory = new FactoryModel( - Skill, - () => { + const postFactory = factoryManager + .define(Skill, () => { return { name: 'Programming', } - }, - factoryManager - ).build() + }) + .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .relation('skills', () => postFactory) .build() @@ -229,63 +218,59 @@ test.group('Factory | ManyToMany | make', (group) => { test.group('Factory | ManyToMany | create', (group) => { group.setup(async () => { - app = await setupApplication() - db = getDb(app) - BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.teardown(async () => { - await db.manager.closeAll() await cleanup() - await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) - test('create model with relationship', async ({ assert }) => { + test('create model with relationship', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } Skill.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } - const postFactory = new FactoryModel( - Skill, - () => { + const postFactory = factoryManager + .define(Skill, () => { return { name: 'Programming', } - }, - factoryManager - ).build() + }) + .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .relation('skills', () => postFactory) .build() @@ -306,47 +291,48 @@ test.group('Factory | ManyToMany | create', (group) => { assert.equal(skillUsers[0].skill_id, skills[0].id) }) - test('pass custom attributes', async ({ assert }) => { + test('pass custom attributes', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } Skill.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } - const postFactory = new FactoryModel( - Skill, - () => { + const postFactory = factoryManager + .define(Skill, () => { return { name: 'Programming', } - }, - factoryManager - ).build() + }) + .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .relation('skills', () => postFactory) .build() @@ -361,47 +347,48 @@ test.group('Factory | ManyToMany | create', (group) => { assert.equal(user.skills[0].name, 'Dancing') }) - test('create many relationships', async ({ assert }) => { + test('create many relationships', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } Skill.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } - const postFactory = new FactoryModel( - Skill, - () => { + const postFactory = factoryManager + .define(Skill, () => { return { name: 'Programming', } - }, - factoryManager - ).build() + }) + .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .relation('skills', () => postFactory) .build() @@ -420,47 +407,48 @@ test.group('Factory | ManyToMany | create', (group) => { assert.equal(user.skills[1].name, 'Programming') }) - test('rollback changes on error', async ({ assert }) => { + test('rollback changes on error', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + assert.plan(4) class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } Skill.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } - const postFactory = new FactoryModel( - Skill, - () => { + const postFactory = factoryManager + .define(Skill, () => { return {} - }, - factoryManager - ).build() + }) + .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .relation('skills', () => postFactory) .build() @@ -479,47 +467,48 @@ test.group('Factory | ManyToMany | create', (group) => { assert.lengthOf(userSkills, 0) }) - test('define pivot attributes for the pivot table', async ({ assert }) => { + test('define pivot attributes for the pivot table', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + const BaseModel = getBaseModel(adapter, app) + class Skill extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public name: string + declare name: string } Skill.boot() class User extends BaseModel { @column({ isPrimary: true }) - public id: number + declare id: number @column() - public username: string + declare username: string @column() - public points: number = 0 + points: number = 0 @manyToMany(() => Skill) - public skills: ManyToMany + declare skills: ManyToMany } - const postFactory = new FactoryModel( - Skill, - () => { + const postFactory = factoryManager + .define(Skill, () => { return { name: 'Programming', } - }, - factoryManager - ).build() + }) + .build() - const factory = new FactoryModel( - User, - () => { + const factory = factoryManager + .define(User, () => { return {} - }, - factoryManager - ) + }) .relation('skills', () => postFactory) .build() From 50b098b15cbffd17d7aad41b059617bfeafd2606 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Tue, 19 Sep 2023 15:55:05 +0530 Subject: [PATCH 08/70] refactor: migrate commands --- adonis-typings/container.ts | 26 -- adonis-typings/test_utils.ts | 21 -- adonis-typings/validator.ts | 28 --- commands/MakeFactory.ts | 97 -------- commands/MakeMigration.ts | 157 ------------ commands/MakeSeeder.ts | 40 --- commands/{DbSeed.ts => db_seed.ts} | 51 ++-- commands/{DbTruncate.ts => db_truncate.ts} | 32 +-- commands/{DbWipe.ts => db_wipe.ts} | 36 ++- commands/make_factory.ts | 38 +++ commands/make_migration.ts | 131 ++++++++++ commands/{MakeModel.ts => make_model.ts} | 46 ++-- commands/make_seeder.ts | 33 +++ .../{Migration/Base.ts => migration/base.ts} | 40 ++- .../Fresh.ts => migration/fresh.ts} | 22 +- .../Refresh.ts => migration/refresh.ts} | 20 +- .../Reset.ts => migration/reset.ts} | 18 +- .../Rollback.ts => migration/rollback.ts} | 45 ++-- .../{Migration/Run.ts => migration/run.ts} | 43 ++-- .../Status.ts => migration/status.ts} | 32 +-- example/index.ts | 4 +- package.json | 9 + providers/DatabaseProvider.ts | 199 --------------- providers/database_provider.ts | 43 ++++ services/db.ts | 23 ++ src/connection/index.ts | 2 +- src/connection/manager.ts | 2 +- src/database/{index.ts => main.ts} | 24 +- src/database/paginator/simple_paginator.ts | 5 +- src/database/query_builder/chainable.ts | 2 +- src/database/query_builder/database.ts | 7 +- src/database/query_builder/insert.ts | 4 +- src/database/query_builder/raw.ts | 4 +- src/database/static_builder/raw.ts | 2 +- src/database/static_builder/reference.ts | 2 +- src/dialects/base_sqlite.ts | 6 +- src/dialects/better_sqlite.ts | 2 +- src/dialects/index.ts | 6 +- src/dialects/mssql.ts | 6 +- src/dialects/mysql.ts | 6 +- src/dialects/oracle.ts | 2 +- src/dialects/pg.ts | 6 +- src/dialects/red_shift.ts | 6 +- src/dialects/sqlite.ts | 2 +- src/{factory => factories}/factory_builder.ts | 11 +- src/{factory => factories}/factory_context.ts | 4 +- src/{factory => factories}/factory_model.ts | 8 +- src/{factory/index.ts => factories/main.ts} | 11 +- src/{factory => factories}/relations/base.ts | 4 +- .../relations/belongs_to.ts | 6 +- .../relations/has_many.ts | 6 +- .../relations/has_one.ts | 6 +- .../relations/many_to_many.ts | 6 +- src/helpers/pretty_print.ts | 2 +- .../index.ts => migration/runner.ts} | 17 +- .../source.ts} | 2 +- src/orm/adapter/index.ts | 9 +- src/orm/base_model/index.ts | 6 +- src/orm/base_model/proxy_handler.ts | 2 +- src/orm/decorators/date.ts | 2 +- src/orm/decorators/date_time.ts | 2 +- src/orm/decorators/index.ts | 4 +- src/orm/main.ts | 15 ++ src/orm/model_keys/index.ts | 2 +- src/orm/naming_strategies/snake_case.ts | 4 +- src/orm/paginator/index.ts | 2 +- src/orm/preloader/index.ts | 6 +- src/orm/query_builder/index.ts | 8 +- .../relations/aggregates_loader/lazy_load.ts | 2 +- src/orm/relations/base/query_builder.ts | 15 +- src/orm/relations/base/sub_query_builder.ts | 11 +- src/orm/relations/belongs_to/index.ts | 16 +- src/orm/relations/belongs_to/query_builder.ts | 4 +- src/orm/relations/belongs_to/query_client.ts | 8 +- .../relations/belongs_to/sub_query_builder.ts | 10 +- src/orm/relations/has_many/index.ts | 16 +- src/orm/relations/has_many/query_builder.ts | 8 +- src/orm/relations/has_many/query_client.ts | 13 +- .../relations/has_many/sub_query_builder.ts | 10 +- src/orm/relations/has_many_through/index.ts | 8 +- .../has_many_through/query_builder.ts | 6 +- .../has_many_through/query_client.ts | 8 +- .../has_many_through/sub_query_builder.ts | 6 +- src/orm/relations/has_one/index.ts | 16 +- src/orm/relations/has_one/query_builder.ts | 4 +- src/orm/relations/has_one/query_client.ts | 13 +- .../relations/has_one/sub_query_builder.ts | 10 +- src/orm/relations/keys_extractor.ts | 2 +- src/orm/relations/many_to_many/index.ts | 6 +- .../relations/many_to_many/query_builder.ts | 6 +- .../relations/many_to_many/query_client.ts | 16 +- .../many_to_many/sub_query_builder.ts | 6 +- src/query_client/index.ts | 52 ++-- src/query_reporter/index.ts | 2 +- src/query_runner/index.ts | 2 +- src/schema/{index.ts => main.ts} | 8 +- .../index.ts => seeders/base_seeder.ts} | 2 +- src/seeders/main.ts | 10 + .../index.ts => seeders/runner.ts} | 8 +- .../seeders_source.ts => seeders/source.ts} | 2 +- src/transaction_client/index.ts | 8 +- {adonis-typings => src/types}/database.ts | 0 {adonis-typings => src/types}/events.ts | 0 {adonis-typings => src/types}/factory.ts | 0 {adonis-typings => src/types}/migrator.ts | 0 {adonis-typings => src/types}/model.ts | 0 {adonis-typings => src/types}/querybuilder.ts | 0 {adonis-typings => src/types}/relations.ts | 13 +- {adonis-typings => src/types}/schema.ts | 0 {adonis-typings => src/types}/seeder.ts | 0 src/utils/index.ts | 10 +- {templates => stubs}/database.txt | 0 stubs/factories/index.txt | 1 + stubs/main.ts | 12 + stubs/make/factory/main.stub | 16 ++ stubs/make/migration/alter.stub | 17 ++ .../make/migration/create.stub | 11 +- stubs/make/model/main.stub | 18 ++ stubs/make/seeder/main.stub | 11 + {templates => stubs}/seeder.txt | 0 templates/factories/index.txt | 1 - templates/factory.txt | 8 - templates/migration-alter.txt | 15 -- templates/model.txt | 13 - test-helpers/index.ts | 82 +----- test/bindings/validator.spec.ts | 2 +- test/commands/db-wipe.spec.ts | 68 ----- .../{db-seed.spec.ts => db_seed.spec.ts} | 88 ++++--- ...b-truncate.spec.ts => db_truncate.spec.ts} | 41 ++- test/commands/db_wipe.spec.ts | 60 +++++ test/commands/make-factory.spec.ts | 96 -------- test/commands/make-migration.spec.ts | 198 --------------- test/commands/make-model.spec.ts | 61 ----- test/commands/make_factory.spec.ts | 42 ++++ test/commands/make_migration.spec.ts | 125 ++++++++++ test/commands/make_model.spec.ts | 81 ++++++ test/commands/make_seeder.spec.ts | 37 +++ test/commands/migration/fresh.spec.ts | 95 +++---- test/commands/migration/refresh.spec.ts | 102 ++++---- test/commands/migration/reset.spec.ts | 58 ++--- test/commands/migration/run.spec.ts | 233 ++++++++++-------- test/connection/connection.spec.ts | 2 +- test/database/database.spec.ts | 2 +- test/factory/belongs_to.spec.ts | 4 +- test/factory/factory_builder.spec.ts | 6 +- test/factory/factory_model.spec.ts | 8 +- test/factory/has_many.spec.ts | 4 +- test/factory/has_one.spec.ts | 4 +- test/factory/many_to_many.spec.ts | 4 +- test/migrations/migration_source.spec.ts | 2 +- test/orm/base_model.spec.ts | 8 +- test/orm/base_model_options.spec.ts | 2 +- test/orm/model_belongs_to.spec.ts | 2 +- test/orm/model_has_many.spec.ts | 2 +- test/orm/model_has_many_through.spec.ts | 2 +- test/orm/model_has_one.spec.ts | 2 +- test/orm/model_many_to_many.spec.ts | 2 +- test/seeders/seeders_runner.spec.ts | 2 +- test/seeders/seeders_source.spec.ts | 2 +- test/utils.spec.ts | 4 +- 160 files changed, 1525 insertions(+), 1943 deletions(-) delete mode 100644 adonis-typings/container.ts delete mode 100644 adonis-typings/test_utils.ts delete mode 100644 adonis-typings/validator.ts delete mode 100644 commands/MakeFactory.ts delete mode 100644 commands/MakeMigration.ts delete mode 100644 commands/MakeSeeder.ts rename commands/{DbSeed.ts => db_seed.ts} (84%) rename commands/{DbTruncate.ts => db_truncate.ts} (79%) rename commands/{DbWipe.ts => db_wipe.ts} (82%) create mode 100644 commands/make_factory.ts create mode 100644 commands/make_migration.ts rename commands/{MakeModel.ts => make_model.ts} (67%) create mode 100644 commands/make_seeder.ts rename commands/{Migration/Base.ts => migration/base.ts} (84%) rename commands/{Migration/Fresh.ts => migration/fresh.ts} (86%) rename commands/{Migration/Refresh.ts => migration/refresh.ts} (86%) rename commands/{Migration/Reset.ts => migration/reset.ts} (81%) rename commands/{Migration/Rollback.ts => migration/rollback.ts} (71%) rename commands/{Migration/Run.ts => migration/run.ts} (70%) rename commands/{Migration/Status.ts => migration/status.ts} (76%) delete mode 100644 providers/DatabaseProvider.ts create mode 100644 providers/database_provider.ts create mode 100644 services/db.ts rename src/database/{index.ts => main.ts} (93%) rename src/{factory => factories}/factory_builder.ts (98%) rename src/{factory => factories}/factory_context.ts (74%) rename src/{factory => factories}/factory_model.ts (97%) rename src/{factory/index.ts => factories/main.ts} (81%) rename src/{factory => factories}/relations/base.ts (92%) rename src/{factory => factories}/relations/belongs_to.ts (87%) rename src/{factory => factories}/relations/has_many.ts (90%) rename src/{factory => factories}/relations/has_one.ts (89%) rename src/{factory => factories}/relations/many_to_many.ts (91%) rename src/{migrator/index.ts => migration/runner.ts} (98%) rename src/{migrator/migration_source.ts => migration/source.ts} (95%) create mode 100644 src/orm/main.ts rename src/schema/{index.ts => main.ts} (94%) rename src/{base_seeder/index.ts => seeders/base_seeder.ts} (82%) create mode 100644 src/seeders/main.ts rename src/{seeders_runner/index.ts => seeders/runner.ts} (91%) rename src/{seeders_runner/seeders_source.ts => seeders/source.ts} (95%) rename {adonis-typings => src/types}/database.ts (100%) rename {adonis-typings => src/types}/events.ts (100%) rename {adonis-typings => src/types}/factory.ts (100%) rename {adonis-typings => src/types}/migrator.ts (100%) rename {adonis-typings => src/types}/model.ts (100%) rename {adonis-typings => src/types}/querybuilder.ts (100%) rename {adonis-typings => src/types}/relations.ts (99%) rename {adonis-typings => src/types}/schema.ts (100%) rename {adonis-typings => src/types}/seeder.ts (100%) rename {templates => stubs}/database.txt (100%) create mode 100644 stubs/factories/index.txt create mode 100644 stubs/main.ts create mode 100644 stubs/make/factory/main.stub create mode 100644 stubs/make/migration/alter.stub rename templates/migration-make.txt => stubs/make/migration/create.stub (63%) create mode 100644 stubs/make/model/main.stub create mode 100644 stubs/make/seeder/main.stub rename {templates => stubs}/seeder.txt (100%) delete mode 100644 templates/factories/index.txt delete mode 100644 templates/factory.txt delete mode 100644 templates/migration-alter.txt delete mode 100644 templates/model.txt delete mode 100644 test/commands/db-wipe.spec.ts rename test/commands/{db-seed.spec.ts => db_seed.spec.ts} (50%) rename test/commands/{db-truncate.spec.ts => db_truncate.spec.ts} (65%) create mode 100644 test/commands/db_wipe.spec.ts delete mode 100644 test/commands/make-factory.spec.ts delete mode 100644 test/commands/make-migration.spec.ts delete mode 100644 test/commands/make-model.spec.ts create mode 100644 test/commands/make_factory.spec.ts create mode 100644 test/commands/make_migration.spec.ts create mode 100644 test/commands/make_model.spec.ts create mode 100644 test/commands/make_seeder.spec.ts diff --git a/adonis-typings/container.ts b/adonis-typings/container.ts deleted file mode 100644 index 91459a87..00000000 --- a/adonis-typings/container.ts +++ /dev/null @@ -1,26 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -// declare module '@ioc:Adonis/Core/Application' { -// import * as Orm from '@ioc:Adonis/Lucid/Orm' -// import Migrator from '@ioc:Adonis/Lucid/Migrator' -// import { DatabaseContract } from '@ioc:Adonis/Lucid/Database' -// import { FactoryManagerContract } from '@ioc:Adonis/Lucid/Factory' -// import { SchemaConstructorContract } from '@ioc:Adonis/Lucid/Schema' -// import { SeederConstructorContract } from '@ioc:Adonis/Lucid/Seeder' - -// export interface ContainerBindings { -// 'Adonis/Lucid/Database': DatabaseContract -// 'Adonis/Lucid/Factory': FactoryManagerContract -// 'Adonis/Lucid/Orm': typeof Orm -// 'Adonis/Lucid/Migrator': typeof Migrator -// 'Adonis/Lucid/Schema': SchemaConstructorContract -// 'Adonis/Lucid/Seeder': SeederConstructorContract -// } -// } diff --git a/adonis-typings/test_utils.ts b/adonis-typings/test_utils.ts deleted file mode 100644 index 8f8cccb6..00000000 --- a/adonis-typings/test_utils.ts +++ /dev/null @@ -1,21 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -// declare module '@ioc:Adonis/Core/TestUtils' { -// type HookCleanupHandler = () => Promise -// type HookCallback = () => Promise | Promise - -// export interface TestUtilsContract { -// db(connectionName?: string): { -// seed: HookCallback -// migrate: HookCallback -// truncate: HookCallback -// } -// } -// } diff --git a/adonis-typings/validator.ts b/adonis-typings/validator.ts deleted file mode 100644 index c32d7cca..00000000 --- a/adonis-typings/validator.ts +++ /dev/null @@ -1,28 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -// declare module '@ioc:Adonis/Core/Validator' { -// import { Rule } from '@ioc:Adonis/Core/Validator' - -// export type DbRowCheckOptions = { -// table: string -// column: string -// dateFormat?: string -// connection?: string -// caseInsensitive?: boolean -// constraints?: { [key: string]: any } -// where?: { [key: string]: any } -// whereNot?: { [key: string]: any } -// } - -// export interface Rules { -// exists(options: DbRowCheckOptions): Rule -// unique(options: DbRowCheckOptions): Rule -// } -// } diff --git a/commands/MakeFactory.ts b/commands/MakeFactory.ts deleted file mode 100644 index 609e9a85..00000000 --- a/commands/MakeFactory.ts +++ /dev/null @@ -1,97 +0,0 @@ -/* - * @adonisjs/assembler - * - * (c) AdonisJS - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -import { join } from 'path' -import { args, BaseCommand, flags } from '@adonisjs/core/build/standalone' - -/** - * Command to make a new Factory - */ -export default class MakeFactory extends BaseCommand { - public static commandName = 'make:factory' - public static description = 'Make a new factory' - - /** - * Name of the model to be used in the factory - */ - @args.string({ description: 'The name of the model' }) - public model: string - - /** - * Import path to the model used in the factory - */ - @flags.string({ description: 'The path to the model' }) - public modelPath: string - - @flags.boolean({ - description: 'Create the factory with the exact name as provided', - alias: 'e', - }) - public exact: boolean - - /** - * Generate model import path used in the factory - */ - private generateModelImportPath() { - let base = this.application.rcFile.namespaces.models || 'App/Models' - if (!base.endsWith('/')) { - base += '/' - } - - let importPath = this.model - if (this.modelPath) { - importPath = this.modelPath - } else if (importPath.endsWith('Factory')) { - importPath = importPath.replace(/Factory$/, '') - } - - if (importPath.startsWith(base)) { - return importPath - } - - return base + importPath - } - - /** - * Path to the factories directory - */ - protected getDestinationPath() { - const base = this.application.rcFile.directories.database || 'database' - return join(base, 'factories') - } - - /** - * Passed down to the stub template - */ - protected templateData() { - return { - model: this.model, - modelImportPath: this.generateModelImportPath(), - toModelName: () => { - return function (model: string, render: any) { - return render(model).split('/').pop() - } - }, - } - } - - public async run() { - const stub = join(__dirname, '..', 'templates', 'factory.txt') - - this.generator - .addFile(this.model, { pattern: 'pascalcase', form: 'singular', suffix: 'Factory' }) - .stub(stub) - .useMustache() - .destinationDir(this.getDestinationPath()) - .appRoot(this.application.appRoot) - .apply(this.templateData()) - - await this.generator.run() - } -} diff --git a/commands/MakeMigration.ts b/commands/MakeMigration.ts deleted file mode 100644 index 43d9e107..00000000 --- a/commands/MakeMigration.ts +++ /dev/null @@ -1,157 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -import { join } from 'path' -import { string } from '@poppinss/utils/build/helpers' -import { BaseCommand, args, flags } from '@adonisjs/core/build/standalone' - -export default class MakeMigration extends BaseCommand { - public static commandName = 'make:migration' - public static description = 'Make a new migration file' - public static settings = { - loadApp: true, - } - - /** - * The name of the migration file. We use this to create the migration - * file and generate the table name - */ - @args.string({ description: 'Name of the migration file' }) - public name: string - - /** - * Choose a custom pre-defined connection. Otherwise, we use the - * default connection - */ - @flags.string({ - description: 'The connection flag is used to lookup the directory for the migration file', - }) - public connection: string - - /** - * Pre select migration directory. If this is defined, we will ignore the paths - * defined inside the config. - */ - @flags.string({ description: 'Pre-select a migration directory' }) - public folder: string - - /** - * Custom table name for creating a new table - */ - @flags.string({ description: 'Define the table name for creating a new table' }) - public create: string - - /** - * Custom table name for altering an existing table - */ - @flags.string({ description: 'Define the table name for altering an existing table' }) - public table: string - - /** - * Not a valid connection - */ - private printNotAValidConnection(connection: string) { - this.logger.error( - `"${connection}" is not a valid connection name. Double check "config/database" file` - ) - } - - /** - * Returns the directory for creating the migration file - */ - private async getDirectory(migrationPaths?: string[]): Promise { - if (this.folder) { - return this.folder - } - - let directories = migrationPaths?.length ? migrationPaths : ['database/migrations'] - if (directories.length === 1) { - return directories[0] - } - - return this.prompt.choice('Select the migrations folder', directories, { name: 'folder' }) - } - - /** - * Execute command - */ - public async run(): Promise { - const db = this.application.container.use('Adonis/Lucid/Database') - this.connection = this.connection || db.primaryConnectionName - const connection = db.getRawConnection(this.connection || db.primaryConnectionName) - - /** - * Invalid database connection - */ - if (!connection) { - this.printNotAValidConnection(this.connection) - this.exitCode = 1 - return - } - - /** - * Not allowed together, hence we must notify the user about the same - */ - if (this.table && this.create) { - this.logger.warning('--table and --create cannot be used together. Ignoring --create') - } - - /** - * The folder for creating the schema file - */ - const folder = await this.getDirectory((connection.config.migrations || {}).paths) - - /** - * Using the user defined table name or an empty string. We can attempt to - * build the table name from the migration file name, but let's do that - * later. - */ - const tableName = this.table || this.create || '' - - /** - * Template stub - */ - const stub = join( - __dirname, - '..', - 'templates', - this.table ? 'migration-alter.txt' : 'migration-make.txt' - ) - - /** - * Prepend timestamp to keep schema files in the order they - * have been created - */ - const prefix = `${new Date().getTime()}_` - - this.generator - .addFile(this.name, { pattern: 'snakecase', form: 'plural', prefix }) - .stub(stub) - .destinationDir(folder) - .appRoot(this.application.cliCwd || this.application.appRoot) - .useMustache() - .apply({ - toClassName() { - return function (filename: string, render: (text: string) => string) { - const migrationClassName = string.camelCase( - tableName || render(filename).replace(prefix, '') - ) - return `${migrationClassName.charAt(0).toUpperCase()}${migrationClassName.slice(1)}` - } - }, - toTableName() { - return function (filename: string, render: (text: string) => string) { - return tableName || string.snakeCase(render(filename).replace(prefix, '')) - } - }, - }) - - await this.generator.run() - } -} diff --git a/commands/MakeSeeder.ts b/commands/MakeSeeder.ts deleted file mode 100644 index 223ff47a..00000000 --- a/commands/MakeSeeder.ts +++ /dev/null @@ -1,40 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -import { join } from 'path' -import { BaseCommand, args } from '@adonisjs/core/build/standalone' - -export default class MakeSeeder extends BaseCommand { - public static commandName = 'make:seeder' - public static description = 'Make a new Seeder file' - - /** - * The name of the seeder file. - */ - @args.string({ description: 'Name of the seeder class' }) - public name: string - - /** - * Execute command - */ - public async run(): Promise { - const stub = join(__dirname, '..', 'templates', 'seeder.txt') - - const path = this.application.rcFile.directories.seeds - - this.generator - .addFile(this.name, { pattern: 'pascalcase', form: 'singular' }) - .stub(stub) - .destinationDir(path || 'database/Seeders') - .useMustache() - .appRoot(this.application.cliCwd || this.application.appRoot) - - await this.generator.run() - } -} diff --git a/commands/DbSeed.ts b/commands/db_seed.ts similarity index 84% rename from commands/DbSeed.ts rename to commands/db_seed.ts index f326b13e..8693fe8b 100644 --- a/commands/DbSeed.ts +++ b/commands/db_seed.ts @@ -8,21 +8,21 @@ */ import slash from 'slash' -import { extname } from 'path' -import { FileNode } from '@ioc:Adonis/Lucid/Database' -import { SeederFileNode } from '@ioc:Adonis/Lucid/Seeder' -import { BaseCommand, flags } from '@adonisjs/core/build/standalone' +import { extname } from 'node:path' +import { BaseCommand, flags } from '@adonisjs/core/ace' -import type { SeedsRunner } from '../src/SeedsRunner' +import { FileNode } from '../src/types/database.js' +import { SeederFileNode } from '../src/types/seeder.js' +import type { SeedsRunner } from '../src/seeders/runner.js' export default class DbSeed extends BaseCommand { - public static commandName = 'db:seed' - public static description = 'Execute database seeders' - public static settings = { + static commandName = 'db:seed' + static description = 'Execute database seeders' + static settings = { loadApp: true, } - private seeder: SeedsRunner + private declare seeder: SeedsRunner /** * Track if one or more seeders have failed @@ -34,32 +34,35 @@ export default class DbSeed extends BaseCommand { * default connection */ @flags.string({ description: 'Define a custom database connection for the seeders', alias: 'c' }) - public connection: string + declare connection: string /** * Interactive mode allows selecting seeder files */ @flags.boolean({ description: 'Run seeders in interactive mode', alias: 'i' }) - public interactive: boolean + declare interactive: boolean /** * Define a custom set of seeder files. Interactive and files together ignores * the interactive mode. */ - @flags.array({ description: 'Define a custom set of seeders files names to run', alias: 'f' }) - public files: string[] = [] + @flags.array({ + description: 'Define a custom set of seeders files names to run', + alias: 'f', + }) + declare files: string[] /** * Display migrations result in one compact single-line output */ @flags.boolean({ description: 'A compact single-line output' }) - public compactOutput: boolean = false + declare compactOutput: boolean /** * Print log message to the console */ private printLogMessage(file: SeederFileNode) { - const colors = this['colors'] + const colors = this.colors let color: keyof typeof colors = 'gray' let message: string = '' @@ -86,9 +89,9 @@ export default class DbSeed extends BaseCommand { break } - console.log(`${colors[color]('❯')} ${colors[color](message)} ${file.file.name}`) + this.logger.log(`${colors[color]('❯')} ${colors[color](message)} ${file.file.name}`) if (prefix) { - console.log(` ${colors[color](prefix)}`) + this.logger.log(` ${colors[color](prefix)}`) } } @@ -121,7 +124,7 @@ export default class DbSeed extends BaseCommand { * "--files" flag */ private async getCherryPickedFiles(seedersFiles: FileNode[]): Promise { - if (this.files.length) { + if (this.files && this.files.length) { return this.files.map((file) => { const fileExt = extname(file) return (fileExt ? file.replace(fileExt, '') : file).replace(/^\.\/|^\.\\\\/, '') @@ -142,9 +145,9 @@ export default class DbSeed extends BaseCommand { * Instantiate seeders runner */ private async instantiateSeeder() { - const db = this.application.container.use('Adonis/Lucid/Database') - const { SeedsRunner } = await import('../src/SeedsRunner') - this.seeder = new SeedsRunner(db, this.application, this.connection) + const db = await this.app.container.make('lucid.db') + const { SeedsRunner } = await import('../src/seeders/runner.js') + this.seeder = new SeedsRunner(db, this.app, this.connection) } /** @@ -216,7 +219,7 @@ export default class DbSeed extends BaseCommand { * process here */ private async runAsSubCommand() { - const db = this.application.container.use('Adonis/Lucid/Database') + const db = await this.app.container.make('lucid.db') this.connection = this.connection || db.primaryConnectionName /** @@ -262,7 +265,7 @@ export default class DbSeed extends BaseCommand { /** * Handle command */ - public async run(): Promise { + async run(): Promise { if (this.isMain) { await this.runAsMain() } else { @@ -274,7 +277,7 @@ export default class DbSeed extends BaseCommand { * Lifecycle method invoked by ace after the "run" * method. */ - public async completed() { + async completed() { if (this.seeder && this.isMain) { await this.seeder.close() } diff --git a/commands/DbTruncate.ts b/commands/db_truncate.ts similarity index 79% rename from commands/DbTruncate.ts rename to commands/db_truncate.ts index 62799b0a..4a0211cd 100644 --- a/commands/DbTruncate.ts +++ b/commands/db_truncate.ts @@ -7,13 +7,13 @@ * file that was distributed with this source code. */ -import { BaseCommand, flags } from '@adonisjs/core/build/standalone' -import { QueryClientContract } from '@ioc:Adonis/Lucid/Database' +import { BaseCommand, flags } from '@adonisjs/core/ace' +import { QueryClientContract } from '../src/types/database.js' export default class DbTruncate extends BaseCommand { - public static commandName = 'db:truncate' - public static description = 'Truncate all tables in database' - public static settings = { + static commandName = 'db:truncate' + static description = 'Truncate all tables in database' + static settings = { loadApp: true, } @@ -22,13 +22,13 @@ export default class DbTruncate extends BaseCommand { * default connection */ @flags.string({ description: 'Define a custom database connection', alias: 'c' }) - public connection: string + declare connection: string /** * Force command execution in production */ @flags.boolean({ description: 'Explicitly force command to run in production' }) - public force: boolean + declare force: boolean /** * Not a valid connection @@ -43,13 +43,6 @@ export default class DbTruncate extends BaseCommand { * Prompts to take consent when truncating the database in production */ private async takeProductionConstent(): Promise { - /** - * Do not prompt when CLI is not interactive - */ - if (!this.isInteractive) { - return false - } - const question = 'You are in production environment. Want to continue truncating the database?' try { return await this.prompt.confirm(question) @@ -74,7 +67,7 @@ export default class DbTruncate extends BaseCommand { * process inside this method */ private async runAsSubCommand() { - const db = this.application.container.use('Adonis/Lucid/Database') + const db = await this.app.container.make('lucid.db') this.connection = this.connection || db.primaryConnectionName const connection = db.connection(this.connection || db.primaryConnectionName) @@ -82,7 +75,7 @@ export default class DbTruncate extends BaseCommand { * Continue with clearing the database when not in production * or force flag is passed */ - let continueTruncate = !this.application.inProduction || this.force + let continueTruncate = !this.app.inProduction || this.force if (!continueTruncate) { continueTruncate = await this.takeProductionConstent() } @@ -119,7 +112,7 @@ export default class DbTruncate extends BaseCommand { /** * Handle command */ - public async run(): Promise { + async run(): Promise { if (this.isMain) { await this.runAsMain() } else { @@ -131,9 +124,10 @@ export default class DbTruncate extends BaseCommand { * Lifecycle method invoked by ace after the "run" * method. */ - public async completed() { + async completed() { if (this.isMain) { - await this.application.container.use('Adonis/Lucid/Database').manager.closeAll(true) + const db = await this.app.container.make('lucid.db') + await db.manager.closeAll(true) } } } diff --git a/commands/DbWipe.ts b/commands/db_wipe.ts similarity index 82% rename from commands/DbWipe.ts rename to commands/db_wipe.ts index 71a5132e..5aa727c1 100644 --- a/commands/DbWipe.ts +++ b/commands/db_wipe.ts @@ -7,13 +7,13 @@ * file that was distributed with this source code. */ -import { BaseCommand, flags } from '@adonisjs/core/build/standalone' -import { QueryClientContract } from '@ioc:Adonis/Lucid/Database' +import { BaseCommand, flags } from '@adonisjs/core/ace' +import { QueryClientContract } from '../src/types/database.js' export default class DbWipe extends BaseCommand { - public static commandName = 'db:wipe' - public static description = 'Drop all tables, views and types in database' - public static settings = { + static commandName = 'db:wipe' + static description = 'Drop all tables, views and types in database' + static settings = { loadApp: true, } @@ -22,25 +22,25 @@ export default class DbWipe extends BaseCommand { * default connection */ @flags.string({ description: 'Define a custom database connection', alias: 'c' }) - public connection: string + declare connection: string /** * Drop all views in database */ @flags.boolean({ description: 'Drop all views' }) - public dropViews: boolean + declare dropViews: boolean /** * Drop all types in database */ @flags.boolean({ description: 'Drop all custom types (Postgres only)' }) - public dropTypes: boolean + declare dropTypes: boolean /** * Force command execution in production */ @flags.boolean({ description: 'Explicitly force command to run in production' }) - public force: boolean + declare force: boolean /** * Not a valid connection @@ -55,13 +55,6 @@ export default class DbWipe extends BaseCommand { * Prompts to take consent when wiping the database in production */ private async takeProductionConstent(): Promise { - /** - * Do not prompt when CLI is not interactive - */ - if (!this.isInteractive) { - return false - } - const question = 'You are in production environment. Want to continue wiping the database?' try { return await this.prompt.confirm(question) @@ -115,7 +108,7 @@ export default class DbWipe extends BaseCommand { * process inside this method */ private async runAsSubCommand() { - const db = this.application.container.use('Adonis/Lucid/Database') + const db = await this.app.container.make('lucid.db') this.connection = this.connection || db.primaryConnectionName const connection = db.connection(this.connection || db.primaryConnectionName) @@ -123,7 +116,7 @@ export default class DbWipe extends BaseCommand { * Continue with clearing the database when not in production * or force flag is passed */ - let continueWipe = !this.application.inProduction || this.force + let continueWipe = !this.app.inProduction || this.force if (!continueWipe) { continueWipe = await this.takeProductionConstent() } @@ -162,7 +155,7 @@ export default class DbWipe extends BaseCommand { /** * Handle command */ - public async run(): Promise { + async run(): Promise { if (this.isMain) { await this.runAsMain() } else { @@ -174,9 +167,10 @@ export default class DbWipe extends BaseCommand { * Lifecycle method invoked by ace after the "run" * method. */ - public async completed() { + async completed() { if (this.isMain) { - await this.application.container.use('Adonis/Lucid/Database').manager.closeAll(true) + const db = await this.app.container.make('lucid.db') + await db.manager.closeAll(true) } } } diff --git a/commands/make_factory.ts b/commands/make_factory.ts new file mode 100644 index 00000000..51f8edf8 --- /dev/null +++ b/commands/make_factory.ts @@ -0,0 +1,38 @@ +/* + * @adonisjs/assembler + * + * (c) AdonisJS + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import { stubsRoot } from '../stubs/main.js' +import { args, BaseCommand } from '@adonisjs/core/ace' + +/** + * Command to make a new Factory + */ +export default class MakeFactory extends BaseCommand { + static commandName = 'make:factory' + static description = 'Make a new factory' + + static options = { + allowUnknownFlags: true, + } + + /** + * Name of the model to be used in the factory + */ + @args.string({ description: 'Model name for which to create the factory' }) + declare model: string + + async run() { + const codemods = await this.createCodemods() + await codemods.makeUsingStub(stubsRoot, 'make/factory/main.stub', { + flags: this.parsed.flags, + entity: this.app.generators.createEntity(this.model), + model: this.app.generators.createEntity(this.model), + }) + } +} diff --git a/commands/make_migration.ts b/commands/make_migration.ts new file mode 100644 index 00000000..a2235849 --- /dev/null +++ b/commands/make_migration.ts @@ -0,0 +1,131 @@ +/* + * @adonisjs/lucid + * + * (c) Harminder Virk + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import { stubsRoot } from '../stubs/main.js' +import { args, BaseCommand, flags } from '@adonisjs/core/ace' + +export default class MakeMigration extends BaseCommand { + static commandName = 'make:migration' + static description = 'Make a new migration file' + static settings = { + loadApp: true, + allowUnknownFlags: true, + } + + /** + * The name of the migration file. We use this to create the migration + * file and generate the table name + */ + @args.string({ description: 'Name of the migration file' }) + declare name: string + + /** + * Choose a custom pre-defined connection. Otherwise, we use the + * default connection + */ + @flags.string({ + description: 'Select database connection for which to create the migration', + }) + declare connection: string + + /** + * Pre select migration directory. If this is defined, we will ignore the paths + * defined inside the config. + */ + @flags.string({ description: 'Select migration directory (if multiple sources are configured)' }) + declare folder: string + + /** + * Custom table name for creating a new table + */ + @flags.boolean({ description: 'Create a new default (Default action)' }) + declare create: boolean + + /** + * Custom table name for altering an existing table + */ + @flags.boolean({ description: 'Alter an existing table' }) + declare alter: boolean + + /** + * Not a valid connection + */ + private printNotAValidConnection(connection: string) { + this.logger.error( + `"${connection}" is not a valid connection name. Double check "config/database" file` + ) + } + + /** + * Returns the directory for creating the migration file + */ + private async getDirectory(migrationPaths?: string[]): Promise { + if (this.folder) { + return this.folder + } + + let directories = migrationPaths?.length ? migrationPaths : ['database/migrations'] + if (directories.length === 1) { + return directories[0] + } + + return this.prompt.choice('Select the migrations folder', directories, { name: 'folder' }) + } + + /** + * Execute command + */ + async run(): Promise { + const db = await this.app.container.make('lucid.db') + this.connection = this.connection || db.primaryConnectionName + const connection = db.getRawConnection(this.connection || db.primaryConnectionName) + + /** + * Invalid database connection + */ + if (!connection) { + this.printNotAValidConnection(this.connection) + this.exitCode = 1 + return + } + + /** + * Not allowed together, hence we must notify the user about the same + */ + if (this.alter && this.create) { + this.logger.warning('--alter and --create cannot be used together. Ignoring --create') + } + + /** + * Entity to create + */ + const entity = this.app.generators.createEntity(this.name) + + /** + * The folder for creating the schema file + */ + const folder = await this.getDirectory((connection.config.migrations || {}).paths) + + const prefix = new Date().getTime() + const action = this.alter ? 'alter' : 'create' + const tableName = this.app.generators.tableName(entity.name) + const fileName = `${prefix}_${action}_${tableName}_table` + + const codemods = await this.createCodemods() + await codemods.makeUsingStub(stubsRoot, `make/migration/${action}.stub`, { + entity, + flags: this.parsed.flags, + migration: { + tableName, + folder, + fileName, + }, + }) + } +} diff --git a/commands/MakeModel.ts b/commands/make_model.ts similarity index 67% rename from commands/MakeModel.ts rename to commands/make_model.ts index 1f2746dd..3f41fe52 100644 --- a/commands/MakeModel.ts +++ b/commands/make_model.ts @@ -7,13 +7,13 @@ * file that was distributed with this source code. */ -import { join } from 'path' -import { BaseCommand, args, flags } from '@adonisjs/core/build/standalone' +import { BaseCommand, args, flags } from '@adonisjs/core/ace' +import { stubsRoot } from '../stubs/main.js' export default class MakeModel extends BaseCommand { - public static commandName = 'make:model' - public static description = 'Make a new Lucid model' - public static settings = { + static commandName = 'make:model' + static description = 'Make a new Lucid model' + static settings = { loadApp: true, } @@ -21,7 +21,7 @@ export default class MakeModel extends BaseCommand { * The name of the model file. */ @args.string({ description: 'Name of the model class' }) - public name: string + declare name: string /** * Defines if we generate the migration for the model. @@ -31,7 +31,7 @@ export default class MakeModel extends BaseCommand { alias: 'm', description: 'Generate the migration for the model', }) - public migration: boolean + declare migration: boolean /** * Defines if we generate the controller for the model. @@ -41,7 +41,7 @@ export default class MakeModel extends BaseCommand { alias: 'c', description: 'Generate the controller for the model', }) - public controller: boolean + declare controller: boolean /** * Defines if we generate the factory for the model. @@ -51,13 +51,13 @@ export default class MakeModel extends BaseCommand { alias: 'f', description: 'Generate a factory for the model', }) - public factory: boolean + declare factory: boolean /** * Run migrations */ private async runMakeMigration() { - if (!this.migration) { + if (!this.migration || this.exitCode) { return } @@ -70,7 +70,7 @@ export default class MakeModel extends BaseCommand { * Make controller */ private async runMakeController() { - if (!this.controller) { + if (!this.controller || this.exitCode) { return } @@ -83,7 +83,7 @@ export default class MakeModel extends BaseCommand { * Make factory */ private async runMakeFactory() { - if (!this.factory) { + if (!this.factory || this.exitCode) { return } @@ -95,24 +95,14 @@ export default class MakeModel extends BaseCommand { /** * Execute command */ - public async run(): Promise { - const stub = join(__dirname, '..', 'templates', 'model.txt') - const path = this.application.resolveNamespaceDirectory('models') - - this.generator - .addFile(this.name, { pattern: 'pascalcase', form: 'singular' }) - .stub(stub) - .destinationDir(path || 'app/Models') - .useMustache() - .appRoot(this.application.cliCwd || this.application.appRoot) - - await this.generator.run() + async run(): Promise { + const codemods = await this.createCodemods() + await codemods.makeUsingStub(stubsRoot, 'make/model/main.stub', { + flags: this.parsed.flags, + entity: this.app.generators.createEntity(this.name), + }) await this.runMakeMigration() - if (this.exitCode) { - return - } - await this.runMakeController() await this.runMakeFactory() } diff --git a/commands/make_seeder.ts b/commands/make_seeder.ts new file mode 100644 index 00000000..57a36b6b --- /dev/null +++ b/commands/make_seeder.ts @@ -0,0 +1,33 @@ +/* + * @adonisjs/lucid + * + * (c) Harminder Virk + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import { BaseCommand, args } from '@adonisjs/core/ace' +import { stubsRoot } from '../stubs/main.js' + +export default class MakeSeeder extends BaseCommand { + static commandName = 'make:seeder' + static description = 'Make a new Seeder file' + + /** + * The name of the seeder file. + */ + @args.string({ description: 'Name of the seeder class' }) + declare name: string + + /** + * Execute command + */ + async run(): Promise { + const codemods = await this.createCodemods() + await codemods.makeUsingStub(stubsRoot, 'make/seeder/main.stub', { + flags: this.parsed.flags, + entity: this.app.generators.createEntity(this.name), + }) + } +} diff --git a/commands/Migration/Base.ts b/commands/migration/base.ts similarity index 84% rename from commands/Migration/Base.ts rename to commands/migration/base.ts index a144598c..89deb26e 100644 --- a/commands/Migration/Base.ts +++ b/commands/migration/base.ts @@ -8,11 +8,12 @@ */ import prettyHrTime from 'pretty-hrtime' -import { BaseCommand } from '@adonisjs/core/build/standalone' -import { MigratedFileNode, MigratorContract } from '@ioc:Adonis/Lucid/Migrator' +import { BaseCommand } from '@adonisjs/core/ace' -import { getDDLMethod } from '../../src/utils' -import { prettyPrint } from '../../src/Helpers/prettyPrint' +import { getDDLMethod } from '../../src/utils/index.js' +import type { MigrationRunner } from '../../src/migration/runner.js' +import { prettyPrint } from '../../src/helpers/pretty_print.js' +import { MigratedFileNode } from '../../src/types/migrator.js' /** * Base class to execute migrations and print logs @@ -36,13 +37,6 @@ export default abstract class MigrationsBase extends BaseCommand { * Prompts to take consent for running migrations in production */ protected async takeProductionConstent(): Promise { - /** - * Do not prompt when CLI is not interactive - */ - if (!this.isInteractive) { - return false - } - const question = 'You are in production environment. Want to continue running migrations?' try { return await this.prompt.confirm(question) @@ -75,8 +69,8 @@ export default abstract class MigrationsBase extends BaseCommand { * Pretty print sql queries of a file */ private prettyPrintSql(file: MigratedFileNode, connectionName: string) { - console.log(this.logger.colors.gray(`------------- ${file.file.name} -------------`)) - console.log() + this.logger.log(this.colors.gray(`------------- ${file.file.name} -------------`)) + this.logger.log('') file.queries.map((sql) => { prettyPrint({ connection: connectionName, @@ -85,24 +79,24 @@ export default abstract class MigrationsBase extends BaseCommand { method: getDDLMethod(sql), bindings: [], }) - console.log() + this.logger.log('') }) - console.log(this.logger.colors.gray('------------- END -------------')) + this.logger.log(this.colors.gray('------------- END -------------')) } /** * Log final status with verbose output */ - private logVerboseFinalStatus(migrator: MigratorContract, duration?: [number, number]) { + private logVerboseFinalStatus(migrator: MigrationRunner, duration?: [number, number]) { switch (migrator.status) { case 'completed': const completionMessage = migrator.direction === 'up' ? 'Migrated in' : 'Reverted in' - console.log(`\n${completionMessage} ${this.colors.cyan(prettyHrTime(duration))}`) + this.logger.log(`\n${completionMessage} ${this.colors.cyan(prettyHrTime(duration!))}`) break case 'skipped': const message = migrator.direction === 'up' ? 'Already up to date' : 'Already at latest batch' - console.log(this.colors.cyan(message)) + this.logger.log(this.colors.cyan(message)) break case 'error': this.logger.fatal(migrator.error!) @@ -116,7 +110,7 @@ export default abstract class MigrationsBase extends BaseCommand { */ private logCompactFinalStatus( processedFiles: Set, - migrator: MigratorContract, + migrator: MigrationRunner, duration?: [number, number] ) { let output = '' @@ -126,7 +120,7 @@ export default abstract class MigrationsBase extends BaseCommand { switch (migrator.status) { case 'completed': message = `❯ ${isUp ? 'Executed' : 'Reverted'} ${processedFiles.size} migrations` - output = this.colors.grey(message + ` (${prettyHrTime(duration)})`) + output = this.colors.grey(message + ` (${prettyHrTime(duration!)})`) break @@ -141,8 +135,8 @@ export default abstract class MigrationsBase extends BaseCommand { ).length message = `❯ Executed ${processedFiles.size} migrations, 1 error, ${skippedMigrations} skipped` - console.log(this.colors.red(message)) - console.log('\n' + this.colors.red(migrator.error!.message)) + this.logger.log(this.colors.red(message)) + this.logger.log('\n' + this.colors.red(migrator.error!.message)) this.exitCode = 1 break } @@ -153,7 +147,7 @@ export default abstract class MigrationsBase extends BaseCommand { /** * Runs the migrations using the migrator */ - protected async runMigrations(migrator: MigratorContract, connectionName: string): Promise { + protected async runMigrations(migrator: MigrationRunner, connectionName: string): Promise { /** * Pretty print SQL in dry run and return early */ diff --git a/commands/Migration/Fresh.ts b/commands/migration/fresh.ts similarity index 86% rename from commands/Migration/Fresh.ts rename to commands/migration/fresh.ts index 1c47baca..3fec73b7 100644 --- a/commands/Migration/Fresh.ts +++ b/commands/migration/fresh.ts @@ -7,16 +7,16 @@ * file that was distributed with this source code. */ -import { flags, BaseCommand } from '@adonisjs/core/build/standalone' +import { flags, BaseCommand } from '@adonisjs/core/ace' /** * This command reset the database by rolling back to batch 0 and then * re-run all migrations. */ export default class Refresh extends BaseCommand { - public static commandName = 'migration:fresh' - public static description = 'Drop all tables and re-migrate the database' - public static settings = { + static commandName = 'migration:fresh' + static description = 'Drop all tables and re-migrate the database' + static settings = { loadApp: true, } @@ -24,37 +24,37 @@ export default class Refresh extends BaseCommand { * Custom connection for running migrations. */ @flags.string({ description: 'Define a custom database connection', alias: 'c' }) - public connection: string + declare connection: string /** * Force command execution in production */ @flags.boolean({ description: 'Explicitly force command to run in production' }) - public force: boolean + declare force: boolean /** * Run seeders */ @flags.boolean({ description: 'Run seeders' }) - public seed: boolean + declare seed: boolean /** * Drop all views in database */ @flags.boolean({ description: 'Drop all views' }) - public dropViews: boolean + declare dropViews: boolean /** * Drop all types in database */ @flags.boolean({ description: 'Drop all custom types (Postgres only)' }) - public dropTypes: boolean + declare dropTypes: boolean /** * Disable advisory locks */ @flags.boolean({ description: 'Disable locks acquired to run migrations safely' }) - public disableLocks: boolean + declare disableLocks: boolean /** * Converting command properties to arguments @@ -127,7 +127,7 @@ export default class Refresh extends BaseCommand { /** * Handle command */ - public async run(): Promise { + async run(): Promise { await this.runDbWipe() if (this.exitCode) { return diff --git a/commands/Migration/Refresh.ts b/commands/migration/refresh.ts similarity index 86% rename from commands/Migration/Refresh.ts rename to commands/migration/refresh.ts index 28d852cd..f996c5fb 100644 --- a/commands/Migration/Refresh.ts +++ b/commands/migration/refresh.ts @@ -7,16 +7,16 @@ * file that was distributed with this source code. */ -import { flags, BaseCommand } from '@adonisjs/core/build/standalone' +import { flags, BaseCommand } from '@adonisjs/core/ace' /** * This command reset the database by rolling back to batch 0 and then * re-run all migrations. */ export default class Refresh extends BaseCommand { - public static commandName = 'migration:refresh' - public static description = 'Rollback and migrate database' - public static settings = { + static commandName = 'migration:refresh' + static description = 'Rollback and migrate database' + static settings = { loadApp: true, } @@ -24,31 +24,31 @@ export default class Refresh extends BaseCommand { * Custom connection for running migrations. */ @flags.string({ description: 'Define a custom database connection', alias: 'c' }) - public connection: string + declare connection: string /** * Force command execution in production */ @flags.boolean({ description: 'Explicitly force command to run in production' }) - public force: boolean + declare force: boolean /** * Perform dry run */ @flags.boolean({ description: 'Do not run actual queries. Instead view the SQL output' }) - public dryRun: boolean + declare dryRun: boolean /** * Run seeders */ @flags.boolean({ description: 'Run seeders' }) - public seed: boolean + declare seed: boolean /** * Disable advisory locks */ @flags.boolean({ description: 'Disable locks acquired to run migrations safely' }) - public disableLocks: boolean + declare disableLocks: boolean /** * Converting command properties to arguments @@ -109,7 +109,7 @@ export default class Refresh extends BaseCommand { /** * Handle command */ - public async run(): Promise { + async run(): Promise { await this.resetMigrations() if (this.exitCode) { return diff --git a/commands/Migration/Reset.ts b/commands/migration/reset.ts similarity index 81% rename from commands/Migration/Reset.ts rename to commands/migration/reset.ts index 09d5a90e..2599e023 100644 --- a/commands/Migration/Reset.ts +++ b/commands/migration/reset.ts @@ -7,16 +7,16 @@ * file that was distributed with this source code. */ -import { BaseCommand, flags } from '@adonisjs/core/build/standalone' +import { BaseCommand, flags } from '@adonisjs/core/ace' /** * This command resets the database by rolling back to batch 0. Same * as calling "migration:rollback --batch=0" */ export default class Reset extends BaseCommand { - public static commandName = 'migration:reset' - public static description = 'Rollback all migrations' - public static settings = { + static commandName = 'migration:reset' + static description = 'Rollback all migrations' + static settings = { loadApp: true, } @@ -24,25 +24,25 @@ export default class Reset extends BaseCommand { * Custom connection for running migrations. */ @flags.string({ description: 'Define a custom database connection', alias: 'c' }) - public connection: string + declare connection: string /** * Force command execution in production */ @flags.boolean({ description: 'Explicitly force command to run in production' }) - public force: boolean + declare force: boolean /** * Perform dry run */ @flags.boolean({ description: 'Do not run actual queries. Instead view the SQL output' }) - public dryRun: boolean + declare dryRun: boolean /** * Disable advisory locks */ @flags.boolean({ description: 'Disable locks acquired to run migrations safely' }) - public disableLocks: boolean + declare disableLocks: boolean /** * Converting command properties to arguments @@ -71,7 +71,7 @@ export default class Reset extends BaseCommand { /** * Handle command */ - public async run(): Promise { + async run(): Promise { const rollback = await this.kernel.exec('migration:rollback', this.getArgs()) this.exitCode = rollback.exitCode this.error = rollback.error diff --git a/commands/Migration/Rollback.ts b/commands/migration/rollback.ts similarity index 71% rename from commands/Migration/Rollback.ts rename to commands/migration/rollback.ts index f06f630e..9e373acf 100644 --- a/commands/Migration/Rollback.ts +++ b/commands/migration/rollback.ts @@ -7,41 +7,41 @@ * file that was distributed with this source code. */ -import { flags } from '@adonisjs/core/build/standalone' -import { MigratorContract } from '@ioc:Adonis/Lucid/Migrator' +import { flags } from '@adonisjs/core/ace' -import MigrationsBase from './Base' +import MigrationsBase from './base.js' +import { MigrationRunner } from '../../src/migration/runner.js' /** * The command is meant to migrate the database by executing migrations * in `down` direction. */ export default class Migrate extends MigrationsBase { - public static commandName = 'migration:rollback' - public static description = 'Rollback migrations to a specific batch number' - public static settings = { + static commandName = 'migration:rollback' + static description = 'Rollback migrations to a specific batch number' + static settings = { loadApp: true, } - private migrator: MigratorContract + private migrator?: MigrationRunner /** * Custom connection for running migrations. */ @flags.string({ description: 'Define a custom database connection', alias: 'c' }) - public connection: string + declare connection: string /** * Force run migrations in production */ @flags.boolean({ description: 'Explictly force to run migrations in production' }) - public force: boolean + declare force: boolean /** * Perform dry run */ @flags.boolean({ description: 'Do not run actual queries. Instead view the SQL output' }) - public dryRun: boolean + declare dryRun: boolean /** * Define custom batch, instead of rolling back to the latest batch @@ -49,28 +49,27 @@ export default class Migrate extends MigrationsBase { @flags.number({ description: 'Define custom batch number for rollback. Use 0 to rollback to initial state', }) - public batch: number + declare batch: number /** * Display migrations result in one compact single-line output */ @flags.boolean({ description: 'A compact single-line output' }) - public compactOutput: boolean = false + declare compactOutput: boolean /** * Disable advisory locks */ @flags.boolean({ description: 'Disable locks acquired to run migrations safely' }) - public disableLocks: boolean + declare disableLocks: boolean /** * Instantiating the migrator instance */ - private instantiateMigrator() { - const db = this.application.container.use('Adonis/Lucid/Database') - const Migrator = this.application.container.resolveBinding('Adonis/Lucid/Migrator') + private async instantiateMigrator() { + const db = await this.app.container.make('lucid.db') - this.migrator = new Migrator(db, this.application, { + this.migrator = new MigrationRunner(db, this.app, { direction: 'down', connectionName: this.connection, batch: this.batch, @@ -84,14 +83,14 @@ export default class Migrate extends MigrationsBase { * process inside this method */ private async runAsSubCommand() { - const db = this.application.container.use('Adonis/Lucid/Database') + const db = await this.app.container.make('lucid.db') this.connection = this.connection || db.primaryConnectionName /** * Continue with migrations when not in prod or force flag * is passed */ - let continueMigrations = !this.application.inProduction || this.force + let continueMigrations = !this.app.inProduction || this.force if (!continueMigrations) { continueMigrations = await this.takeProductionConstent() } @@ -112,8 +111,8 @@ export default class Migrate extends MigrationsBase { return } - this.instantiateMigrator() - await this.runMigrations(this.migrator, this.connection) + await this.instantiateMigrator() + await this.runMigrations(this.migrator!, this.connection) } /** @@ -129,7 +128,7 @@ export default class Migrate extends MigrationsBase { /** * Handle command */ - public async run(): Promise { + async run(): Promise { if (this.isMain) { await this.runAsMain() } else { @@ -141,7 +140,7 @@ export default class Migrate extends MigrationsBase { * Lifecycle method invoked by ace after the "run" * method. */ - public async completed() { + async completed() { if (this.migrator && this.isMain) { await this.migrator.close() } diff --git a/commands/Migration/Run.ts b/commands/migration/run.ts similarity index 70% rename from commands/Migration/Run.ts rename to commands/migration/run.ts index b7366523..7366140c 100644 --- a/commands/Migration/Run.ts +++ b/commands/migration/run.ts @@ -7,61 +7,60 @@ * file that was distributed with this source code. */ -import { flags } from '@adonisjs/core/build/standalone' -import { MigratorContract } from '@ioc:Adonis/Lucid/Migrator' -import MigrationsBase from './Base' +import { flags } from '@adonisjs/core/ace' +import MigrationsBase from './base.js' +import { MigrationRunner } from '../../src/migration/runner.js' /** * The command is meant to migrate the database by executing migrations * in `up` direction. */ export default class Migrate extends MigrationsBase { - public static commandName = 'migration:run' - public static description = 'Migrate database by running pending migrations' - public static settings = { + static commandName = 'migration:run' + static description = 'Migrate database by running pending migrations' + static settings = { loadApp: true, } - private migrator: MigratorContract + private migrator?: MigrationRunner /** * Custom connection for running migrations. */ @flags.string({ description: 'Define a custom database connection', alias: 'c' }) - public connection: string + declare connection: string /** * Force run migrations in production */ @flags.boolean({ description: 'Explicitly force to run migrations in production' }) - public force: boolean + declare force: boolean /** * Perform dry run */ @flags.boolean({ description: 'Do not run actual queries. Instead view the SQL output' }) - public dryRun: boolean + declare dryRun: boolean /** * Display migrations result in one compact single-line output */ @flags.boolean({ description: 'A compact single-line output' }) - public compactOutput: boolean = false + compactOutput: boolean = false /** * Disable advisory locks */ @flags.boolean({ description: 'Disable locks acquired to run migrations safely' }) - public disableLocks: boolean + declare disableLocks: boolean /** * Instantiating the migrator instance */ - private instantiateMigrator() { - const db = this.application.container.use('Adonis/Lucid/Database') - const Migrator = this.application.container.resolveBinding('Adonis/Lucid/Migrator') + private async instantiateMigrator() { + const db = await this.app.container.make('lucid.db') - this.migrator = new Migrator(db, this.application, { + this.migrator = new MigrationRunner(db, this.app, { direction: 'up', connectionName: this.connection, dryRun: this.dryRun, @@ -74,14 +73,14 @@ export default class Migrate extends MigrationsBase { * process inside this method */ private async runAsSubCommand() { - const db = this.application.container.use('Adonis/Lucid/Database') + const db = await this.app.container.make('lucid.db') this.connection = this.connection || db.primaryConnectionName /** * Continue with migrations when not in prod or force flag * is passed */ - let continueMigrations = !this.application.inProduction || this.force + let continueMigrations = !this.app.inProduction || this.force if (!continueMigrations) { continueMigrations = await this.takeProductionConstent() } @@ -102,8 +101,8 @@ export default class Migrate extends MigrationsBase { return } - this.instantiateMigrator() - await this.runMigrations(this.migrator, this.connection) + await this.instantiateMigrator() + await this.runMigrations(this.migrator!, this.connection) } /** @@ -119,7 +118,7 @@ export default class Migrate extends MigrationsBase { /** * Handle command */ - public async run(): Promise { + async run(): Promise { if (this.isMain) { await this.runAsMain() } else { @@ -131,7 +130,7 @@ export default class Migrate extends MigrationsBase { * Lifecycle method invoked by ace after the "run" * method. */ - public async completed() { + async completed() { if (this.migrator && this.isMain) { await this.migrator.close() } diff --git a/commands/Migration/Status.ts b/commands/migration/status.ts similarity index 76% rename from commands/Migration/Status.ts rename to commands/migration/status.ts index 4cfe0a1b..2f16f7d0 100644 --- a/commands/Migration/Status.ts +++ b/commands/migration/status.ts @@ -7,27 +7,28 @@ * file that was distributed with this source code. */ -import { flags, BaseCommand } from '@adonisjs/core/build/standalone' -import { MigrationListNode, MigratorContract } from '@ioc:Adonis/Lucid/Migrator' +import { flags, BaseCommand } from '@adonisjs/core/ace' +import { MigrationListNode } from '../../src/types/migrator.js' +import { MigrationRunner } from '../../src/migration/runner.js' /** * The command is meant to migrate the database by execute migrations * in `up` direction. */ export default class Status extends BaseCommand { - public static commandName = 'migration:status' - public static description = 'View migrations status' - public static settings = { + static commandName = 'migration:status' + static description = 'View migrations status' + static settings = { loadApp: true, } - private migrator: MigratorContract + private migrator?: MigrationRunner /** * Define custom connection */ @flags.string({ description: 'Define a custom database connection', alias: 'c' }) - public connection: string + declare connection: string /** * Not a valid connection @@ -55,11 +56,10 @@ export default class Status extends BaseCommand { /** * Instantiating the migrator instance */ - private instantiateMigrator() { - const db = this.application.container.use('Adonis/Lucid/Database') - const Migrator = this.application.container.resolveBinding('Adonis/Lucid/Migrator') + private async instantiateMigrator() { + const db = await this.app.container.make('lucid.db') - this.migrator = new Migrator(db, this.application, { + this.migrator = new MigrationRunner(db, this.app, { direction: 'up', connectionName: this.connection, }) @@ -92,7 +92,7 @@ export default class Status extends BaseCommand { * process inside this method */ private async runAsSubCommand() { - const db = this.application.container.use('Adonis/Lucid/Database') + const db = await this.app.container.make('lucid.db') this.connection = this.connection || db.primaryConnectionName /** @@ -104,8 +104,8 @@ export default class Status extends BaseCommand { return } - this.instantiateMigrator() - this.renderList(await this.migrator.getList()) + await this.instantiateMigrator() + this.renderList(await this.migrator!.getList()) } /** @@ -121,7 +121,7 @@ export default class Status extends BaseCommand { /** * Handle command */ - public async run(): Promise { + async run(): Promise { if (this.isMain) { await this.runAsMain() } else { @@ -133,7 +133,7 @@ export default class Status extends BaseCommand { * Lifecycle method invoked by ace after the "run" * method. */ - public async completed() { + async completed() { if (this.migrator && this.isMain) { await this.migrator.close() } diff --git a/example/index.ts b/example/index.ts index 5270c4c6..ddb852d9 100644 --- a/example/index.ts +++ b/example/index.ts @@ -1,9 +1,9 @@ import { DateTime } from 'luxon' import { BaseModel } from '../src/orm/base_model/index.js' import { column, hasOne } from '../src/orm/decorators/index.js' -import { HasOne } from '../adonis-typings/relations.js' +import { HasOne } from '../src/types/relations.js' import { scope } from '../src/helpers/scope.js' -import { ModelQueryBuilderContract } from '../adonis-typings/model.js' +import { ModelQueryBuilderContract } from '../src/types/model.js' // import Factory from '@ioc:Adonis/Lucid/Factory' enum ProfileTypes { diff --git a/package.json b/package.json index 3cde9e64..6aee925e 100644 --- a/package.json +++ b/package.json @@ -6,6 +6,15 @@ "node": ">=18.16.0" }, "type": "module", + "exports": { + "./schema": "./build/src/schema/main.js", + "./factories": "./build/src/factories/main.js", + "./database": "./build/src/database/main.js", + "./orm": "./build/src/orm/main.js", + "./seeders": "./build/src/seeders/main.js", + "./services/*": "./build/services/*.js", + "./types/*": "./build/types/*.js" + }, "scripts": { "pretest": "npm run lint", "test:better_sqlite": "DB=better_sqlite node --enable-source-maps --loader=ts-node/esm ./bin/test.js", diff --git a/providers/DatabaseProvider.ts b/providers/DatabaseProvider.ts deleted file mode 100644 index f5b8f402..00000000 --- a/providers/DatabaseProvider.ts +++ /dev/null @@ -1,199 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -/** - * Database service provider - */ -export default class DatabaseServiceProvider { - constructor(protected app: ApplicationContract) {} - public static needsApplication = true - - /** - * Register the database binding - */ - private registerDatabase() { - this.app.container.singleton('Adonis/Lucid/Database', () => { - const config = this.app.container.resolveBinding('Adonis/Core/Config').get('database', {}) - const Logger = this.app.container.resolveBinding('Adonis/Core/Logger') - const Profiler = this.app.container.resolveBinding('Adonis/Core/Profiler') - const Emitter = this.app.container.resolveBinding('Adonis/Core/Event') - - const { Database } = require('../src/Database') - return new Database(config, Logger, Profiler, Emitter) - }) - } - - /** - * Registers ORM - */ - private registerOrm() { - this.app.container.singleton('Adonis/Lucid/Orm', () => { - const { Adapter } = require('../src/Orm/Adapter') - const { scope } = require('../src/Helpers/scope') - const decorators = require('../src/Orm/Decorators') - const { BaseModel } = require('../src/Orm/BaseModel') - const { ModelPaginator } = require('../src/Orm/Paginator') - const { SnakeCaseNamingStrategy } = require('../src/Orm/NamingStrategies/SnakeCase') - - /** - * Attaching adapter to the base model. Each model is allowed to define - * a different adapter. - */ - BaseModel.$adapter = new Adapter(this.app.container.resolveBinding('Adonis/Lucid/Database')) - BaseModel.$container = this.app.container - - return { - BaseModel, - ModelPaginator, - SnakeCaseNamingStrategy, - scope, - ...decorators, - } - }) - } - - /** - * Registers schema class - */ - private registerSchema() { - this.app.container.singleton('Adonis/Lucid/Schema', () => { - const { Schema } = require('../src/Schema') - return Schema - }) - } - - /** - * Registers schema class - */ - private registerFactory() { - this.app.container.singleton('Adonis/Lucid/Factory', () => { - const { FactoryManager } = require('../src/Factory') - return new FactoryManager() - }) - } - - /** - * Registers schema class - */ - private registerBaseSeeder() { - this.app.container.singleton('Adonis/Lucid/Seeder', () => { - const { BaseSeeder } = require('../src/BaseSeeder') - return BaseSeeder - }) - } - - /** - * Registers the health checker - */ - private registerHealthChecker() { - /** - * Do not register health checks in the repl environment - */ - if (this.app.environment === 'repl') { - return - } - - this.app.container.withBindings( - ['Adonis/Core/HealthCheck', 'Adonis/Lucid/Database'], - (HealthCheck, Db) => { - if (Db.hasHealthChecksEnabled) { - HealthCheck.addChecker('lucid', 'Adonis/Lucid/Database') - } - } - ) - } - - /** - * Register the migrator used for database migration - */ - private registerMigrator() { - this.app.container.bind('Adonis/Lucid/Migrator', () => { - const { Migrator } = require('../src/Migrator') - return Migrator - }) - } - - /** - * Extends the validator by defining validation rules - */ - private defineValidationRules() { - /** - * Do not register validation rules in the "repl" environment - */ - if (this.app.environment === 'repl') { - return - } - - this.app.container.withBindings( - ['Adonis/Core/Validator', 'Adonis/Lucid/Database', 'Adonis/Core/Logger'], - (Validator, Db, Logger) => { - const { extendValidator } = require('../src/Bindings/Validator') - extendValidator(Validator.validator, Db, Logger) - } - ) - } - - /** - * Defines REPL bindings - */ - private defineReplBindings() { - if (this.app.environment !== 'repl') { - return - } - - this.app.container.withBindings(['Adonis/Addons/Repl'], (Repl) => { - const { defineReplBindings } = require('../src/Bindings/Repl') - defineReplBindings(this.app, Repl) - }) - } - - /** - * Define test utilities for database - */ - private defineTestUtils() { - this.app.container.withBindings( - ['Adonis/Core/TestUtils', 'Adonis/Core/Ace'], - (testUtils, ace) => { - const { defineTestUtils } = require('../src/Bindings/TestUtils') - return new defineTestUtils(testUtils, ace) - } - ) - } - - /** - * Called when registering providers - */ - public register(): void { - this.registerDatabase() - this.registerOrm() - this.registerSchema() - this.registerFactory() - this.registerBaseSeeder() - this.registerMigrator() - } - - /** - * Called when all bindings are in place - */ - public boot(): void { - this.registerHealthChecker() - this.defineValidationRules() - this.defineReplBindings() - this.defineTestUtils() - } - - /** - * Gracefully close connections during shutdown - */ - public async shutdown() { - await this.app.container.resolveBinding('Adonis/Lucid/Database').manager.closeAll() - } -} diff --git a/providers/database_provider.ts b/providers/database_provider.ts new file mode 100644 index 00000000..7f096e16 --- /dev/null +++ b/providers/database_provider.ts @@ -0,0 +1,43 @@ +/* + * @adonisjs/lucid + * + * (c) Harminder Virk + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import type { ApplicationService } from '@adonisjs/core/types' + +import { Database } from '../src/database/main.js' +import { QueryClient } from '../src/query_client/index.js' +import type { DatabaseConfig } from '../src/types/database.js' + +declare module '@adonisjs/core/types' { + export interface ContainerBindings { + 'lucid.db': Database + } +} + +/** + * Database service provider + */ +export default class DatabaseServiceProvider { + constructor(protected app: ApplicationService) {} + + register() { + this.app.container.singleton(Database, async (resolver) => { + const config = this.app.config.get('database') + const emitter = await resolver.make('emitter') + const logger = await resolver.make('logger') + return new Database(config, logger, emitter) + }) + + this.app.container.singleton(QueryClient, async (resolver) => { + const db = await resolver.make('lucid.db') + return db.connection() as QueryClient + }) + + this.app.container.alias('lucid.db', Database) + } +} diff --git a/services/db.ts b/services/db.ts new file mode 100644 index 00000000..87769955 --- /dev/null +++ b/services/db.ts @@ -0,0 +1,23 @@ +/* + * @adonisjs/lucid + * + * (c) AdonisJS + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import app from '@adonisjs/core/services/app' +import { Database } from '../src/database/main.js' + +let db: Database + +/** + * Returns a singleton instance of the Database class from the + * container + */ +await app.booted(async () => { + db = await app.container.make(Database) +}) + +export { db as default } diff --git a/src/connection/index.ts b/src/connection/index.ts index b3fa9e68..6ccce980 100644 --- a/src/connection/index.ts +++ b/src/connection/index.ts @@ -15,7 +15,7 @@ import { patchKnex } from 'knex-dynamic-connection' import type { Logger } from '@adonisjs/core/logger' // @ts-expect-error import { resolveClientNameWithAliases } from 'knex/lib/util/helpers.js' -import { ConnectionConfig, ConnectionContract, ReportNode } from '../../adonis-typings/database.js' +import { ConnectionConfig, ConnectionContract, ReportNode } from '../types/database.js' import { Logger as ConnectionLogger } from './logger.js' diff --git a/src/connection/manager.ts b/src/connection/manager.ts index 88bde2f8..42a68238 100644 --- a/src/connection/manager.ts +++ b/src/connection/manager.ts @@ -17,7 +17,7 @@ import { ConnectionConfig, ConnectionContract, ConnectionManagerContract, -} from '../../adonis-typings/database.js' +} from '../types/database.js' import { Connection } from './index.js' diff --git a/src/database/index.ts b/src/database/main.ts similarity index 93% rename from src/database/index.ts rename to src/database/main.ts index 59c55ce3..bf7a5d38 100644 --- a/src/database/index.ts +++ b/src/database/main.ts @@ -7,8 +7,8 @@ * file that was distributed with this source code. */ -import { Exception } from '@poppinss/utils' import Macroable from '@poppinss/macroable' +import { Exception } from '@poppinss/utils' import type { Emitter } from '@adonisjs/core/events' import type { Logger } from '@adonisjs/core/logger' @@ -19,8 +19,9 @@ import { DatabaseClientOptions, TransactionClientContract, ConnectionManagerContract, -} from '../../adonis-typings/database.js' +} from '../types/database.js' +import { LucidModel } from '../types/model.js' import { QueryClient } from '../query_client/index.js' import { RawBuilder } from './static_builder/raw.js' import { prettyPrint } from '../helpers/pretty_print.js' @@ -29,20 +30,14 @@ import { InsertQueryBuilder } from './query_builder/insert.js' import { ReferenceBuilder } from './static_builder/reference.js' import { SimplePaginator } from './paginator/simple_paginator.js' import { DatabaseQueryBuilder } from './query_builder/database.js' -import { ModelQueryBuilder } from '../orm/query_builder/index.js' -import { LucidModel } from '../../adonis-typings/model.js' + +export { DatabaseQueryBuilder, InsertQueryBuilder, SimplePaginator, QueryClient } /** * Database class exposes the API to manage multiple connections and obtain an instance * of query/transaction clients. */ export class Database extends Macroable { - /** - * Reference to self constructor. TypeScript sucks with "this.constructor" - * https://github.com/microsoft/TypeScript/issues/4586 - */ - Database = Database - /** * Reference to connections manager */ @@ -53,15 +48,6 @@ export class Database extends Macroable { */ primaryConnectionName: string - /** - * Reference to query builders. We expose them, so that they can be - * extended from outside using macros. - */ - DatabaseQueryBuilder = DatabaseQueryBuilder - InsertQueryBuilder = InsertQueryBuilder - ModelQueryBuilder = ModelQueryBuilder - SimplePaginator = SimplePaginator - /** * A store of global transactions */ diff --git a/src/database/paginator/simple_paginator.ts b/src/database/paginator/simple_paginator.ts index e313aaae..72afda9c 100644 --- a/src/database/paginator/simple_paginator.ts +++ b/src/database/paginator/simple_paginator.ts @@ -8,10 +8,7 @@ */ import { stringify } from 'qs' -import { - SimplePaginatorContract, - SimplePaginatorMetaKeys, -} from '../../../adonis-typings/querybuilder.js' +import { SimplePaginatorContract, SimplePaginatorMetaKeys } from '../../types/querybuilder.js' import { SnakeCaseNamingStrategy } from '../../Orm/naming_strategies/snake_case.js' /** diff --git a/src/database/query_builder/chainable.ts b/src/database/query_builder/chainable.ts index b709f11e..1743e623 100644 --- a/src/database/query_builder/chainable.ts +++ b/src/database/query_builder/chainable.ts @@ -10,7 +10,7 @@ import { Knex } from 'knex' import Macroable from '@poppinss/macroable' import { Exception } from '@poppinss/utils' -import { ChainableContract, DBQueryCallback } from '../../../adonis-typings/querybuilder.js' +import { ChainableContract, DBQueryCallback } from '../../types/querybuilder.js' import { isObject } from '../../utils/index.js' import { RawQueryBuilder } from './raw.js' diff --git a/src/database/query_builder/database.ts b/src/database/query_builder/database.ts index 7276871c..1dc477d5 100644 --- a/src/database/query_builder/database.ts +++ b/src/database/query_builder/database.ts @@ -13,11 +13,8 @@ import { DialectContract, QueryClientContract, TransactionClientContract, -} from '../../../adonis-typings/database.js' -import { - DBQueryCallback, - DatabaseQueryBuilderContract, -} from '../../../adonis-typings/querybuilder.js' +} from '../../types/database.js' +import { DBQueryCallback, DatabaseQueryBuilderContract } from '../../types/querybuilder.js' import { Chainable } from './chainable.js' import { QueryRunner } from '../../query_runner/index.js' diff --git a/src/database/query_builder/insert.ts b/src/database/query_builder/insert.ts index f9b28750..2aa7bd5a 100644 --- a/src/database/query_builder/insert.ts +++ b/src/database/query_builder/insert.ts @@ -10,8 +10,8 @@ import { Knex } from 'knex' import Macroable from '@poppinss/macroable' -import { InsertQueryBuilderContract } from '../../../adonis-typings/querybuilder.js' -import { QueryClientContract, TransactionClientContract } from '../../../adonis-typings/database.js' +import { InsertQueryBuilderContract } from '../../types/querybuilder.js' +import { QueryClientContract, TransactionClientContract } from '../../types/database.js' import { RawQueryBuilder } from './raw.js' import { RawBuilder } from '../static_builder/raw.js' diff --git a/src/database/query_builder/raw.ts b/src/database/query_builder/raw.ts index 026d4aab..813b07e6 100644 --- a/src/database/query_builder/raw.ts +++ b/src/database/query_builder/raw.ts @@ -10,8 +10,8 @@ import { Knex } from 'knex' import { QueryRunner } from '../../query_runner/index.js' -import { RawQueryBuilderContract } from '../../../adonis-typings/querybuilder.js' -import { QueryClientContract, TransactionClientContract } from '../../../adonis-typings/database.js' +import { RawQueryBuilderContract } from '../../types/querybuilder.js' +import { QueryClientContract, TransactionClientContract } from '../../types/database.js' /** * Exposes the API to execute raw queries diff --git a/src/database/static_builder/raw.ts b/src/database/static_builder/raw.ts index fcde0fbb..88107034 100644 --- a/src/database/static_builder/raw.ts +++ b/src/database/static_builder/raw.ts @@ -8,7 +8,7 @@ */ import { Knex } from 'knex' -import { RawBuilderContract } from '../../../adonis-typings/querybuilder.js' +import { RawBuilderContract } from '../../types/querybuilder.js' /** * Exposes the API to construct raw queries. If you want to execute diff --git a/src/database/static_builder/reference.ts b/src/database/static_builder/reference.ts index 52e875ca..31458df0 100644 --- a/src/database/static_builder/reference.ts +++ b/src/database/static_builder/reference.ts @@ -8,7 +8,7 @@ */ import { Knex } from 'knex' -import { ReferenceBuilderContract } from '../../../adonis-typings/querybuilder.js' +import { ReferenceBuilderContract } from '../../types/querybuilder.js' /** * Reference builder to create SQL reference values diff --git a/src/dialects/base_sqlite.ts b/src/dialects/base_sqlite.ts index 5a6d806d..cdbd567c 100644 --- a/src/dialects/base_sqlite.ts +++ b/src/dialects/base_sqlite.ts @@ -7,11 +7,7 @@ * file that was distributed with this source code. */ -import type { - DialectContract, - QueryClientContract, - SharedConfigNode, -} from '../../adonis-typings/database.js' +import type { DialectContract, QueryClientContract, SharedConfigNode } from '../types/database.js' export abstract class BaseSqliteDialect implements DialectContract { abstract readonly name: 'sqlite3' | 'better-sqlite3' diff --git a/src/dialects/better_sqlite.ts b/src/dialects/better_sqlite.ts index 6525886b..05543aa9 100644 --- a/src/dialects/better_sqlite.ts +++ b/src/dialects/better_sqlite.ts @@ -7,7 +7,7 @@ * file that was distributed with this source code. */ -import { DialectContract } from '../../adonis-typings/database.js' +import { DialectContract } from '../types/database.js' import { BaseSqliteDialect } from './base_sqlite.js' export class BetterSqliteDialect extends BaseSqliteDialect implements DialectContract { diff --git a/src/dialects/index.ts b/src/dialects/index.ts index e30fc5cb..87e24426 100644 --- a/src/dialects/index.ts +++ b/src/dialects/index.ts @@ -14,11 +14,7 @@ import { SqliteDialect } from './sqlite.js' import { OracleDialect } from './oracle.js' import { RedshiftDialect } from './red_shift.js' import { BetterSqliteDialect } from './better_sqlite.js' -import { - DialectContract, - QueryClientContract, - SharedConfigNode, -} from '../../adonis-typings/database.js' +import { DialectContract, QueryClientContract, SharedConfigNode } from '../types/database.js' export const dialects: { [key: string]: { diff --git a/src/dialects/mssql.ts b/src/dialects/mssql.ts index 3cbd90d2..f5588883 100644 --- a/src/dialects/mssql.ts +++ b/src/dialects/mssql.ts @@ -8,11 +8,7 @@ */ import { RawBuilder } from '../database/static_builder/raw.js' -import { - DialectContract, - SharedConfigNode, - QueryClientContract, -} from '../../adonis-typings/database.js' +import { DialectContract, SharedConfigNode, QueryClientContract } from '../types/database.js' export class MssqlDialect implements DialectContract { readonly name = 'mssql' diff --git a/src/dialects/mysql.ts b/src/dialects/mysql.ts index 0e4daf63..72738609 100644 --- a/src/dialects/mysql.ts +++ b/src/dialects/mysql.ts @@ -8,11 +8,7 @@ */ import { RawBuilder } from '../database/static_builder/raw.js' -import { - DialectContract, - SharedConfigNode, - QueryClientContract, -} from '../../adonis-typings/database.js' +import { DialectContract, SharedConfigNode, QueryClientContract } from '../types/database.js' export class MysqlDialect implements DialectContract { readonly name = 'mysql' diff --git a/src/dialects/oracle.ts b/src/dialects/oracle.ts index ee3d1213..196e42c4 100644 --- a/src/dialects/oracle.ts +++ b/src/dialects/oracle.ts @@ -7,7 +7,7 @@ * file that was distributed with this source code. */ -import { DialectContract, QueryClientContract } from '../../adonis-typings/database.js' +import { DialectContract, QueryClientContract } from '../types/database.js' export class OracleDialect implements DialectContract { readonly name = 'oracledb' diff --git a/src/dialects/pg.ts b/src/dialects/pg.ts index 4505484c..dde80f6e 100644 --- a/src/dialects/pg.ts +++ b/src/dialects/pg.ts @@ -7,11 +7,7 @@ * file that was distributed with this source code. */ -import { - DialectContract, - SharedConfigNode, - QueryClientContract, -} from '../../adonis-typings/database.js' +import { DialectContract, SharedConfigNode, QueryClientContract } from '../types/database.js' export class PgDialect implements DialectContract { readonly name = 'postgres' diff --git a/src/dialects/red_shift.ts b/src/dialects/red_shift.ts index 59c0d425..bd8ed2f2 100644 --- a/src/dialects/red_shift.ts +++ b/src/dialects/red_shift.ts @@ -7,11 +7,7 @@ * file that was distributed with this source code. */ -import { - DialectContract, - SharedConfigNode, - QueryClientContract, -} from '../../adonis-typings/database.js' +import { DialectContract, SharedConfigNode, QueryClientContract } from '../types/database.js' export class RedshiftDialect implements DialectContract { readonly name = 'redshift' diff --git a/src/dialects/sqlite.ts b/src/dialects/sqlite.ts index 367ea372..acef5031 100644 --- a/src/dialects/sqlite.ts +++ b/src/dialects/sqlite.ts @@ -7,7 +7,7 @@ * file that was distributed with this source code. */ -import { DialectContract } from '../../adonis-typings/database.js' +import { DialectContract } from '../types/database.js' import { BaseSqliteDialect } from './base_sqlite.js' export class SqliteDialect extends BaseSqliteDialect implements DialectContract { diff --git a/src/factory/factory_builder.ts b/src/factories/factory_builder.ts similarity index 98% rename from src/factory/factory_builder.ts rename to src/factories/factory_builder.ts index ec7d12d6..9a77a10c 100644 --- a/src/factory/factory_builder.ts +++ b/src/factories/factory_builder.ts @@ -7,19 +7,14 @@ * file that was distributed with this source code. */ -import { QueryClientContract } from '../../adonis-typings/database.js' -import { - LucidRow, - LucidModel, - ModelAdapterOptions, - ModelObject, -} from '../../adonis-typings/model.js' +import { QueryClientContract } from '../types/database.js' +import { LucidRow, LucidModel, ModelAdapterOptions, ModelObject } from '../types/model.js' import { FactoryModelContract, FactoryContextContract, FactoryBuilderContract, FactoryRelationContract, -} from '../../adonis-typings/factory.js' +} from '../types/factory.js' import { FactoryModel } from './factory_model.js' import { FactoryContext } from './factory_context.js' diff --git a/src/factory/factory_context.ts b/src/factories/factory_context.ts similarity index 74% rename from src/factory/factory_context.ts rename to src/factories/factory_context.ts index 42fc6412..e1cbd36f 100644 --- a/src/factory/factory_context.ts +++ b/src/factories/factory_context.ts @@ -8,8 +8,8 @@ */ import { faker } from '@faker-js/faker' -import { FactoryContextContract } from '../../adonis-typings/factory.js' -import { TransactionClientContract } from '../../adonis-typings/database.js' +import { FactoryContextContract } from '../types/factory.js' +import { TransactionClientContract } from '../types/database.js' export class FactoryContext implements FactoryContextContract { faker = faker diff --git a/src/factory/factory_model.ts b/src/factories/factory_model.ts similarity index 97% rename from src/factory/factory_model.ts rename to src/factories/factory_model.ts index 83d39bae..9d35ca7d 100644 --- a/src/factory/factory_model.ts +++ b/src/factories/factory_model.ts @@ -8,8 +8,8 @@ */ import Hooks from '@poppinss/hooks' -import { LucidModel, ModelAdapterOptions } from '../../adonis-typings/model.js' -import { ExtractModelRelations, RelationshipsContract } from '../../adonis-typings/relations.js' +import { LucidModel, ModelAdapterOptions } from '../types/model.js' +import { ExtractModelRelations, RelationshipsContract } from '../types/relations.js' import { EventsList, @@ -22,9 +22,9 @@ import { FactoryRelationContract, FactoryBuilderQueryContract, FactoryBuilderContract, -} from '../../adonis-typings/factory.js' +} from '../types/factory.js' -import { FactoryManager } from './index.js' +import { FactoryManager } from './main.js' import { HasOne } from './relations/has_one.js' import { HasMany } from './relations/has_many.js' import { FactoryBuilder } from './factory_builder.js' diff --git a/src/factory/index.ts b/src/factories/main.ts similarity index 81% rename from src/factory/index.ts rename to src/factories/main.ts index fad645a8..73eb44ee 100644 --- a/src/factory/index.ts +++ b/src/factories/main.ts @@ -7,12 +7,8 @@ * file that was distributed with this source code. */ -import { LucidModel, LucidRow } from '../../adonis-typings/model.js' -import { - DefineCallback, - FactoryModelContract, - StubIdCallback, -} from '../../adonis-typings/factory.js' +import { LucidModel, LucidRow } from '../types/model.js' +import { DefineCallback, FactoryModelContract, StubIdCallback } from '../types/factory.js' import { FactoryModel } from './factory_model.js' /** @@ -46,3 +42,6 @@ export class FactoryManager { this.stubIdCallback = callback } } + +const factory = new FactoryManager() +export default factory diff --git a/src/factory/relations/base.ts b/src/factories/relations/base.ts similarity index 92% rename from src/factory/relations/base.ts rename to src/factories/relations/base.ts index da4760c6..9f3c4429 100644 --- a/src/factory/relations/base.ts +++ b/src/factories/relations/base.ts @@ -7,14 +7,14 @@ * file that was distributed with this source code. */ -import { LucidModel, LucidRow } from '../../../adonis-typings/model.js' +import { LucidModel, LucidRow } from '../../types/model.js' import { RelationCallback, FactoryModelContract, FactoryContextContract, FactoryBuilderQueryContract, FactoryRelationContract, -} from '../../../adonis-typings/factory.js' +} from '../../types/factory.js' /** * Base relation to be extended by other factory relations diff --git a/src/factory/relations/belongs_to.ts b/src/factories/relations/belongs_to.ts similarity index 87% rename from src/factory/relations/belongs_to.ts rename to src/factories/relations/belongs_to.ts index ffdfcd49..25da1672 100644 --- a/src/factory/relations/belongs_to.ts +++ b/src/factories/relations/belongs_to.ts @@ -7,14 +7,14 @@ * file that was distributed with this source code. */ -import { LucidModel, LucidRow } from '../../../adonis-typings/model.js' -import { BelongsToRelationContract } from '../../../adonis-typings/relations.js' +import { LucidModel, LucidRow } from '../../types/model.js' +import { BelongsToRelationContract } from '../../types/relations.js' import { RelationCallback, FactoryModelContract, FactoryRelationContract, FactoryBuilderQueryContract, -} from '../../../adonis-typings/factory.js' +} from '../../types/factory.js' import { BaseRelation } from './base.js' diff --git a/src/factory/relations/has_many.ts b/src/factories/relations/has_many.ts similarity index 90% rename from src/factory/relations/has_many.ts rename to src/factories/relations/has_many.ts index e411e2e4..a47f5067 100644 --- a/src/factory/relations/has_many.ts +++ b/src/factories/relations/has_many.ts @@ -7,14 +7,14 @@ * file that was distributed with this source code. */ -import { LucidModel, LucidRow } from '../../../adonis-typings/model.js' -import { HasManyRelationContract } from '../../../adonis-typings/relations.js' +import { LucidModel, LucidRow } from '../../types/model.js' +import { HasManyRelationContract } from '../../types/relations.js' import { RelationCallback, FactoryModelContract, FactoryRelationContract, FactoryBuilderQueryContract, -} from '../../../adonis-typings/factory.js' +} from '../../types/factory.js' import { BaseRelation } from './base.js' diff --git a/src/factory/relations/has_one.ts b/src/factories/relations/has_one.ts similarity index 89% rename from src/factory/relations/has_one.ts rename to src/factories/relations/has_one.ts index 7b057d5a..26ece5d4 100644 --- a/src/factory/relations/has_one.ts +++ b/src/factories/relations/has_one.ts @@ -7,14 +7,14 @@ * file that was distributed with this source code. */ -import { LucidModel, LucidRow } from '../../../adonis-typings/model.js' -import { HasOneRelationContract } from '../../../adonis-typings/relations.js' +import { LucidModel, LucidRow } from '../../types/model.js' +import { HasOneRelationContract } from '../../types/relations.js' import { RelationCallback, FactoryModelContract, FactoryRelationContract, FactoryBuilderQueryContract, -} from '../../../adonis-typings/factory.js' +} from '../../types/factory.js' import { BaseRelation } from './base.js' diff --git a/src/factory/relations/many_to_many.ts b/src/factories/relations/many_to_many.ts similarity index 91% rename from src/factory/relations/many_to_many.ts rename to src/factories/relations/many_to_many.ts index a72e0354..75279b37 100644 --- a/src/factory/relations/many_to_many.ts +++ b/src/factories/relations/many_to_many.ts @@ -7,15 +7,15 @@ * file that was distributed with this source code. */ -import { LucidModel, LucidRow, ModelObject } from '../../../adonis-typings/model.js' -import { ManyToManyRelationContract } from '../../../adonis-typings/relations.js' +import { LucidModel, LucidRow, ModelObject } from '../../types/model.js' +import { ManyToManyRelationContract } from '../../types/relations.js' import { RelationCallback, FactoryModelContract, FactoryRelationContract, FactoryBuilderQueryContract, -} from '../../../adonis-typings/factory.js' +} from '../../types/factory.js' import { BaseRelation } from './base.js' diff --git a/src/helpers/pretty_print.ts b/src/helpers/pretty_print.ts index 7afb9540..d7c00068 100644 --- a/src/helpers/pretty_print.ts +++ b/src/helpers/pretty_print.ts @@ -12,7 +12,7 @@ import igniculus from 'igniculus' import kleur from 'kleur' import { inspect } from 'node:util' import hrTime from 'pretty-hrtime' -import { DbQueryEventNode } from '../../adonis-typings/database.js' +import { DbQueryEventNode } from '../types/database.js' const illuminate = igniculus({ comments: { fg: 'gray' }, diff --git a/src/migrator/index.ts b/src/migration/runner.ts similarity index 98% rename from src/migrator/index.ts rename to src/migration/runner.ts index 4ed4a092..8775ce53 100644 --- a/src/migrator/index.ts +++ b/src/migration/runner.ts @@ -10,12 +10,7 @@ import slash from 'slash' import { EventEmitter } from 'node:events' import { Exception } from '@poppinss/utils' - -import { - MigratorOptions, - MigratedFileNode, - MigrationListNode, -} from '../../adonis-typings/migrator.js' +import { MigratorOptions, MigratedFileNode, MigrationListNode } from '../types/migrator.js' import { FileNode, @@ -23,18 +18,18 @@ import { QueryClientContract, SharedConfigNode, TransactionClientContract, -} from '../../adonis-typings/database.js' +} from '../types/database.js' -import { MigrationSource } from './migration_source.js' -import { Database } from '../database/index.js' +import { MigrationSource } from './source.js' +import { Database } from '../database/main.js' import { Application } from '@adonisjs/core/app' -import { Schema } from '../schema/index.js' +import { Schema } from '../schema/main.js' /** * Migrator exposes the API to execute migrations using the schema files * for a given connection at a time. */ -export class Migrator extends EventEmitter { +export class MigrationRunner extends EventEmitter { private client: QueryClientContract private config: SharedConfigNode diff --git a/src/migrator/migration_source.ts b/src/migration/source.ts similarity index 95% rename from src/migrator/migration_source.ts rename to src/migration/source.ts index bf81b6f1..7e03a136 100644 --- a/src/migrator/migration_source.ts +++ b/src/migration/source.ts @@ -9,7 +9,7 @@ import type { Application } from '@adonisjs/core/app' import { sourceFiles } from '../utils/index.js' -import { SharedConfigNode, FileNode } from '../../adonis-typings/database.js' +import { SharedConfigNode, FileNode } from '../types/database.js' /** * Migration source exposes the API to read the migration files diff --git a/src/orm/adapter/index.ts b/src/orm/adapter/index.ts index 0a543659..edb4cb46 100644 --- a/src/orm/adapter/index.ts +++ b/src/orm/adapter/index.ts @@ -8,14 +8,9 @@ */ import { Exception } from '@poppinss/utils' -import { - LucidRow, - LucidModel, - AdapterContract, - ModelAdapterOptions, -} from '../../../adonis-typings/model.js' +import { LucidRow, LucidModel, AdapterContract, ModelAdapterOptions } from '../../types/model.js' import { isObject } from '../../utils/index.js' -import type { Database } from '../../database/index.js' +import type { Database } from '../../database/main.js' /** * Adapter exposes the API to make database queries and constructor diff --git a/src/orm/base_model/index.ts b/src/orm/base_model/index.ts index 29cafd01..c62a2733 100644 --- a/src/orm/base_model/index.ts +++ b/src/orm/base_model/index.ts @@ -13,7 +13,7 @@ import Hooks from '@poppinss/hooks' import lodash from '@poppinss/utils/lodash' import type { Container } from '@adonisjs/core/container' import { Exception, defineStaticProperty } from '@poppinss/utils' -import { QueryClientContract, TransactionClientContract } from '../../../adonis-typings/database.js' +import { QueryClientContract, TransactionClientContract } from '../../types/database.js' import { LucidRow, @@ -37,7 +37,7 @@ import { ModelPaginatorContract, QueryScopeCallback, QueryScope, -} from '../../../adonis-typings/model.js' +} from '../../types/model.js' import { ModelRelations, @@ -45,7 +45,7 @@ import { RelationshipsContract, ThroughRelationOptions, ManyToManyRelationOptions, -} from '../../../adonis-typings/relations.js' +} from '../../types/relations.js' import { ModelKeys } from '../model_keys/index.js' import { Preloader } from '../preloader/index.js' diff --git a/src/orm/base_model/proxy_handler.ts b/src/orm/base_model/proxy_handler.ts index eb71f671..cfdcf3f9 100644 --- a/src/orm/base_model/proxy_handler.ts +++ b/src/orm/base_model/proxy_handler.ts @@ -7,7 +7,7 @@ * file that was distributed with this source code. */ -import { LucidModel } from '../../../adonis-typings/model.js' +import { LucidModel } from '../../types/model.js' /** * A proxy trap to add support for custom getters and setters diff --git a/src/orm/decorators/date.ts b/src/orm/decorators/date.ts index 08fc6a32..b498730f 100644 --- a/src/orm/decorators/date.ts +++ b/src/orm/decorators/date.ts @@ -9,7 +9,7 @@ import { DateTime } from 'luxon' import { Exception } from '@poppinss/utils' -import { LucidRow, LucidModel, DateColumnDecorator } from '../../../adonis-typings/model.js' +import { LucidRow, LucidModel, DateColumnDecorator } from '../../types/model.js' /** * The method to prepare the date column before persisting it's diff --git a/src/orm/decorators/date_time.ts b/src/orm/decorators/date_time.ts index 2feabce4..8181cdc8 100644 --- a/src/orm/decorators/date_time.ts +++ b/src/orm/decorators/date_time.ts @@ -9,7 +9,7 @@ import { DateTime } from 'luxon' import { Exception } from '@poppinss/utils' -import { LucidRow, LucidModel, DateTimeColumnDecorator } from '../../../adonis-typings/model.js' +import { LucidRow, LucidModel, DateTimeColumnDecorator } from '../../types/model.js' /** * The method to prepare the datetime column before persisting it's diff --git a/src/orm/decorators/index.ts b/src/orm/decorators/index.ts index fb55847d..ac11b2ad 100644 --- a/src/orm/decorators/index.ts +++ b/src/orm/decorators/index.ts @@ -14,7 +14,7 @@ import { ComputedDecorator, DateColumnDecorator, DateTimeColumnDecorator, -} from '../../../adonis-typings/model.js' +} from '../../types/model.js' import { HasOneDecorator, @@ -22,7 +22,7 @@ import { BelongsToDecorator, ManyToManyDecorator, HasManyThroughDecorator, -} from '../../../adonis-typings/relations.js' +} from '../../types/relations.js' import { dateColumn } from './date.js' import { dateTimeColumn } from './date_time.js' diff --git a/src/orm/main.ts b/src/orm/main.ts new file mode 100644 index 00000000..37519609 --- /dev/null +++ b/src/orm/main.ts @@ -0,0 +1,15 @@ +/* + * @adonisjs/lucid + * + * (c) AdoniJS + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +export * from './decorators/index.js' +export * from './decorators/date.js' +export * from './decorators/date_time.js' +export { BaseModel, scope } from './base_model/index.js' +export { ModelQueryBuilder } from './query_builder/index.js' +export { SnakeCaseNamingStrategy } from './naming_strategies/snake_case.js' diff --git a/src/orm/model_keys/index.ts b/src/orm/model_keys/index.ts index 94dcb20b..ad17c382 100644 --- a/src/orm/model_keys/index.ts +++ b/src/orm/model_keys/index.ts @@ -7,7 +7,7 @@ * file that was distributed with this source code. */ -import { ModelKeysContract, ModelObject } from '../../../adonis-typings/model.js' +import { ModelKeysContract, ModelObject } from '../../types/model.js' /** * Exposes the API to collect, get and resolve model keys diff --git a/src/orm/naming_strategies/snake_case.ts b/src/orm/naming_strategies/snake_case.ts index f5536636..b8e59345 100644 --- a/src/orm/naming_strategies/snake_case.ts +++ b/src/orm/naming_strategies/snake_case.ts @@ -8,8 +8,8 @@ */ import string from '@poppinss/utils/string' -import { ModelRelations } from '../../../adonis-typings/relations.js' -import { NamingStrategyContract, LucidModel } from '../../../adonis-typings/model.js' +import { ModelRelations } from '../../types/relations.js' +import { NamingStrategyContract, LucidModel } from '../../types/model.js' /** * Uses snake case as the naming strategy for different model properties diff --git a/src/orm/paginator/index.ts b/src/orm/paginator/index.ts index e3f2e68f..6b35a3df 100644 --- a/src/orm/paginator/index.ts +++ b/src/orm/paginator/index.ts @@ -7,7 +7,7 @@ * file that was distributed with this source code. */ -import { ModelPaginatorContract, CherryPick } from '../../../adonis-typings/model.js' +import { ModelPaginatorContract, CherryPick } from '../../types/model.js' import { SimplePaginator } from '../../database/paginator/simple_paginator.js' /** diff --git a/src/orm/preloader/index.ts b/src/orm/preloader/index.ts index e386635e..2b8b9391 100644 --- a/src/orm/preloader/index.ts +++ b/src/orm/preloader/index.ts @@ -9,15 +9,15 @@ import { Exception } from '@poppinss/utils' -import { LucidRow, LucidModel, ModelObject } from '../../../adonis-typings/model.js' +import { LucidRow, LucidModel, ModelObject } from '../../types/model.js' import { PreloaderContract, RelationshipsContract, RelationQueryBuilderContract, -} from '../../../adonis-typings/relations.js' +} from '../../types/relations.js' -import { QueryClientContract } from '../../../adonis-typings/database.js' +import { QueryClientContract } from '../../types/database.js' /** * Exposes the API to define and preload relationships in reference to diff --git a/src/orm/query_builder/index.ts b/src/orm/query_builder/index.ts index 04d120ad..a8dd50b0 100644 --- a/src/orm/query_builder/index.ts +++ b/src/orm/query_builder/index.ts @@ -16,21 +16,21 @@ import { ModelObject, ModelAdapterOptions, ModelQueryBuilderContract, -} from '../../../adonis-typings/model.js' +} from '../../types/model.js' import { PreloaderContract, RelationshipsContract, RelationQueryBuilderContract, -} from '../../../adonis-typings/relations.js' +} from '../../types/relations.js' import { DialectContract, QueryClientContract, TransactionClientContract, -} from '../../../adonis-typings/database.js' +} from '../../types/database.js' -import { DBQueryCallback, Dictionary, OneOrMany } from '../../../adonis-typings/querybuilder.js' +import { DBQueryCallback, Dictionary, OneOrMany } from '../../types/querybuilder.js' import { isObject } from '../../utils/index.js' import { Preloader } from '../preloader/index.js' diff --git a/src/orm/relations/aggregates_loader/lazy_load.ts b/src/orm/relations/aggregates_loader/lazy_load.ts index 46b2b49e..b8492fba 100644 --- a/src/orm/relations/aggregates_loader/lazy_load.ts +++ b/src/orm/relations/aggregates_loader/lazy_load.ts @@ -12,7 +12,7 @@ import { LucidModel, ModelQueryBuilderContract, LazyLoadAggregatesContract, -} from '../../../../adonis-typings/model.js' +} from '../../../types/model.js' /** * An implementation for lazy loading model relationship aggregates diff --git a/src/orm/relations/base/query_builder.ts b/src/orm/relations/base/query_builder.ts index dc6fa834..f4b0e5e6 100644 --- a/src/orm/relations/base/query_builder.ts +++ b/src/orm/relations/base/query_builder.ts @@ -8,17 +8,10 @@ */ import { Knex } from 'knex' -import { DBQueryCallback } from '../../../../adonis-typings/querybuilder.js' -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { - LucidRow, - LucidModel, - ModelQueryBuilderContract, -} from '../../../../adonis-typings/model.js' -import { - RelationshipsContract, - RelationQueryBuilderContract, -} from '../../../../adonis-typings/relations.js' +import { DBQueryCallback } from '../../../types/querybuilder.js' +import { QueryClientContract } from '../../../types/database.js' +import { LucidRow, LucidModel, ModelQueryBuilderContract } from '../../../types/model.js' +import { RelationshipsContract, RelationQueryBuilderContract } from '../../../types/relations.js' import { ModelQueryBuilder } from '../../query_builder/index.js' /** diff --git a/src/orm/relations/base/sub_query_builder.ts b/src/orm/relations/base/sub_query_builder.ts index 1ba1a4b7..f5b37b6d 100644 --- a/src/orm/relations/base/sub_query_builder.ts +++ b/src/orm/relations/base/sub_query_builder.ts @@ -8,13 +8,10 @@ */ import { Knex } from 'knex' -import { DBQueryCallback } from '../../../../adonis-typings/querybuilder.js' -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { LucidModel } from '../../../../adonis-typings/model.js' -import { - RelationSubQueryBuilderContract, - RelationshipsContract, -} from '../../../../adonis-typings/relations.js' +import { DBQueryCallback } from '../../../types/querybuilder.js' +import { QueryClientContract } from '../../../types/database.js' +import { LucidModel } from '../../../types/model.js' +import { RelationSubQueryBuilderContract, RelationshipsContract } from '../../../types/relations.js' import { ModelQueryBuilder } from '../../query_builder/index.js' /** diff --git a/src/orm/relations/belongs_to/index.ts b/src/orm/relations/belongs_to/index.ts index aa259142..3bf70bf3 100644 --- a/src/orm/relations/belongs_to/index.ts +++ b/src/orm/relations/belongs_to/index.ts @@ -7,15 +7,15 @@ * file that was distributed with this source code. */ -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { OneOrMany } from '../../../../adonis-typings/querybuilder.js' +import { QueryClientContract } from '../../../types/database.js' +import { OneOrMany } from '../../../types/querybuilder.js' -import { LucidRow, LucidModel, ModelObject } from '../../../../adonis-typings/model.js' +import { LucidRow, LucidModel, ModelObject } from '../../../types/model.js' import { RelationOptions, BelongsToRelationContract, BelongsTo as ModelBelongsTo, -} from '../../../../adonis-typings/relations.js' +} from '../../../types/relations.js' import { KeysExtractor } from '../keys_extractor.js' import { BelongsToQueryClient } from './query_client.js' @@ -45,14 +45,14 @@ export class BelongsTo implements BelongsToRelationContract * @note: Available after boot is invoked */ declare localKey: string - declare localKeyColumName: string + declare localKeyColumnName: string /** * Foreign key is reference to the foreign key in the related table * @note: Available after boot is invoked */ declare foreignKey: string - declare foreignKeyColumName: string + declare foreignKeyColumnName: string /** * Reference to the onQuery hook defined by the user @@ -135,13 +135,13 @@ export class HasMany implements HasManyRelationContract * Keys on the parent model */ this.localKey = localKey.attributeName - this.localKeyColumName = localKey.columnName + this.localKeyColumnName = localKey.columnName /** * Keys on the related model */ this.foreignKey = foreignKey.attributeName - this.foreignKeyColumName = foreignKey.columnName + this.foreignKeyColumnName = foreignKey.columnName /** * Booted successfully diff --git a/src/orm/relations/has_many/query_builder.ts b/src/orm/relations/has_many/query_builder.ts index 9045c823..05afa8e1 100644 --- a/src/orm/relations/has_many/query_builder.ts +++ b/src/orm/relations/has_many/query_builder.ts @@ -8,9 +8,9 @@ */ import { Knex } from 'knex' -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { LucidRow, LucidModel } from '../../../../adonis-typings/model.js' -import { HasManyQueryBuilderContract } from '../../../../adonis-typings/relations.js' +import { QueryClientContract } from '../../../types/database.js' +import { LucidRow, LucidModel } from '../../../types/model.js' +import { HasManyQueryBuilderContract } from '../../../types/relations.js' import { HasMany } from './index.js' import { getValue, unique } from '../../../utils/index.js' @@ -139,7 +139,7 @@ export class HasManyQueryBuilder } const rowName = 'adonis_group_limit_counter' - const partitionBy = `PARTITION BY ${this.relation.foreignKeyColumName}` + const partitionBy = `PARTITION BY ${this.relation.foreignKeyColumnName}` const orderBy = `ORDER BY ${column} ${direction}` /** diff --git a/src/orm/relations/has_many/query_client.ts b/src/orm/relations/has_many/query_client.ts index a52ce9c7..3e790c27 100644 --- a/src/orm/relations/has_many/query_client.ts +++ b/src/orm/relations/has_many/query_client.ts @@ -7,15 +7,10 @@ * file that was distributed with this source code. */ -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { OneOrMany } from '../../../../adonis-typings/querybuilder.js' -import { - LucidRow, - LucidModel, - ModelObject, - ModelAssignOptions, -} from '../../../../adonis-typings/model.js' -import { HasManyClientContract } from '../../../../adonis-typings/relations.js' +import { QueryClientContract } from '../../../types/database.js' +import { OneOrMany } from '../../../types/querybuilder.js' +import { LucidRow, LucidModel, ModelObject, ModelAssignOptions } from '../../../types/model.js' +import { HasManyClientContract } from '../../../types/relations.js' import { HasMany } from './index.js' import { managedTransaction } from '../../../utils/index.js' diff --git a/src/orm/relations/has_many/sub_query_builder.ts b/src/orm/relations/has_many/sub_query_builder.ts index 0e4c6fbc..a65bedaa 100644 --- a/src/orm/relations/has_many/sub_query_builder.ts +++ b/src/orm/relations/has_many/sub_query_builder.ts @@ -8,9 +8,9 @@ */ import { Knex } from 'knex' -import { LucidModel } from '../../../../adonis-typings/model.js' -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { RelationSubQueryBuilderContract } from '../../../../adonis-typings/relations.js' +import { LucidModel } from '../../../types/model.js' +import { QueryClientContract } from '../../../types/database.js' +import { RelationSubQueryBuilderContract } from '../../../types/relations.js' import { HasMany } from './index.js' import { BaseSubQueryBuilder } from '../base/sub_query_builder.js' @@ -86,8 +86,8 @@ export class HasManySubQueryBuilder } this.wrapExisting().where( - `${localTable}.${this.relation.localKeyColumName}`, - this.client.ref(`${tablePrefix}.${this.relation.foreignKeyColumName}`) + `${localTable}.${this.relation.localKeyColumnName}`, + this.client.ref(`${tablePrefix}.${this.relation.foreignKeyColumnName}`) ) } } diff --git a/src/orm/relations/has_many_through/index.ts b/src/orm/relations/has_many_through/index.ts index b04c9026..d71510c7 100644 --- a/src/orm/relations/has_many_through/index.ts +++ b/src/orm/relations/has_many_through/index.ts @@ -7,14 +7,14 @@ * file that was distributed with this source code. */ -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { OneOrMany } from '../../../../adonis-typings/querybuilder.js' -import { LucidRow, LucidModel } from '../../../../adonis-typings/model.js' +import { QueryClientContract } from '../../../types/database.js' +import { OneOrMany } from '../../../types/querybuilder.js' +import { LucidRow, LucidModel } from '../../../types/model.js' import { ThroughRelationOptions, HasManyThroughRelationContract, HasManyThrough as ModelHasManyThrough, -} from '../../../../adonis-typings/relations.js' +} from '../../../types/relations.js' import { KeysExtractor } from '../keys_extractor.js' import { HasManyThroughClient } from './query_client.js' diff --git a/src/orm/relations/has_many_through/query_builder.ts b/src/orm/relations/has_many_through/query_builder.ts index 8f27d7c5..9b16a422 100644 --- a/src/orm/relations/has_many_through/query_builder.ts +++ b/src/orm/relations/has_many_through/query_builder.ts @@ -8,9 +8,9 @@ */ import { Knex } from 'knex' -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { LucidRow, LucidModel } from '../../../../adonis-typings/model.js' -import { HasManyThroughQueryBuilderContract } from '../../../../adonis-typings/relations.js' +import { QueryClientContract } from '../../../types/database.js' +import { LucidRow, LucidModel } from '../../../types/model.js' +import { HasManyThroughQueryBuilderContract } from '../../../types/relations.js' import { HasManyThrough } from './index.js' import { getValue, unique } from '../../../utils/index.js' diff --git a/src/orm/relations/has_many_through/query_client.ts b/src/orm/relations/has_many_through/query_client.ts index e03525db..b5b8e14d 100644 --- a/src/orm/relations/has_many_through/query_client.ts +++ b/src/orm/relations/has_many_through/query_client.ts @@ -7,10 +7,10 @@ * file that was distributed with this source code. */ -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { OneOrMany } from '../../../../adonis-typings/querybuilder.js' -import { LucidModel, LucidRow } from '../../../../adonis-typings/model.js' -import { HasManyThroughClientContract } from '../../../../adonis-typings/relations.js' +import { QueryClientContract } from '../../../types/database.js' +import { OneOrMany } from '../../../types/querybuilder.js' +import { LucidModel, LucidRow } from '../../../types/model.js' +import { HasManyThroughClientContract } from '../../../types/relations.js' import { HasManyThrough } from './index.js' import { HasManyThroughQueryBuilder } from './query_builder.js' diff --git a/src/orm/relations/has_many_through/sub_query_builder.ts b/src/orm/relations/has_many_through/sub_query_builder.ts index 69ddffc2..892ffa0c 100644 --- a/src/orm/relations/has_many_through/sub_query_builder.ts +++ b/src/orm/relations/has_many_through/sub_query_builder.ts @@ -8,9 +8,9 @@ */ import { Knex } from 'knex' -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { LucidModel } from '../../../../adonis-typings/model.js' -import { RelationSubQueryBuilderContract } from '../../../../adonis-typings/relations.js' +import { QueryClientContract } from '../../../types/database.js' +import { LucidModel } from '../../../types/model.js' +import { RelationSubQueryBuilderContract } from '../../../types/relations.js' import { HasManyThrough } from './index.js' import { BaseSubQueryBuilder } from '../base/sub_query_builder.js' diff --git a/src/orm/relations/has_one/index.ts b/src/orm/relations/has_one/index.ts index cb0ac3bf..23a37a64 100644 --- a/src/orm/relations/has_one/index.ts +++ b/src/orm/relations/has_one/index.ts @@ -7,14 +7,14 @@ * file that was distributed with this source code. */ -import { OneOrMany } from '../../../../adonis-typings/querybuilder.js' -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { LucidRow, LucidModel, ModelObject } from '../../../../adonis-typings/model.js' +import { OneOrMany } from '../../../types/querybuilder.js' +import { QueryClientContract } from '../../../types/database.js' +import { LucidRow, LucidModel, ModelObject } from '../../../types/model.js' import { RelationOptions, HasOne as ModelHasOne, HasOneRelationContract, -} from '../../../../adonis-typings/relations.js' +} from '../../../types/relations.js' import { KeysExtractor } from '../keys_extractor.js' import { HasOneQueryClient } from './query_client.js' @@ -34,14 +34,14 @@ export class HasOne implements HasOneRelationContract { * @note: Available after boot is invoked */ declare localKey: string - declare localKeyColumName: string + declare localKeyColumnName: string /** * Foreign key is reference to the foreign key in the related table * @note: Available after boot is invoked */ declare foreignKey: string - declare foreignKeyColumName: string + declare foreignKeyColumnName: string /** * Reference to the onQuery hook defined by the user @@ -111,13 +111,13 @@ export class HasOne implements HasOneRelationContract { * Keys on the parent model */ this.localKey = localKey.attributeName - this.localKeyColumName = localKey.columnName + this.localKeyColumnName = localKey.columnName /** * Keys on the related model */ this.foreignKey = foreignKey.attributeName - this.foreignKeyColumName = foreignKey.columnName + this.foreignKeyColumnName = foreignKey.columnName /** * Booted successfully diff --git a/src/orm/relations/has_one/query_builder.ts b/src/orm/relations/has_one/query_builder.ts index 0b811048..5a10bb57 100644 --- a/src/orm/relations/has_one/query_builder.ts +++ b/src/orm/relations/has_one/query_builder.ts @@ -8,8 +8,8 @@ */ import { Knex } from 'knex' -import { LucidRow } from '../../../../adonis-typings/model.js' -import { QueryClientContract } from '../../../../adonis-typings/database.js' +import { LucidRow } from '../../../types/model.js' +import { QueryClientContract } from '../../../types/database.js' import { HasOne } from './index.js' import { getValue, unique } from '../../../utils/index.js' diff --git a/src/orm/relations/has_one/query_client.ts b/src/orm/relations/has_one/query_client.ts index 6463c08c..8de26b0c 100644 --- a/src/orm/relations/has_one/query_client.ts +++ b/src/orm/relations/has_one/query_client.ts @@ -7,15 +7,10 @@ * file that was distributed with this source code. */ -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { OneOrMany } from '../../../../adonis-typings/querybuilder.js' -import { - ModelObject, - LucidModel, - LucidRow, - ModelAssignOptions, -} from '../../../../adonis-typings/model.js' -import { HasOneClientContract } from '../../../../adonis-typings/relations.js' +import { QueryClientContract } from '../../../types/database.js' +import { OneOrMany } from '../../../types/querybuilder.js' +import { ModelObject, LucidModel, LucidRow, ModelAssignOptions } from '../../../types/model.js' +import { HasOneClientContract } from '../../../types/relations.js' import { HasOne } from './index.js' import { managedTransaction } from '../../../utils/index.js' diff --git a/src/orm/relations/has_one/sub_query_builder.ts b/src/orm/relations/has_one/sub_query_builder.ts index 2bad0d69..a1f544cc 100644 --- a/src/orm/relations/has_one/sub_query_builder.ts +++ b/src/orm/relations/has_one/sub_query_builder.ts @@ -8,9 +8,9 @@ */ import { Knex } from 'knex' -import { LucidModel } from '../../../../adonis-typings/model.js' -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { RelationSubQueryBuilderContract } from '../../../../adonis-typings/relations.js' +import { LucidModel } from '../../../types/model.js' +import { QueryClientContract } from '../../../types/database.js' +import { RelationSubQueryBuilderContract } from '../../../types/relations.js' import { HasOne } from './index.js' import { BaseSubQueryBuilder } from '../base/sub_query_builder.js' @@ -85,8 +85,8 @@ export class HasOneSubQueryBuilder } this.wrapExisting().where( - `${localTable}.${this.relation.localKeyColumName}`, - this.client.ref(`${tablePrefix}.${this.relation.foreignKeyColumName}`) + `${localTable}.${this.relation.localKeyColumnName}`, + this.client.ref(`${tablePrefix}.${this.relation.foreignKeyColumnName}`) ) } } diff --git a/src/orm/relations/keys_extractor.ts b/src/orm/relations/keys_extractor.ts index 6b1e5983..dd7c8203 100644 --- a/src/orm/relations/keys_extractor.ts +++ b/src/orm/relations/keys_extractor.ts @@ -8,7 +8,7 @@ */ import { Exception } from '@poppinss/utils' -import { LucidModel } from '../../../adonis-typings/model.js' +import { LucidModel } from '../../types/model.js' /** * Utility to consistently extract relationship keys from the model diff --git a/src/orm/relations/many_to_many/index.ts b/src/orm/relations/many_to_many/index.ts index 56462c07..d1481f12 100644 --- a/src/orm/relations/many_to_many/index.ts +++ b/src/orm/relations/many_to_many/index.ts @@ -7,13 +7,13 @@ * file that was distributed with this source code. */ -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { LucidRow, LucidModel } from '../../../../adonis-typings/model.js' +import { QueryClientContract } from '../../../types/database.js' +import { LucidRow, LucidModel } from '../../../types/model.js' import { ManyToManyRelationOptions, ManyToManyRelationContract, ManyToMany as ModelManyToMany, -} from '../../../../adonis-typings/relations.js' +} from '../../../types/relations.js' import { KeysExtractor } from '../keys_extractor.js' import { ManyToManyQueryClient } from './query_client.js' diff --git a/src/orm/relations/many_to_many/query_builder.ts b/src/orm/relations/many_to_many/query_builder.ts index eed15152..dc05d1dc 100644 --- a/src/orm/relations/many_to_many/query_builder.ts +++ b/src/orm/relations/many_to_many/query_builder.ts @@ -9,9 +9,9 @@ import { Knex } from 'knex' import { DateTime } from 'luxon' -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { LucidModel, LucidRow } from '../../../../adonis-typings/model.js' -import { ManyToManyQueryBuilderContract } from '../../../../adonis-typings/relations.js' +import { QueryClientContract } from '../../../types/database.js' +import { LucidModel, LucidRow } from '../../../types/model.js' +import { ManyToManyQueryBuilderContract } from '../../../types/relations.js' import { ManyToMany } from './index.js' import { PivotHelpers } from './pivot_helpers.js' diff --git a/src/orm/relations/many_to_many/query_client.ts b/src/orm/relations/many_to_many/query_client.ts index bd9c6794..de214b3a 100644 --- a/src/orm/relations/many_to_many/query_client.ts +++ b/src/orm/relations/many_to_many/query_client.ts @@ -8,18 +8,10 @@ */ import { DateTime } from 'luxon' -import { - LucidModel, - LucidRow, - ModelObject, - ModelAssignOptions, -} from '../../../../adonis-typings/model.js' -import { ManyToManyClientContract } from '../../../../adonis-typings/relations.js' -import { - QueryClientContract, - TransactionClientContract, -} from '../../../../adonis-typings/database.js' -import { OneOrMany } from '../../../../adonis-typings/querybuilder.js' +import { LucidModel, LucidRow, ModelObject, ModelAssignOptions } from '../../../types/model.js' +import { ManyToManyClientContract } from '../../../types/relations.js' +import { QueryClientContract, TransactionClientContract } from '../../../types/database.js' +import { OneOrMany } from '../../../types/querybuilder.js' import { ManyToMany } from './index.js' import { ManyToManyQueryBuilder } from './query_builder.js' diff --git a/src/orm/relations/many_to_many/sub_query_builder.ts b/src/orm/relations/many_to_many/sub_query_builder.ts index 49f71188..62b8811f 100644 --- a/src/orm/relations/many_to_many/sub_query_builder.ts +++ b/src/orm/relations/many_to_many/sub_query_builder.ts @@ -8,9 +8,9 @@ */ import { Knex } from 'knex' -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { LucidModel } from '../../../../adonis-typings/model.js' -import { ManyToManySubQueryBuilderContract } from '../../../../adonis-typings/relations.js' +import { QueryClientContract } from '../../../types/database.js' +import { LucidModel } from '../../../types/model.js' +import { ManyToManySubQueryBuilderContract } from '../../../types/relations.js' import { ManyToMany } from './index.js' import { PivotHelpers } from './pivot_helpers.js' diff --git a/src/query_client/index.ts b/src/query_client/index.ts index be5eca17..1473f7a9 100644 --- a/src/query_client/index.ts +++ b/src/query_client/index.ts @@ -17,7 +17,7 @@ import { ConnectionContract, QueryClientContract, TransactionClientContract, -} from '../../adonis-typings/database.js' +} from '../types/database.js' import { dialects } from '../dialects/index.js' import { TransactionClient } from '../transaction_client/index.js' @@ -26,11 +26,18 @@ import { RawQueryBuilder } from '../database/query_builder/raw.js' import { InsertQueryBuilder } from '../database/query_builder/insert.js' import { ReferenceBuilder } from '../database/static_builder/reference.js' import { DatabaseQueryBuilder } from '../database/query_builder/database.js' -import { LucidModel, ModelQueryBuilderContract } from '../../adonis-typings/model.js' +import { LucidModel, ModelQueryBuilderContract } from '../types/model.js' import { RawQueryBindings, DatabaseQueryBuilderContract, -} from '../../adonis-typings/querybuilder.js' + InsertQueryBuilderContract, + RawQueryBuilderContract, + RawBuilderContract, + ReferenceBuilderContract, + ChainableContract, + Dictionary, + QueryCallback, +} from '../types/querybuilder.js' import { ModelQueryBuilder } from '../orm/query_builder/index.js' /** @@ -178,12 +185,17 @@ export class QueryClient implements QueryClientContract { * Returns an instance of a transaction. Each transaction will * query and hold a single connection for all queries. */ - async transaction( + transaction( + callback: (trx: TransactionClientContract) => Promise, + options?: { isolationLevel?: IsolationLevels } + ): Promise + transaction(options?: { isolationLevel?: IsolationLevels }): Promise + async transaction( callback?: | { isolationLevel?: IsolationLevels } | ((trx: TransactionClientContract) => Promise), options?: { isolationLevel?: IsolationLevels } - ): Promise { + ): Promise { const trx = await this.getWriteClient().transaction(options) const transaction = new TransactionClient( trx, @@ -250,15 +262,21 @@ export class QueryClient implements QueryClientContract { /** * Returns instance of a query builder for inserting rows */ - insertQuery(): any { + insertQuery(): InsertQueryBuilderContract { return new InsertQueryBuilder(this.getWriteClient().queryBuilder(), this) } /** * Returns instance of raw query builder */ - rawQuery(sql: any, bindings?: any): any { - return new RawQueryBuilder(this.connection.client!.raw(sql, bindings), this) + rawQuery( + sql: string, + bindings?: RawQueryBindings | undefined + ): RawQueryBuilderContract { + return new RawQueryBuilder( + bindings ? this.connection.client!.raw(sql, bindings) : this.connection.client!.raw(sql), + this + ) } /** @@ -266,21 +284,27 @@ export class QueryClient implements QueryClientContract { * cannot be executed. Use `rawQuery`, if you want to execute * queries raw queries. */ - raw(sql: string, bindings?: any) { + raw(sql: string, bindings?: RawQueryBindings | undefined): RawBuilderContract { return new RawBuilder(sql, bindings) } /** * Returns reference builder. */ - ref(reference: string) { + ref(reference: string): ReferenceBuilderContract { return new ReferenceBuilder(reference, this.getReadClient().client) } /** * Returns instance of a query builder and selects the table */ - from(table: any): any { + from( + table: + | string + | Dictionary + | QueryCallback + | ChainableContract + ): DatabaseQueryBuilderContract { return this.query().from(table) } @@ -288,21 +312,21 @@ export class QueryClient implements QueryClientContract { * Returns instance of a query builder and selects the table * for an insert query */ - table(table: any): any { + table(table: string): InsertQueryBuilderContract { return this.insertQuery().table(table) } /** * Get advisory lock on the selected connection */ - getAdvisoryLock(key: string, timeout?: number): any { + getAdvisoryLock(key: string | number, timeout?: number | undefined): Promise { return this.dialect.getAdvisoryLock(key, timeout) } /** * Release advisory lock */ - releaseAdvisoryLock(key: string): any { + releaseAdvisoryLock(key: string | number): Promise { return this.dialect.releaseAdvisoryLock(key) } } diff --git a/src/query_reporter/index.ts b/src/query_reporter/index.ts index 691236bb..658fe184 100644 --- a/src/query_reporter/index.ts +++ b/src/query_reporter/index.ts @@ -7,7 +7,7 @@ * file that was distributed with this source code. */ -import { QueryClientContract, TransactionClientContract } from '../../adonis-typings/database.js' +import { QueryClientContract, TransactionClientContract } from '../types/database.js' /** * Used for reporting queries using the profiler and the event diff --git a/src/query_runner/index.ts b/src/query_runner/index.ts index c771ebf1..8b96e550 100644 --- a/src/query_runner/index.ts +++ b/src/query_runner/index.ts @@ -10,7 +10,7 @@ import { Knex } from 'knex' import { Exception } from '@poppinss/utils' import { QueryReporter } from '../query_reporter/index.js' -import { QueryClientContract, TransactionClientContract } from '../../adonis-typings/database.js' +import { QueryClientContract, TransactionClientContract } from '../types/database.js' /** * Query runner exposes the API for executing knex query builder by using the diff --git a/src/schema/index.ts b/src/schema/main.ts similarity index 94% rename from src/schema/index.ts rename to src/schema/main.ts index caf94a7f..23632114 100644 --- a/src/schema/index.ts +++ b/src/schema/main.ts @@ -7,13 +7,13 @@ * file that was distributed with this source code. */ -import { Knex } from 'knex' +import type { Knex } from 'knex' import { Exception } from '@poppinss/utils' import { getDDLMethod } from '../utils/index.js' import { QueryReporter } from '../query_reporter/index.js' -import { DeferCallback } from '../../adonis-typings/schema.js' -import { QueryClientContract } from '../../adonis-typings/database.js' -import { RawQueryBindings } from '../../adonis-typings/querybuilder.js' +import type { DeferCallback } from '../types/schema.js' +import type { QueryClientContract } from '../types/database.js' +import type { RawQueryBindings } from '../types/querybuilder.js' /** * Exposes the API to define table schema using deferred database diff --git a/src/base_seeder/index.ts b/src/seeders/base_seeder.ts similarity index 82% rename from src/base_seeder/index.ts rename to src/seeders/base_seeder.ts index 52b1cab9..8bbf297c 100644 --- a/src/base_seeder/index.ts +++ b/src/seeders/base_seeder.ts @@ -7,7 +7,7 @@ * file that was distributed with this source code. */ -import { QueryClientContract } from '../../adonis-typings/database.js' +import { QueryClientContract } from '../types/database.js' export class BaseSeeder { static environment: string[] diff --git a/src/seeders/main.ts b/src/seeders/main.ts new file mode 100644 index 00000000..3ee51065 --- /dev/null +++ b/src/seeders/main.ts @@ -0,0 +1,10 @@ +/* + * @adonisjs/lucid + * + * (c) AdonisJS + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +export { BaseSeeder } from './base_seeder.js' diff --git a/src/seeders_runner/index.ts b/src/seeders/runner.ts similarity index 91% rename from src/seeders_runner/index.ts rename to src/seeders/runner.ts index 95a429a6..d7c100a1 100644 --- a/src/seeders_runner/index.ts +++ b/src/seeders/runner.ts @@ -8,11 +8,11 @@ */ import { Application } from '@adonisjs/core/app' -import { FileNode, QueryClientContract, SharedConfigNode } from '../../adonis-typings/database.js' -import { SeederConstructorContract, SeederFileNode } from '../../adonis-typings/seeder.js' +import { FileNode, QueryClientContract, SharedConfigNode } from '../types/database.js' +import { SeederConstructorContract, SeederFileNode } from '../types/seeder.js' -import { SeedersSource } from './seeders_source.js' -import { Database } from '../database/index.js' +import { SeedersSource } from './source.js' +import { Database } from '../database/main.js' /** * Seeds Runner exposes the API to traverse seeders and execute them diff --git a/src/seeders_runner/seeders_source.ts b/src/seeders/source.ts similarity index 95% rename from src/seeders_runner/seeders_source.ts rename to src/seeders/source.ts index be2c0c05..9d1d33d2 100644 --- a/src/seeders_runner/seeders_source.ts +++ b/src/seeders/source.ts @@ -9,7 +9,7 @@ import { Application } from '@adonisjs/core/app' -import { FileNode, SharedConfigNode } from '../../adonis-typings/database.js' +import { FileNode, SharedConfigNode } from '../types/database.js' import { sourceFiles } from '../utils/index.js' /** diff --git a/src/transaction_client/index.ts b/src/transaction_client/index.ts index 837804e2..81ae6965 100644 --- a/src/transaction_client/index.ts +++ b/src/transaction_client/index.ts @@ -11,11 +11,7 @@ import { Knex } from 'knex' import Hooks from '@poppinss/hooks' import { EventEmitter } from 'node:events' import type { Emitter } from '@adonisjs/core/events' -import { - IsolationLevels, - DialectContract, - TransactionClientContract, -} from '../../adonis-typings/database.js' +import { IsolationLevels, DialectContract, TransactionClientContract } from '../types/database.js' import { ModelQueryBuilder } from '../orm/query_builder/index.js' import { RawBuilder } from '../database/static_builder/raw.js' @@ -23,7 +19,7 @@ import { RawQueryBuilder } from '../database/query_builder/raw.js' import { InsertQueryBuilder } from '../database/query_builder/insert.js' import { ReferenceBuilder } from '../database/static_builder/reference.js' import { DatabaseQueryBuilder } from '../database/query_builder/database.js' -import { LucidModel, ModelQueryBuilderContract } from '../../adonis-typings/model.js' +import { LucidModel, ModelQueryBuilderContract } from '../types/model.js' /** * Transaction uses a dedicated connection from the connection pool diff --git a/adonis-typings/database.ts b/src/types/database.ts similarity index 100% rename from adonis-typings/database.ts rename to src/types/database.ts diff --git a/adonis-typings/events.ts b/src/types/events.ts similarity index 100% rename from adonis-typings/events.ts rename to src/types/events.ts diff --git a/adonis-typings/factory.ts b/src/types/factory.ts similarity index 100% rename from adonis-typings/factory.ts rename to src/types/factory.ts diff --git a/adonis-typings/migrator.ts b/src/types/migrator.ts similarity index 100% rename from adonis-typings/migrator.ts rename to src/types/migrator.ts diff --git a/adonis-typings/model.ts b/src/types/model.ts similarity index 100% rename from adonis-typings/model.ts rename to src/types/model.ts diff --git a/adonis-typings/querybuilder.ts b/src/types/querybuilder.ts similarity index 100% rename from adonis-typings/querybuilder.ts rename to src/types/querybuilder.ts diff --git a/adonis-typings/relations.ts b/src/types/relations.ts similarity index 99% rename from adonis-typings/relations.ts rename to src/types/relations.ts index cd73937c..49f2ebcb 100644 --- a/adonis-typings/relations.ts +++ b/src/types/relations.ts @@ -282,11 +282,6 @@ export interface BaseRelationContract< readonly booted: boolean readonly model: ParentModel - foreignKey: string - foreignKeyColumnName: string - localKey: string - localKeyColumnName: string - relatedModel(): RelatedModel boot(): void clone(parent: LucidModel): this @@ -317,6 +312,8 @@ export interface HasOneRelationContract< readonly type: 'hasOne' readonly localKey: string readonly foreignKey: string + foreignKeyColumnName: string + localKeyColumnName: string /** * Set related model as a relationship on the parent model. @@ -365,6 +362,8 @@ export interface HasManyRelationContract< readonly type: 'hasMany' readonly localKey: string readonly foreignKey: string + foreignKeyColumnName: string + localKeyColumnName: string /** * Set related models as a relationship on the parent model @@ -416,6 +415,8 @@ export interface BelongsToRelationContract< readonly type: 'belongsTo' readonly localKey: string readonly foreignKey: string + foreignKeyColumnName: string + localKeyColumnName: string /** * Set related model as a relationship on the parent model @@ -538,6 +539,8 @@ export interface HasManyThroughRelationContract< readonly throughForeignKey: string throughLocalKeyColumnName: string throughForeignKeyColumnName: string + foreignKeyColumnName: string + localKeyColumnName: string /** * Set related models as a relationship on the parent model diff --git a/adonis-typings/schema.ts b/src/types/schema.ts similarity index 100% rename from adonis-typings/schema.ts rename to src/types/schema.ts diff --git a/adonis-typings/seeder.ts b/src/types/seeder.ts similarity index 100% rename from adonis-typings/seeder.ts rename to src/types/seeder.ts diff --git a/src/utils/index.ts b/src/utils/index.ts index bda238eb..0aad5a02 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -10,13 +10,9 @@ import slash from 'slash' import { join, extname } from 'node:path' import { Exception, fsReadAll, isScriptFile } from '@poppinss/utils' -import { RelationshipsContract } from '../../adonis-typings/relations.js' -import { LucidRow, ModelObject, CherryPickFields } from '../../adonis-typings/model.js' -import { - FileNode, - QueryClientContract, - TransactionClientContract, -} from '../../adonis-typings/database.js' +import { RelationshipsContract } from '../types/relations.js' +import { LucidRow, ModelObject, CherryPickFields } from '../types/model.js' +import { FileNode, QueryClientContract, TransactionClientContract } from '../types/database.js' import { fileURLToPath, pathToFileURL } from 'node:url' /** diff --git a/templates/database.txt b/stubs/database.txt similarity index 100% rename from templates/database.txt rename to stubs/database.txt diff --git a/stubs/factories/index.txt b/stubs/factories/index.txt new file mode 100644 index 00000000..25f391a2 --- /dev/null +++ b/stubs/factories/index.txt @@ -0,0 +1 @@ +import factory from '@adonisjs/lucid/factories' diff --git a/stubs/main.ts b/stubs/main.ts new file mode 100644 index 00000000..17bd1342 --- /dev/null +++ b/stubs/main.ts @@ -0,0 +1,12 @@ +/* + * @adonisjs/lucid + * + * (c) AdonisJS + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import { getDirname } from '@poppinss/utils' + +export const stubsRoot = getDirname(import.meta.url) diff --git a/stubs/make/factory/main.stub b/stubs/make/factory/main.stub new file mode 100644 index 00000000..fe2522b8 --- /dev/null +++ b/stubs/make/factory/main.stub @@ -0,0 +1,16 @@ +{{#var factoryName = generators.factoryName(entity.name)}} +{{#var factoryFileName = generators.factoryFileName(entity.name)}} +{{#var modelName = generators.modelName(model.name)}} +{{#var modelFileName = generators.modelFileName(model.name)}} +{{#var modelImportPath = generators.importPath('#models', model.path, modelFileName.replace(/\.ts$/, ''))}} +--- +to: {{ app.factoriesPath(entity.path, factoryFileName) }} +--- +import factory from '@adonisjs/lucid/factories' +import {{ modelName }} from '{{ modelImportPath }}' + +export const {{ factoryName }} = factory + .define({{ modelName }}, ({ faker }) => { + return {} + }) + .build() diff --git a/stubs/make/migration/alter.stub b/stubs/make/migration/alter.stub new file mode 100644 index 00000000..34120a3b --- /dev/null +++ b/stubs/make/migration/alter.stub @@ -0,0 +1,17 @@ +--- +to: {{ app.makePath(migration.folder, entity.path, migration.fileName) }} +--- +import { BaseSchema } from '@adonisjs/lucid/schema' + +export default class extends BaseSchema { + protected tableName = '{{ migration.tableName }}' + + async up () { + this.schema.alterTable(this.tableName, (table) => { + }) + } + + async down () { + this.schema.alterTable(this.tableName) + } +} diff --git a/templates/migration-make.txt b/stubs/make/migration/create.stub similarity index 63% rename from templates/migration-make.txt rename to stubs/make/migration/create.stub index 29b468d8..b57f2390 100644 --- a/templates/migration-make.txt +++ b/stubs/make/migration/create.stub @@ -1,9 +1,12 @@ -import BaseSchema from '@ioc:Adonis/Lucid/Schema' +--- +to: {{ app.makePath(migration.folder, entity.path, migration.fileName) }} +--- +import { BaseSchema } from '@adonisjs/lucid/schema' export default class extends BaseSchema { - protected tableName = '{{#toTableName}}{{ filename }}{{/toTableName}}' + protected tableName = '{{ migration.tableName }}' - public async up () { + async up () { this.schema.createTable(this.tableName, (table) => { table.increments('id') @@ -15,7 +18,7 @@ export default class extends BaseSchema { }) } - public async down () { + async down () { this.schema.dropTable(this.tableName) } } diff --git a/stubs/make/model/main.stub b/stubs/make/model/main.stub new file mode 100644 index 00000000..b994560d --- /dev/null +++ b/stubs/make/model/main.stub @@ -0,0 +1,18 @@ +{{#var modelName = generators.modelName(entity.name)}} +{{#var modelFileName = generators.modelFileName(entity.name)}} +--- +to: {{ app.modelsPath(entity.path, modelFileName) }} +--- +import { DateTime } from 'luxon' +import { BaseModel, column } from '@adonisjs/lucid/orm' + +export default class {{ modelName }} extends BaseModel { + @column({ isPrimary: true }) + declare id: number + + @column.dateTime({ autoCreate: true }) + declare createdAt: DateTime + + @column.dateTime({ autoCreate: true, autoUpdate: true }) + declare updatedAt: DateTime +} diff --git a/stubs/make/seeder/main.stub b/stubs/make/seeder/main.stub new file mode 100644 index 00000000..1be66bba --- /dev/null +++ b/stubs/make/seeder/main.stub @@ -0,0 +1,11 @@ +{{#var seederFileName = generators.seederFileName(entity.name)}} +--- +to: {{ app.seedersPath(entity.path, seederFileName) }} +--- +import { BaseSeeder } from '@adonisjs/lucid/seeders' + +export default class extends BaseSeeder { + async run () { + // Write your database queries inside the run method + } +} diff --git a/templates/seeder.txt b/stubs/seeder.txt similarity index 100% rename from templates/seeder.txt rename to stubs/seeder.txt diff --git a/templates/factories/index.txt b/templates/factories/index.txt deleted file mode 100644 index de08b6b6..00000000 --- a/templates/factories/index.txt +++ /dev/null @@ -1 +0,0 @@ -// import Factory from '@ioc:Adonis/Lucid/Factory' diff --git a/templates/factory.txt b/templates/factory.txt deleted file mode 100644 index a17e7630..00000000 --- a/templates/factory.txt +++ /dev/null @@ -1,8 +0,0 @@ -import {{#toModelName}}{{{ model }}}{{/toModelName}} from '{{{ modelImportPath }}}' -import Factory from '@ioc:Adonis/Lucid/Factory' - -export default Factory.define({{#toModelName}}{{{ model }}}{{/toModelName}}, ({ faker }) => { - return { - // - } -}).build() diff --git a/templates/migration-alter.txt b/templates/migration-alter.txt deleted file mode 100644 index acf62567..00000000 --- a/templates/migration-alter.txt +++ /dev/null @@ -1,15 +0,0 @@ -import BaseSchema from '@ioc:Adonis/Lucid/Schema' - -export default class extends BaseSchema { - protected tableName = '{{#toTableName}}{{ filename }}{{/toTableName}}' - - public async up () { - this.schema.alterTable(this.tableName, (table) => { - }) - } - - public async down () { - this.schema.alterTable(this.tableName, (table) => { - }) - } -} diff --git a/templates/model.txt b/templates/model.txt deleted file mode 100644 index d74542ea..00000000 --- a/templates/model.txt +++ /dev/null @@ -1,13 +0,0 @@ -import { DateTime } from 'luxon' -import { BaseModel, column } from '@ioc:Adonis/Lucid/Orm' - -export default class {{ filename }} extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @column.dateTime({ autoCreate: true }) - public createdAt: DateTime - - @column.dateTime({ autoCreate: true, autoUpdate: true }) - public updatedAt: DateTime -} diff --git a/test-helpers/index.ts b/test-helpers/index.ts index 7e492e7d..a1406e15 100644 --- a/test-helpers/index.ts +++ b/test-helpers/index.ts @@ -16,32 +16,26 @@ import { Logger } from '@adonisjs/core/logger' import { Emitter } from '@adonisjs/core/events' import { AppFactory } from '@adonisjs/core/factories/app' -import { - ConnectionConfig, - ConnectionContract, - QueryClientContract, -} from '../adonis-typings/database.js' +import { ConnectionConfig, ConnectionContract, DatabaseConfig, QueryClientContract } from '../src/types/database.js' import { RawQueryBuilderContract, InsertQueryBuilderContract, DatabaseQueryBuilderContract, -} from '../adonis-typings/querybuilder.js' +} from '../src/types/querybuilder.js' -import { MigratorOptions } from '../adonis-typings/migrator.js' -import { LucidRow, LucidModel, AdapterContract } from '../adonis-typings/model.js' +import { MigratorOptions } from '../src/types/migrator.js' +import { LucidRow, LucidModel, AdapterContract } from '../src/types/model.js' import { fileURLToPath } from 'node:url' -// import { QueryClient } from '../src/QueryClient/index.js' -import { DefineCallback, FactoryModelContract } from '../adonis-typings/factory.js' import { QueryClient } from '../src/query_client/index.js' -import { Database } from '../src/database/index.js' +import { Database } from '../src/database/main.js' import { DatabaseQueryBuilder } from '../src/database/query_builder/database.js' import { RawQueryBuilder } from '../src/database/query_builder/raw.js' import { InsertQueryBuilder } from '../src/database/query_builder/insert.js' -import { Migrator } from '../src/migrator/index.js' +import { MigrationRunner } from '../src/migration/runner.js' import { Application } from '@adonisjs/core/app' -import { Schema } from '../src/schema/index.js' +import { Schema } from '../src/schema/main.js' import { BaseModel } from '../src/orm/base_model/index.js' import { Adapter } from '../src/orm/adapter/index.js' @@ -405,8 +399,8 @@ export function getInsertBuilder(client: QueryClientContract) { /** * Returns the database instance */ -export function getDb(eventEmitter?: Emitter) { - const config = { +export function getDb(eventEmitter?: Emitter, config?: DatabaseConfig) { + const defaultConfig = { connection: 'primary', connections: { primary: getConfig(), @@ -414,7 +408,7 @@ export function getDb(eventEmitter?: Emitter) { }, } - const db = new Database(config, logger, eventEmitter || createEmitter()) + const db = new Database(config || defaultConfig, logger, eventEmitter || createEmitter()) const test = getActiveTest() test?.cleanup(() => { return db.manager.closeAll() @@ -538,7 +532,7 @@ export class FakeAdapter implements AdapterContract { export function mapToObj(collection: Map): T { let obj = {} as T collection.forEach((value, key) => { - obj[key] = value + ;(obj as any)[key] = value }) return obj } @@ -554,7 +548,7 @@ export function getBaseSchema() { * Returns instance of migrator */ export function getMigrator(db: Database, application: Application, config: MigratorOptions) { - return new Migrator(db, application, config) + return new MigrationRunner(db, application, config) } /** @@ -590,58 +584,6 @@ export function getPosts(count: number, userId: number) { }) } -/** - * Setup application - */ -export async function setupApplication( - dbConfig?: any, - additionalProviders?: string[], - environment: 'web' | 'repl' | 'test' = 'test' -) { - await fs.add('.env', '') - await fs.add( - 'config/app.ts', - ` - export const appKey = 'averylong32charsrandomsecretkey', - export const http = { - cookie: {}, - trustProxy: () => true, - } - ` - ) - - await fs.add( - 'config/database.ts', - ` - const dbConfig = ${JSON.stringify(dbConfig, null, 2)} - export default dbConfig - ` - ) - - const app = new Application(fs.basePath, environment, { - aliases: { - App: './app', - }, - providers: ['@adonisjs/core', '@adonisjs/repl'].concat(additionalProviders || []), - }) - - await app.setup() - await app.registerProviders() - await app.bootProviders() - - if (process.env.DEBUG) { - app.container.use('Adonis/Core/Event').on('db:query', (query) => { - console.log({ - model: query.model, - sql: query.sql, - bindings: query.bindings, - }) - }) - } - - return app -} - export async function setupReplicaDb(connection: Knex, datatoInsert: { username: string }[]) { const hasUsersTable = await connection.schema.hasTable('replica_users') if (!hasUsersTable) { diff --git a/test/bindings/validator.spec.ts b/test/bindings/validator.spec.ts index e5365500..154cc5ca 100644 --- a/test/bindings/validator.spec.ts +++ b/test/bindings/validator.spec.ts @@ -7,7 +7,7 @@ * file that was distributed with this source code. */ -/// +/// import { test } from '@japa/runner' import { rules } from '@adonisjs/validator/build/src/Rules' diff --git a/test/commands/db-wipe.spec.ts b/test/commands/db-wipe.spec.ts deleted file mode 100644 index 51769055..00000000 --- a/test/commands/db-wipe.spec.ts +++ /dev/null @@ -1,68 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -/// - -import 'reflect-metadata' -import { test } from '@japa/runner' -import Migrate from '../../commands/Migration/Run' -import { Kernel } from '@adonisjs/core/build/standalone' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -import DbWipe from '../../commands/DbWipe' -import { Migrator } from '../../src/Migrator' -import { fs, setup, cleanup, getDb, setupApplication } from '../../test-helpers' - -let app: ApplicationContract -let db: ReturnType - -test.group('db:wipe and migrate:fresh', (group) => { - group.each.setup(async () => { - app = await setupApplication() - return () => fs.cleanup() - }) - - group.each.setup(async () => { - db = getDb(app) - app.container.bind('Adonis/Lucid/Database', () => db) - app.container.bind('Adonis/Lucid/Migrator', () => Migrator) - await setup() - - return async () => { - await cleanup() - await cleanup(['adonis_schema', 'adonis_schema_versions', 'schema_users']) - await db.manager.closeAll() - } - }) - - test('db:wipe should drop all tables', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', - ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { - public async up () { - this.schema.createTable('schema_users', (table) => { - table.increments() - }) - } - } - ` - ) - - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate, DbWipe]) - - await kernel.exec('migration:run', []) - assert.isAbove((await db.connection().getAllTables(['public'])).length, 0) - - await kernel.exec('db:wipe', []) - assert.lengthOf(await db.connection().getAllTables(['public']), 0) - }) -}) diff --git a/test/commands/db-seed.spec.ts b/test/commands/db_seed.spec.ts similarity index 50% rename from test/commands/db-seed.spec.ts rename to test/commands/db_seed.spec.ts index 3f591fa5..eb5db1d3 100644 --- a/test/commands/db-seed.spec.ts +++ b/test/commands/db_seed.spec.ts @@ -7,57 +7,50 @@ * file that was distributed with this source code. */ -/// - import 'reflect-metadata' import { test } from '@japa/runner' -import { Kernel } from '@adonisjs/core/build/standalone' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -import DbSeed from '../../commands/DbSeed' -import { fs, setup, cleanup, getDb, setupApplication } from '../../test-helpers' +import { AceFactory } from '@adonisjs/core/factories' -let app: ApplicationContract -let db: ReturnType +import DbSeed from '../../commands/db_seed.js' +import { setup, cleanup, getDb } from '../../test-helpers/index.js' test.group('DbSeed', (group) => { group.each.setup(async () => { - app = await setupApplication() - return () => fs.cleanup() - }) - - group.each.setup(async () => { - db = getDb(app) - app.container.bind('Adonis/Lucid/Database', () => db) await setup() return async () => { await cleanup() await cleanup(['adonis_schema', 'adonis_schema_versions', 'schema_users', 'schema_accounts']) - await db.manager.closeAll(true) } }) - test('run seeders', async ({ assert }) => { - await fs.add( + test('run seeders', async ({ fs, assert }) => { + await fs.create( 'database/seeders/user.ts', `export default class UserSeeder { - public async run () { + async run () { process.env.EXEC_USER_SEEDER = 'true' } }` ) - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([DbSeed]) - await kernel.exec('db:seed', []) + const ace = await new AceFactory().make(fs.baseUrl, { + importer: () => {}, + }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => getDb()) + ace.ui.switchMode('raw') + + const command = await ace.create(DbSeed, []) + await command.exec() + command.assertLog('green(❯) green(completed) database/seeders/user') assert.equal(process.env.EXEC_USER_SEEDER, 'true') delete process.env.EXEC_USER_SEEDER }) - test('cherry pick files', async ({ assert }) => { - await fs.add( + test('cherry pick files using the --files flag', async ({ fs, assert }) => { + await fs.create( 'database/seeders/user.ts', `export default class UserSeeder { public async run () { @@ -66,7 +59,7 @@ test.group('DbSeed', (group) => { }` ) - await fs.add( + await fs.create( 'database/seeders/post.ts', `export default class PostSeeder { public async run () { @@ -75,31 +68,44 @@ test.group('DbSeed', (group) => { }` ) - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([DbSeed]) - await kernel.exec('db:seed', ['--files', './database/seeders/post.ts']) + const ace = await new AceFactory().make(fs.baseUrl, { + importer: () => {}, + }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => getDb()) + ace.ui.switchMode('raw') + + const command = await ace.create(DbSeed, ['--files', './database/seeders/post.ts']) + await command.exec() + + assert.deepEqual(command.logger.getLogs(), [ + { + message: 'green(❯) green(completed) database/seeders/post', + stream: 'stdout', + }, + ]) assert.isUndefined(process.env.EXEC_USER_SEEDER) assert.equal(process.env.EXEC_POST_SEEDER, 'true') delete process.env.EXEC_POST_SEEDER }) - test('run seeders with compact output', async ({ assert }) => { - await fs.add( + test('run seeders with compact output', async ({ fs }) => { + await fs.create( 'database/seeders/user.ts', `export default class UserSeeder { public async run () {} }` ) - await fs.add( + await fs.create( 'database/seeders/client.ts', `export default class ClientSeeder { public async run () {} }` ) - await fs.add( + await fs.create( 'database/seeders/post.ts', `export default class PostSeeder { public static developmentOnly = true @@ -108,14 +114,16 @@ test.group('DbSeed', (group) => { }` ) - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([DbSeed]) + const ace = await new AceFactory().make(fs.baseUrl, { + importer: () => {}, + }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => getDb()) + ace.ui.switchMode('raw') - app.nodeEnvironment = 'production' - const command = await kernel.exec('db:seed', ['--compact-output']) - app.nodeEnvironment = 'test' + const command = await ace.create(DbSeed, ['--compact-output']) + await command.exec() - assert.deepEqual(command.ui.testingRenderer.logs.length, 1) - assert.deepInclude(command.ui.testingRenderer.logs[0].message, 'Executed 2 seeders, 1 ignored') + command.assertLog('grey(❯ Executed 3 seeders)') }) }) diff --git a/test/commands/db-truncate.spec.ts b/test/commands/db_truncate.spec.ts similarity index 65% rename from test/commands/db-truncate.spec.ts rename to test/commands/db_truncate.spec.ts index eb90f081..d7d31df5 100644 --- a/test/commands/db-truncate.spec.ts +++ b/test/commands/db_truncate.spec.ts @@ -8,41 +8,34 @@ */ import { test } from '@japa/runner' -import { Kernel } from '@adonisjs/core/build/standalone' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' -import { fs, setup, cleanup, getDb, setupApplication } from '../../test-helpers' -import DbTruncate from '../../commands/DbTruncate' +import { AceFactory } from '@adonisjs/core/factories' -let app: ApplicationContract -let db: ReturnType +import DbTruncate from '../../commands/db_truncate.js' +import { setup, cleanup, getDb } from '../../test-helpers/index.js' test.group('db:truncate', (group) => { group.each.setup(async () => { - app = await setupApplication() - return () => fs.cleanup() - }) - - group.each.setup(async () => { - db = getDb(app) - app.container.bind('Adonis/Lucid/Database', () => db) await setup() return async () => { await cleanup() await cleanup(['adonis_schema', 'adonis_schema_versions']) - await db.manager.closeAll() } }) - test('should truncate all tables', async ({ assert }) => { - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([DbTruncate]) + test('should truncate all tables', async ({ fs, assert }) => { + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') await db.table('users').insert({ username: 'bonjour' }) await db.table('users').insert({ username: 'bonjour2' }) await db.table('friends').insert({ username: 'bonjour' }) - await kernel.exec('db:truncate', []) + const command = await ace.create(DbTruncate, []) + await command.exec() const usersCount = await db.from('users').count('*', 'total') const friendsCount = await db.from('friends').count('*', 'total') @@ -51,9 +44,12 @@ test.group('db:truncate', (group) => { assert.equal(friendsCount[0]['total'], 0) }) - test('should not truncate adonis migrations tables', async ({ assert }) => { - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([DbTruncate]) + test('should not truncate adonis migrations tables', async ({ fs, assert }) => { + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') await db.connection().schema.createTable('adonis_schema', (table) => { table.increments('id') @@ -68,7 +64,8 @@ test.group('db:truncate', (group) => { await db.table('adonis_schema').insert({ name: 'bonjour' }) await db.table('adonis_schema_versions').insert({ name: 'bonjour' }) - await kernel.exec('db:truncate', []) + const command = await ace.create(DbTruncate, []) + await command.exec() const adonisSchemaCount = await db.from('adonis_schema').count('*', 'total') const adonisSchemaVersionsCount = await db.from('adonis_schema_versions').count('*', 'total') diff --git a/test/commands/db_wipe.spec.ts b/test/commands/db_wipe.spec.ts new file mode 100644 index 00000000..7fc61321 --- /dev/null +++ b/test/commands/db_wipe.spec.ts @@ -0,0 +1,60 @@ +/* + * @adonisjs/lucid + * + * (c) Harminder Virk + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import 'reflect-metadata' +import { test } from '@japa/runner' +import { AceFactory } from '@adonisjs/core/factories' + +import DbWipe from '../../commands/db_wipe.js' +import Migrate from '../../commands/migration/run.js' +import { setup, cleanup, getDb } from '../../test-helpers/index.js' + +test.group('db:wipe and migrate:fresh', (group) => { + group.each.setup(async () => { + await setup() + + return async () => { + await cleanup() + await cleanup(['adonis_schema', 'adonis_schema_versions', 'schema_users']) + } + }) + + test('db:wipe should drop all tables', async ({ fs, assert }) => { + await fs.create( + 'database/migrations/users.ts', + ` + import { Schema } from '../../../../src/Schema' + module.exports = class User extends Schema { + public async up () { + this.schema.createTable('schema_users', (table) => { + table.increments() + }) + } + } + ` + ) + + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') + + const migrate = await ace.create(Migrate, []) + await migrate.exec() + + const tables = await db.connection().getAllTables(['public']) + assert.isAbove(tables.length, 0) + + const dbWipe = await ace.create(DbWipe, []) + await dbWipe.exec() + + assert.lengthOf(await db.connection().getAllTables(['public']), 0) + }) +}) diff --git a/test/commands/make-factory.spec.ts b/test/commands/make-factory.spec.ts deleted file mode 100644 index 4266e99a..00000000 --- a/test/commands/make-factory.spec.ts +++ /dev/null @@ -1,96 +0,0 @@ -/* - * @adonisjs/assembler - * - * (c) AdonisJS - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -import { test } from '@japa/runner' -import { join } from 'path' -import { Kernel } from '@adonisjs/ace' -import { Filesystem } from '@poppinss/dev-utils' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' -import MakeFactory from '../../commands/MakeFactory' -import { - fs, - toNewlineArray, - setupApplication, - replaceFactoryBindings, -} from '../../test-helpers/index' - -const templates = new Filesystem(join(__dirname, '..', '..', 'templates')) - -test.group('Make Factory', async (group) => { - let app: ApplicationContract - - group.each.setup(async () => { - app = await setupApplication() - return () => fs.cleanup() - }) - - test('generate a factory for {model}') - .with([ - { - argument: 'User', - model: 'User', - finalDestination: 'UserFactory.ts', - finalImportPath: 'App/Models/User', - }, - { - argument: 'Blog/Post', - model: 'Post', - finalDestination: 'Blog/PostFactory.ts', - finalImportPath: 'App/Models/Blog/Post', - }, - ]) - .run(async ({ assert }, set) => { - const factory = new MakeFactory(app, new Kernel(app).mockConsoleOutput()) - - factory.model = set.argument - await factory.run() - - const UserFactory = await fs.get(`database/factories/${set.finalDestination}`) - const factoryTemplate = await templates.get('factory.txt') - - assert.deepEqual( - toNewlineArray(UserFactory), - replaceFactoryBindings(factoryTemplate, set.model, set.finalImportPath) - ) - }) - - test('generate a factory with custom import path') - .with([ - { - argument: 'User', - model: 'User', - modelPath: 'Test/User', - finalDestination: 'UserFactory.ts', - finalImportPath: 'App/Models/Test/User', - }, - { - argument: 'Client', - model: 'Client', - modelPath: 'App/Models/Test/B/Client', - finalDestination: 'ClientFactory.ts', - finalImportPath: 'App/Models/Test/B/Client', - }, - ]) - .run(async ({ assert }, set) => { - const factory = new MakeFactory(app, new Kernel(app).mockConsoleOutput()) - - factory.model = set.model - factory.modelPath = set.modelPath - - await factory.run() - - const UserFactory = await fs.get(`database/factories/${set.finalDestination}`) - const factoryTemplate = await templates.get('factory.txt') - - assert.deepEqual( - toNewlineArray(UserFactory), - replaceFactoryBindings(factoryTemplate, set.model, set.finalImportPath) - ) - }) -}) diff --git a/test/commands/make-migration.spec.ts b/test/commands/make-migration.spec.ts deleted file mode 100644 index 30fbbf05..00000000 --- a/test/commands/make-migration.spec.ts +++ /dev/null @@ -1,198 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -/// - -import 'reflect-metadata' -import { join } from 'path' -import { test } from '@japa/runner' -import { Filesystem } from '@poppinss/dev-utils' -import { Kernel } from '@adonisjs/core/build/standalone' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -import { Database } from '../../src/Database' -import MakeMigration from '../../commands/MakeMigration' -import { - fs, - setup, - getDb, - cleanup, - getConfig, - toNewlineArray, - setupApplication, -} from '../../test-helpers' - -let db: ReturnType -let app: ApplicationContract -const templatesFs = new Filesystem(join(__dirname, '..', '..', 'templates')) - -test.group('MakeMigration', (group) => { - group.each.setup(async () => { - app = await setupApplication() - return () => fs.cleanup() - }) - - group.each.setup(async () => { - db = getDb(app) - app.container.bind('Adonis/Lucid/Database', () => db) - await setup() - - return async () => { - await cleanup() - await cleanup(['adonis_schema', 'adonis_schema_versions', 'schema_users', 'schema_accounts']) - await db.manager.closeAll(true) - } - }) - - test('create migration in the default migrations directory', async ({ assert }) => { - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([MakeMigration]) - const makeMigration = await kernel.exec('make:migration', ['user']) - - assert.lengthOf(makeMigration.ui.testingRenderer.logs, 1) - const successLog = makeMigration.ui.testingRenderer.logs[0] - - const userSchema = await fs.get(successLog.message.replace('green(CREATE:)', '').trim()) - const schemaTemplate = await templatesFs.get('migration-make.txt') - - assert.deepEqual( - toNewlineArray(userSchema), - toNewlineArray( - schemaTemplate - .replace('{{#toClassName}}{{ filename }}{{/toClassName}}', 'Users') - .replace('{{#toTableName}}{{ filename }}{{/toTableName}}', 'users') - ) - ) - }) - - test('create migration for alter table', async ({ assert }) => { - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([MakeMigration]) - const makeMigration = await kernel.exec('make:migration', ['user', '--table=my_users']) - - assert.lengthOf(makeMigration.ui.testingRenderer.logs, 1) - const successLog = makeMigration.ui.testingRenderer.logs[0] - - const userSchema = await fs.get(successLog.message.replace('green(CREATE:)', '').trim()) - const schemaTemplate = await templatesFs.get('migration-alter.txt') - - assert.deepEqual( - toNewlineArray(userSchema), - toNewlineArray( - schemaTemplate - .replace('{{#toClassName}}{{ filename }}{{/toClassName}}', 'MyUsers') - .replace('{{#toTableName}}{{ filename }}{{/toTableName}}', 'my_users') - ) - ) - }) - - test('create migration for make table with custom table name', async ({ assert }) => { - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([MakeMigration]) - const makeMigration = await kernel.exec('make:migration', ['user', '--create=my_users']) - - assert.lengthOf(makeMigration.ui.testingRenderer.logs, 1) - const successLog = makeMigration.ui.testingRenderer.logs[0] - - const userSchema = await fs.get(successLog.message.replace('green(CREATE:)', '').trim()) - const schemaTemplate = await templatesFs.get('migration-make.txt') - - assert.deepEqual( - toNewlineArray(userSchema), - toNewlineArray( - schemaTemplate - .replace('{{#toClassName}}{{ filename }}{{/toClassName}}', 'MyUsers') - .replace('{{#toTableName}}{{ filename }}{{/toTableName}}', 'my_users') - ) - ) - }) - - test('create migration file inside a sub-folder', async ({ assert }) => { - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([MakeMigration]) - const makeMigration = await kernel.exec('make:migration', ['profile/users', '--create=users']) - - assert.lengthOf(makeMigration.ui.testingRenderer.logs, 1) - const successLog = makeMigration.ui.testingRenderer.logs[0] - - const userSchema = await fs.get(successLog.message.replace('green(CREATE:)', '').trim()) - const schemaTemplate = await templatesFs.get('migration-make.txt') - - assert.deepEqual( - toNewlineArray(userSchema), - toNewlineArray( - schemaTemplate - .replace('{{#toClassName}}{{ filename }}{{/toClassName}}', 'Users') - .replace('{{#toTableName}}{{ filename }}{{/toTableName}}', 'users') - ) - ) - }) - - test('raise error when defined connection is invalid', async ({ assert }) => { - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([MakeMigration]) - const makeMigration = await kernel.exec('make:migration', ['profile/users', '--connection=foo']) - - assert.equal(makeMigration.exitCode, 1) - assert.deepEqual(makeMigration.ui.testingRenderer.logs, [ - { - stream: 'stderr', - message: - '[ red(error) ] "foo" is not a valid connection name. Double check "config/database" file', - }, - ]) - }) - - test('use custom directory when defined') - .setup(() => { - const config = { - connection: 'primary', - connections: { - primary: Object.assign( - { - migrations: { - paths: ['database/a', 'database/b'], - }, - }, - getConfig() - ), - }, - } - - const customDb = new Database( - config, - app.logger, - app.profiler, - app.container.use('Adonis/Core/Event') - ) - - app.container.bind('Adonis/Lucid/Database', () => customDb) - return () => customDb.manager.closeAll() - }) - .run(async ({ assert }) => { - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([MakeMigration]) - const makeMigration = await kernel.exec('make:migration', ['users', '--folder=database/c']) - - const successLog = makeMigration.ui.testingRenderer.logs[0].message - const userSchema = await fs.get(successLog.replace('green(CREATE:)', '').trim()) - const schemaTemplate = await templatesFs.get('migration-make.txt') - - assert.isTrue(successLog.startsWith('green(CREATE:) database/c')) - - assert.deepEqual( - toNewlineArray(userSchema), - toNewlineArray( - schemaTemplate - .replace('{{#toClassName}}{{ filename }}{{/toClassName}}', 'Users') - .replace('{{#toTableName}}{{ filename }}{{/toTableName}}', 'users') - ) - ) - }) -}) diff --git a/test/commands/make-model.spec.ts b/test/commands/make-model.spec.ts deleted file mode 100644 index 94c2764f..00000000 --- a/test/commands/make-model.spec.ts +++ /dev/null @@ -1,61 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -/// - -import 'reflect-metadata' -import { join } from 'path' -import { test } from '@japa/runner' -import { Filesystem } from '@poppinss/dev-utils' -import { Kernel } from '@adonisjs/core/build/standalone' - -import MakeModel from '../../commands/MakeModel' -import { toNewlineArray, fs, setupApplication } from '../../test-helpers' - -const templatesFs = new Filesystem(join(__dirname, '..', '..', 'templates')) - -test.group('MakeModel', (group) => { - group.each.teardown(async () => { - delete process.env.ADONIS_ACE_CWD - await fs.cleanup() - }) - - test('make a model inside the default directory', async ({ assert }) => { - const app = await setupApplication() - - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([MakeModel]) - await kernel.exec('make:model', ['user']) - - const userModel = await fs.get('app/Models/User.ts') - const schemaTemplate = await templatesFs.get('model.txt') - - assert.deepEqual( - toNewlineArray(userModel), - toNewlineArray(schemaTemplate.replace('{{ filename }}', 'User')) - ) - }) - - test('make a model inside a custom directory', async ({ assert }) => { - const app = await setupApplication() - app.rcFile.namespaces.models = 'App' - - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([MakeModel]) - await kernel.exec('make:model', ['user']) - - const userModel = await fs.get('app/User.ts') - const schemaTemplate = await templatesFs.get('model.txt') - - assert.deepEqual( - toNewlineArray(userModel), - toNewlineArray(schemaTemplate.replace('{{ filename }}', 'User')) - ) - }) -}) diff --git a/test/commands/make_factory.spec.ts b/test/commands/make_factory.spec.ts new file mode 100644 index 00000000..f3cd916e --- /dev/null +++ b/test/commands/make_factory.spec.ts @@ -0,0 +1,42 @@ +/* + * @adonisjs/assembler + * + * (c) AdonisJS + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import { test } from '@japa/runner' +import MakeFactory from '../../commands/make_factory.js' +import { AceFactory } from '@adonisjs/core/factories' + +test.group('Make Factory', async () => { + test('generate a factory for {model}') + .with([ + { + model: 'User', + factoryDestination: 'user_factory.ts', + modelImportPath: '#models/user', + }, + { + model: 'blog/Post', + factoryDestination: 'blog/post_factory.ts', + modelImportPath: '#models/blog/post', + }, + ]) + .run(async ({ assert, fs }, set) => { + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.ui.switchMode('raw') + + const command = await ace.create(MakeFactory, [set.model]) + await command.exec() + + command.assertLog(`green(DONE:) create database/factories/${set.factoryDestination}`) + await assert.fileContains( + `database/factories/${set.factoryDestination}`, + `import ${set.model.split('/').pop()} from '${set.modelImportPath}'` + ) + }) +}) diff --git a/test/commands/make_migration.spec.ts b/test/commands/make_migration.spec.ts new file mode 100644 index 00000000..93f667e4 --- /dev/null +++ b/test/commands/make_migration.spec.ts @@ -0,0 +1,125 @@ +/* + * @adonisjs/lucid + * + * (c) Harminder Virk + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import { test } from '@japa/runner' +import { AceFactory } from '@adonisjs/core/factories' + +import MakeMigration from '../../commands/make_migration.js' +import { setup, getDb, cleanup, getConfig } from '../../test-helpers/index.js' + +function fileNameFromLog(message: string) { + return message + .replace(/green\(DONE\:\)/, '') + .trim() + .replace(/^create/, '') + .trim() +} + +test.group('MakeMigration', (group) => { + group.each.setup(async () => { + await setup() + + return async () => { + await cleanup() + await cleanup(['adonis_schema', 'adonis_schema_versions', 'schema_users', 'schema_accounts']) + } + }) + + test('create migration in the default migrations directory', async ({ fs, assert }) => { + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + ace.app.container.singleton('lucid.db', () => db) + await ace.app.init() + ace.ui.switchMode('raw') + + const command = await ace.create(MakeMigration, ['users']) + await command.exec() + const filename = fileNameFromLog(command.logger.getLogs()[0].message) + + command.assertLogMatches(/database\/migrations\/\d+_create_users_table/) + await assert.fileContains(filename, `import { BaseSchema } from '@adonisjs/lucid/schema'`) + await assert.fileContains(filename, `protected tableName = 'users'`) + await assert.fileContains(filename, `this.schema.createTable`) + }) + + test('create migration for alter table', async ({ fs, assert }) => { + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + ace.app.container.singleton('lucid.db', () => db) + await ace.app.init() + ace.ui.switchMode('raw') + + const command = await ace.create(MakeMigration, ['users', '--alter']) + await command.exec() + const filename = fileNameFromLog(command.logger.getLogs()[0].message) + + command.assertLogMatches(/database\/migrations\/\d+_alter_users_table/) + await assert.fileContains(filename, `import { BaseSchema } from '@adonisjs/lucid/schema'`) + await assert.fileContains(filename, `protected tableName = 'users'`) + await assert.fileContains(filename, `this.schema.alterTable`) + }) + + test('create migration file inside a sub-folder', async ({ fs, assert }) => { + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + ace.app.container.singleton('lucid.db', () => db) + await ace.app.init() + ace.ui.switchMode('raw') + + const command = await ace.create(MakeMigration, ['invoices/lineItem', '--alter']) + await command.exec() + const filename = fileNameFromLog(command.logger.getLogs()[0].message) + + command.assertLogMatches(/database\/migrations\/invoices\/\d+_alter_line_items_table/) + await assert.fileContains(filename, `import { BaseSchema } from '@adonisjs/lucid/schema'`) + await assert.fileContains(filename, `protected tableName = 'line_items'`) + await assert.fileContains(filename, `this.schema.alterTable`) + }) + + test('print error when using an invalid db connection', async ({ fs }) => { + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + ace.app.container.singleton('lucid.db', () => db) + await ace.app.init() + ace.ui.switchMode('raw') + + const command = await ace.create(MakeMigration, ['users', '--connection', 'foo']) + await command.exec() + + command.assertFailed() + command.assertLog( + '[ red(error) ] "foo" is not a valid connection name. Double check "config/database" file', + 'stderr' + ) + }) + + test('pick directory from migration sources').run(async ({ fs }) => { + const db = getDb(undefined, { + connection: 'primary', + connections: { + primary: Object.assign(getConfig(), { + migrations: { + paths: ['database/foo', './database/bar'], + }, + }), + }, + }) + + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + ace.app.container.singleton('lucid.db', () => db) + await ace.app.init() + ace.ui.switchMode('raw') + + const command = await ace.create(MakeMigration, ['users']) + command.prompt.trap('Select the migrations folder').chooseOption(0) + + await command.exec() + command.assertLogMatches(/database\/foo\/\d+_create_users_table/) + }) +}) diff --git a/test/commands/make_model.spec.ts b/test/commands/make_model.spec.ts new file mode 100644 index 00000000..2d97911d --- /dev/null +++ b/test/commands/make_model.spec.ts @@ -0,0 +1,81 @@ +/* + * @adonisjs/lucid + * + * (c) Harminder Virk + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import { test } from '@japa/runner' +import { ListLoader } from '@adonisjs/core/ace' +import { AceFactory } from '@adonisjs/core/factories' + +import { getDb } from '../../test-helpers/index.js' +import MakeModel from '../../commands/make_model.js' +import MakeFactory from '../../commands/make_factory.js' +import MakeMigration from '../../commands/make_migration.js' + +test.group('MakeModel', (group) => { + group.each.teardown(async () => { + delete process.env.ADONIS_ACE_CWD + }) + + test('make a model', async ({ fs, assert }) => { + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.ui.switchMode('raw') + + const command = await ace.create(MakeModel, ['user']) + await command.exec() + + command.assertLog('green(DONE:) create app/models/user.ts') + await assert.fileContains('app/models/user.ts', 'export default class User extends BaseModel {') + await assert.fileContains( + 'app/models/user.ts', + `import { BaseModel, column } from '@adonisjs/lucid/orm'` + ) + }) + + test('make a model with migration', async ({ fs, assert }) => { + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + ace.app.container.singleton('lucid.db', () => db) + await ace.app.init() + ace.ui.switchMode('raw') + + ace.addLoader(new ListLoader([MakeMigration])) + + const command = await ace.create(MakeModel, ['user', '--migration']) + await command.exec() + + command.assertLog('green(DONE:) create app/models/user.ts') + command.assertLogMatches(/database\/migrations\/\d+_create_users_table/) + await assert.fileContains('app/models/user.ts', 'export default class User extends BaseModel {') + await assert.fileContains( + 'app/models/user.ts', + `import { BaseModel, column } from '@adonisjs/lucid/orm'` + ) + }) + + test('make a model with factory', async ({ fs, assert }) => { + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + ace.app.container.singleton('lucid.db', () => db) + await ace.app.init() + ace.ui.switchMode('raw') + + ace.addLoader(new ListLoader([MakeFactory])) + + const command = await ace.create(MakeModel, ['user', '--factory']) + await command.exec() + + command.assertLog('green(DONE:) create app/models/user.ts') + command.assertLog('green(DONE:) create database/factories/user_factory.ts') + await assert.fileContains('app/models/user.ts', 'export default class User extends BaseModel {') + await assert.fileContains( + 'app/models/user.ts', + `import { BaseModel, column } from '@adonisjs/lucid/orm'` + ) + }) +}) diff --git a/test/commands/make_seeder.spec.ts b/test/commands/make_seeder.spec.ts new file mode 100644 index 00000000..c2f69c60 --- /dev/null +++ b/test/commands/make_seeder.spec.ts @@ -0,0 +1,37 @@ +/* + * @adonisjs/lucid + * + * (c) Harminder Virk + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import { test } from '@japa/runner' +import { AceFactory } from '@adonisjs/core/factories' +import MakeSeeder from '../../commands/make_seeder.js' + +test.group('MakeSeeder', (group) => { + group.each.teardown(async () => { + delete process.env.ADONIS_ACE_CWD + }) + + test('make a seeder', async ({ fs, assert }) => { + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.ui.switchMode('raw') + + const command = await ace.create(MakeSeeder, ['user']) + await command.exec() + + command.assertLog('green(DONE:) create database/seeders/user_seeder.ts') + await assert.fileContains( + 'database/seeders/user_seeder.ts', + `import { BaseSeeder } from '@adonisjs/lucid/seeders'` + ) + await assert.fileContains( + 'database/seeders/user_seeder.ts', + `export default class extends BaseSeeder` + ) + }) +}) diff --git a/test/commands/migration/fresh.spec.ts b/test/commands/migration/fresh.spec.ts index 8c9cd31b..67d0e6cb 100644 --- a/test/commands/migration/fresh.spec.ts +++ b/test/commands/migration/fresh.spec.ts @@ -7,48 +7,33 @@ * file that was distributed with this source code. */ -/// - import 'reflect-metadata' import { test } from '@japa/runner' -import Migrate from '../../../commands/Migration/Run' -import { Kernel } from '@adonisjs/core/build/standalone' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -import DbSeed from '../../../commands/DbSeed' -import DbWipe from '../../../commands/DbWipe' -import { Migrator } from '../../../src/Migrator' -import Fresh from '../../../commands/Migration/Fresh' -import { fs, setup, cleanup, getDb, setupApplication } from '../../../test-helpers' +import { AceFactory } from '@adonisjs/core/factories' -let app: ApplicationContract -let db: ReturnType +import Migrate from '../../../commands/migration/run.js' +import Fresh from '../../../commands/migration/fresh.js' +import { setup, cleanup, getDb } from '../../../test-helpers/index.js' +import { ListLoader } from '@adonisjs/core/ace' +import DbWipe from '../../../commands/db_wipe.js' +import DbSeed from '../../../commands/db_seed.js' test.group('migrate:fresh', (group) => { group.each.setup(async () => { - app = await setupApplication() - return () => fs.cleanup() - }) - - group.each.setup(async () => { - db = getDb(app) - app.container.bind('Adonis/Lucid/Database', () => db) - app.container.bind('Adonis/Lucid/Migrator', () => Migrator) await setup() return async () => { await cleanup() await cleanup(['adonis_schema', 'adonis_schema_versions', 'schema_users']) - await db.manager.closeAll() } }) - test('migration:fresh should drop all tables and run migrations', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', + test('migration:fresh should drop all tables and run migrations', async ({ fs, assert }) => { + await fs.create( + 'database/migrations/fresh_cmd_users.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -58,24 +43,40 @@ test.group('migrate:fresh', (group) => { ` ) - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate, Fresh, DbWipe]) + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') + + ace.addLoader(new ListLoader([DbWipe, DbSeed, Migrate])) - await kernel.exec('migration:run', []) - await kernel.exec('migration:fresh', []) + const migrate = await ace.create(Migrate, []) + await migrate.exec() const migrated = await db.connection().from('adonis_schema').select('*') const hasUsersTable = await db.connection().schema.hasTable('schema_users') assert.lengthOf(migrated, 1) assert.isTrue(hasUsersTable) - assert.equal(migrated[0].name, 'database/migrations/users') + assert.equal(migrated[0].name, 'database/migrations/fresh_cmd_users') assert.equal(migrated[0].batch, 1) + + const fresh = await ace.create(Fresh, []) + await fresh.exec() + + const migrated1 = await db.connection().from('adonis_schema').select('*') + const hasUsersTable1 = await db.connection().schema.hasTable('schema_users') + + assert.lengthOf(migrated1, 1) + assert.isTrue(hasUsersTable1) + assert.equal(migrated1[0].name, 'database/migrations/fresh_cmd_users') + assert.equal(migrated1[0].batch, 1) }) - test('migration:fresh --seed should run seeders', async ({ assert }) => { - await fs.add( - 'database/seeders/user.ts', + test('migration:fresh --seed should run seeders', async ({ fs, assert }) => { + await fs.create( + 'database/seeders/fresh_cmd_user.ts', `export default class UserSeeder { public async run () { process.env.EXEC_USER_SEEDER = 'true' @@ -83,11 +84,11 @@ test.group('migrate:fresh', (group) => { }` ) - await fs.add( - 'database/migrations/users.ts', + await fs.create( + 'database/migrations/fresh_cmd_users_v1.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -97,11 +98,19 @@ test.group('migrate:fresh', (group) => { ` ) - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate, Fresh, DbSeed, DbWipe]) + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') + + ace.addLoader(new ListLoader([DbWipe, DbSeed, Migrate])) + + const migrate = await ace.create(Migrate, []) + await migrate.exec() - await kernel.exec('migration:run', []) - await kernel.exec('migration:fresh', ['--seed']) + const fresh = await ace.create(Fresh, ['--seed']) + await fresh.exec() assert.equal(process.env.EXEC_USER_SEEDER, 'true') delete process.env.EXEC_USER_SEEDER diff --git a/test/commands/migration/refresh.spec.ts b/test/commands/migration/refresh.spec.ts index afdc82dd..5ffde438 100644 --- a/test/commands/migration/refresh.spec.ts +++ b/test/commands/migration/refresh.spec.ts @@ -7,48 +7,32 @@ * file that was distributed with this source code. */ -/// - import 'reflect-metadata' import { test } from '@japa/runner' -import { Kernel } from '@adonisjs/core/build/standalone' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -import DbSeed from '../../../commands/DbSeed' -import { Migrator } from '../../../src/Migrator' -import Reset from '../../../commands/Migration/Reset' -import Migrate from '../../../commands/Migration/Run' -import Refresh from '../../../commands/Migration/Refresh' -import Rollback from '../../../commands/Migration/Rollback' -import { fs, setup, cleanup, getDb, setupApplication } from '../../../test-helpers' +import { ListLoader } from '@adonisjs/core/ace' +import { AceFactory } from '@adonisjs/core/factories' -let db: ReturnType -let app: ApplicationContract +import DbSeed from '../../../commands/db_seed.js' +import Reset from '../../../commands/migration/reset.js' +import Migrate from '../../../commands/migration/run.js' +import Refresh from '../../../commands/migration/refresh.js' +import Rollback from '../../../commands/migration/rollback.js' +import { cleanup, getDb } from '../../../test-helpers/index.js' test.group('migration:refresh', (group) => { group.each.setup(async () => { - app = await setupApplication() - await setup() - return () => fs.cleanup() - }) - - group.each.setup(async () => { - db = getDb(app) - app.container.bind('Adonis/Lucid/Database', () => db) - app.container.bind('Adonis/Lucid/Migrator', () => Migrator) return async () => { await cleanup() await cleanup(['adonis_schema', 'adonis_schema_versions', 'schema_users', 'schema_accounts']) - await db.manager.closeAll(true) } }) - test('rollback to batch 0 and migrate database', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', + test('rollback to batch 0 and migrate database', async ({ fs, assert }) => { + await fs.create( + 'database/migrations/refresh_cmd_users.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -62,11 +46,11 @@ test.group('migration:refresh', (group) => { ` ) - await fs.add( - 'database/migrations/posts.ts', + await fs.create( + 'database/migrations/refresh_cmd_posts.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class Account extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class Account extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { table.increments() @@ -80,11 +64,19 @@ test.group('migration:refresh', (group) => { ` ) - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate, Rollback, Reset, Refresh]) + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') + + ace.addLoader(new ListLoader([Reset, DbSeed, Migrate, Rollback])) + + const migrate = await ace.create(Migrate, []) + await migrate.exec() - await kernel.exec('migration:run', []) - await kernel.exec('migration:refresh', []) + const refresh = await ace.create(Refresh, []) + await refresh.exec() const migrated = await db.connection().from('adonis_schema').select('*') const hasUsersTable = await db.connection().schema.hasTable('schema_users') @@ -95,9 +87,9 @@ test.group('migration:refresh', (group) => { assert.isTrue(hasAccountsTable) }) - test('run seeders when --seed flag is passed', async ({ assert }) => { - await fs.add( - 'database/seeders/user.ts', + test('run seeders when --seed flag is passed', async ({ fs, assert }) => { + await fs.create( + 'database/seeders/refres_cmd_user.ts', `export default class UserSeeder { public async run () { process.env.EXEC_USER_SEEDER = 'true' @@ -105,11 +97,11 @@ test.group('migration:refresh', (group) => { }` ) - await fs.add( - 'database/migrations/users.ts', + await fs.create( + 'database/migrations/refres_cmd_users_v1.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -123,11 +115,11 @@ test.group('migration:refresh', (group) => { ` ) - await fs.add( + await fs.create( 'database/migrations/posts.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class Account extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class Account extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { table.increments() @@ -141,11 +133,19 @@ test.group('migration:refresh', (group) => { ` ) - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate, Rollback, Reset, Refresh, DbSeed]) + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') + + ace.addLoader(new ListLoader([Reset, DbSeed, Migrate, Rollback])) + + const migrate = await ace.create(Migrate, []) + await migrate.exec() - await kernel.exec('migration:run', []) - await kernel.exec('migration:refresh', ['--seed']) + const refresh = await ace.create(Refresh, ['--seed']) + await refresh.exec() assert.equal(process.env.EXEC_USER_SEEDER, 'true') delete process.env.EXEC_USER_SEEDER diff --git a/test/commands/migration/reset.spec.ts b/test/commands/migration/reset.spec.ts index fe405006..ee9f6e97 100644 --- a/test/commands/migration/reset.spec.ts +++ b/test/commands/migration/reset.spec.ts @@ -7,46 +7,32 @@ * file that was distributed with this source code. */ -/// - import 'reflect-metadata' import { test } from '@japa/runner' -import { Kernel } from '@adonisjs/core/build/standalone' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -import { Migrator } from '../../../src/Migrator' -import Reset from '../../../commands/Migration/Reset' -import Migrate from '../../../commands/Migration/Run' -import Rollback from '../../../commands/Migration/Rollback' -import { fs, setup, cleanup, getDb, setupApplication } from '../../../test-helpers' +import { ListLoader } from '@adonisjs/core/ace' +import { AceFactory } from '@adonisjs/core/factories' -let db: ReturnType -let app: ApplicationContract +import Reset from '../../../commands/migration/reset.js' +import Migrate from '../../../commands/migration/run.js' +import Rollback from '../../../commands/migration/rollback.js' +import { setup, cleanup, getDb } from '../../../test-helpers/index.js' test.group('migration:reset', (group) => { group.each.setup(async () => { - app = await setupApplication() await setup() - return () => fs.cleanup() - }) - group.each.setup(async () => { - db = getDb(app) - app.container.bind('Adonis/Lucid/Database', () => db) - app.container.bind('Adonis/Lucid/Migrator', () => Migrator) return async () => { await cleanup() await cleanup(['adonis_schema', 'adonis_schema_versions', 'schema_users', 'schema_accounts']) - await db.manager.closeAll(true) } }) - test('rollback to batch 0', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', + test('rollback to batch 0', async ({ fs, assert }) => { + await fs.create( + 'database/migrations/reset_cmd_users.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -60,11 +46,11 @@ test.group('migration:reset', (group) => { ` ) - await fs.add( - 'database/migrations/posts.ts', + await fs.create( + 'database/migrations/reset_cmd_posts.ts', ` import { Schema } from '../../../../src/Schema' - module.exports = class Account extends Schema { + export default class Account extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { table.increments() @@ -78,11 +64,19 @@ test.group('migration:reset', (group) => { ` ) - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate, Rollback, Reset]) + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') + + ace.addLoader(new ListLoader([Rollback])) + + const migrate = await ace.create(Migrate, []) + await migrate.exec() - await kernel.exec('migration:run', []) - await kernel.exec('migration:reset', []) + const refresh = await ace.create(Reset, []) + await refresh.exec() const migrated = await db.connection().from('adonis_schema').select('*') const hasUsersTable = await db.connection().schema.hasTable('schema_users') diff --git a/test/commands/migration/run.spec.ts b/test/commands/migration/run.spec.ts index e2b9ef75..c46ed5d2 100644 --- a/test/commands/migration/run.spec.ts +++ b/test/commands/migration/run.spec.ts @@ -7,51 +7,34 @@ * file that was distributed with this source code. */ -/// - import 'reflect-metadata' -import { join } from 'path' import { test } from '@japa/runner' -import { Kernel } from '@adonisjs/core/build/standalone' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -import { Migrator } from '../../../src/Migrator' -import Migrate from '../../../commands/Migration/Run' -import { fs, setup, cleanup, getDb, setupApplication } from '../../../test-helpers' +import { AceFactory } from '@adonisjs/core/factories' -let db: ReturnType -let app: ApplicationContract +import Migrate from '../../../commands/migration/run.js' +import { setup, cleanup as cleanupTables, getDb } from '../../../test-helpers/index.js' test.group('migration:run', (group) => { group.each.setup(async () => { - app = await setupApplication() await setup() - return () => fs.cleanup() - }) - - group.each.setup(async () => { - db = getDb(app) - app.container.bind('Adonis/Lucid/Database', () => db) - app.container.bind('Adonis/Lucid/Migrator', () => Migrator) return async () => { - await cleanup() - await cleanup([ + await cleanupTables() + await cleanupTables([ 'adonis_schema', 'adonis_schema_versions', 'schema_users', 'schema_accounts', 'schema_clients', ]) - await db.manager.closeAll(true) } }) - test('run migrations from default directory', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', + test('run migrations from default directory', async ({ fs, assert }) => { + await fs.create( + 'database/migrations/run_cmd_users.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -61,36 +44,44 @@ test.group('migration:run', (group) => { ` ) - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate]) - await kernel.exec('migration:run', []) + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') + + const migrate = await ace.create(Migrate, []) + await migrate.exec() const migrated = await db.connection().from('adonis_schema').select('*') const hasUsersTable = await db.connection().schema.hasTable('schema_users') assert.lengthOf(migrated, 1) assert.isTrue(hasUsersTable) - assert.equal(migrated[0].name, 'database/migrations/users') + assert.equal(migrated[0].name, 'database/migrations/run_cmd_users') assert.equal(migrated[0].batch, 1) }) - test('skip migrations when already up to date', async ({ assert }) => { - await fs.fsExtra.ensureDir(join(fs.basePath, 'database/migrations')) + test('skip migrations when already up to date', async ({ fs, assert }) => { + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate]) - await kernel.exec('migration:run', []) + const migrate = await ace.create(Migrate, []) + await migrate.exec() const migrated = await db.connection().from('adonis_schema').select('*') assert.lengthOf(migrated, 0) }) - test('do not execute migrations in dry-run', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', + test('do not execute migrations in dry-run', async ({ fs, assert }) => { + await fs.create( + 'database/migrations/run_cmd_users_v1.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -100,23 +91,31 @@ test.group('migration:run', (group) => { ` ) - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate]) - await kernel.exec('migration:run', ['--dry-run']) + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') + + const migrate = await ace.create(Migrate, ['--dry-run']) + await migrate.exec() const migrated = await db.connection().from('adonis_schema').select('*') assert.lengthOf(migrated, 0) }) - test('do not run migrations in production', async ({ assert }) => { + test('do not run migrations in production', async ({ fs, assert, cleanup }) => { assert.plan(1) - app.nodeEnvironment = 'production' + process.env.NODE_ENV = 'production' + cleanup(() => { + delete process.env.NODE_ENV + }) - await fs.add( - 'database/migrations/users.ts', + await fs.create( + 'database/migrations/run_cmd_users_v2.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -126,21 +125,43 @@ test.group('migration:run', (group) => { ` ) - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate]).interactive(false) - await kernel.exec('migration:run', []) + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { + importer: (filePath) => { + return import(filePath) + }, + }) + + await ace.app.init() + await ace.app.boot() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') + + const migrate = await ace.create(Migrate, []) + migrate.prompt + .trap('You are in production environment. Want to continue running migrations?') + .reject() + + await migrate.exec() assert.isFalse(await db.connection().schema.hasTable('adonis_schema')) }) - test('run migrations in production when --force flag is passed', async ({ assert }) => { - app.nodeEnvironment = 'production' + test('run migrations in production when --force flag is passed', async ({ + fs, + assert, + cleanup, + }) => { + process.env.NODE_ENV = 'production' + cleanup(() => { + delete process.env.NODE_ENV + }) - await fs.add( - 'database/migrations/users.ts', + await fs.create( + 'database/migrations/run_cmd_users_v3.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -150,25 +171,36 @@ test.group('migration:run', (group) => { ` ) - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate]).interactive(false) - await kernel.exec('migration:run', ['--force']) + const db = getDb() + + const ace = await new AceFactory().make(fs.baseUrl, { + importer: (filePath) => { + return import(filePath) + }, + }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') + + const migrate = await ace.create(Migrate, ['--force']) + await migrate.exec() const migrated = await db.connection().from('adonis_schema').select('*') const hasUsersTable = await db.connection().schema.hasTable('schema_users') assert.lengthOf(migrated, 1) assert.isTrue(hasUsersTable) - assert.equal(migrated[0].name, 'database/migrations/users') + assert.equal(migrated[0].name, 'database/migrations/run_cmd_users_v3') assert.equal(migrated[0].batch, 1) }) - test('run migrations with compact output should display one line', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', + test('run migrations with compact output should display one line', async ({ fs }) => { + await fs.create( + 'database/migrations/run_cmd_users_v4.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + + export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -178,11 +210,12 @@ test.group('migration:run', (group) => { ` ) - await fs.add( - 'database/migrations/clients.ts', + await fs.create( + 'database/migrations/run_cmd_clients_v4.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class Client extends Schema { + import { Schema } from '../../../../src/schema/index.js' + + export default class Client extends Schema { public async up () { this.schema.createTable('schema_clients', (table) => { table.increments() @@ -192,27 +225,27 @@ test.group('migration:run', (group) => { ` ) - process.env.CLI_UI_IS_TESTING = 'true' - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate]).interactive(false) + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') - const command = await kernel.exec('migration:run', ['--compact-output']) - const logs = command.ui.testingRenderer.logs.filter( - (log) => !log.message.includes('Upgrading migrations version from') - ) + const migrate = await ace.create(Migrate, ['--compact-output']) + await migrate.exec() - assert.deepEqual(logs.length, 1) - assert.isTrue(logs[0].message.includes('❯ Executed 2 migrations')) + migrate.assertLogMatches(/grey\(❯ Executed 2 migrations/) }) test('run already migrated migrations with compact output should display one line', async ({ - assert, + fs, }) => { - await fs.add( - 'database/migrations/users.ts', + await fs.create( + 'database/migrations/run_cmd_users_v5.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + + export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -222,11 +255,12 @@ test.group('migration:run', (group) => { ` ) - await fs.add( - 'database/migrations/clients.ts', + await fs.create( + 'database/migrations/run_cmd_clients_v5.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class Client extends Schema { + import { Schema } from '../../../../src/schema/index.js' + + export default class Client extends Schema { public async up () { this.schema.createTable('schema_clients', (table) => { table.increments() @@ -236,17 +270,16 @@ test.group('migration:run', (group) => { ` ) - process.env.CLI_UI_IS_TESTING = 'true' - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate]).interactive(false) + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') - await kernel.exec('migration:run', ['--compact-output']) - const command = await kernel.exec('migration:run', ['--compact-output']) - const logs = command.ui.testingRenderer.logs.filter( - (log) => !log.message.includes('Upgrading migrations version from') - ) + const migrate = await ace.create(Migrate, ['--compact-output']) + await migrate.exec() + await migrate.exec() - assert.deepEqual(logs.length, 1) - assert.isTrue(logs[0].message.includes('❯ Already up to date')) + migrate.assertLogMatches(/grey\(❯ Already up to date/) }) }) diff --git a/test/connection/connection.spec.ts b/test/connection/connection.spec.ts index 36f06551..7d42593d 100644 --- a/test/connection/connection.spec.ts +++ b/test/connection/connection.spec.ts @@ -9,7 +9,7 @@ import { Knex } from 'knex' import { test } from '@japa/runner' -import { MysqlConfig } from '../../adonis-typings/database.js' +import { MysqlConfig } from '../../src/types/database.js' import { Connection } from '../../src/connection/index.js' import { setup, cleanup, getConfig, resetTables, logger } from '../../test-helpers/index.js' diff --git a/test/database/database.spec.ts b/test/database/database.spec.ts index acaf6fad..b3f8084f 100644 --- a/test/database/database.spec.ts +++ b/test/database/database.spec.ts @@ -9,7 +9,7 @@ import { test } from '@japa/runner' -import { Database } from '../../src/database/index.js' +import { Database } from '../../src/database/main.js' import { getConfig, setup, cleanup, logger, createEmitter } from '../../test-helpers/index.js' test.group('Database', (group) => { diff --git a/test/factory/belongs_to.spec.ts b/test/factory/belongs_to.spec.ts index 9456ea05..2b8caf34 100644 --- a/test/factory/belongs_to.spec.ts +++ b/test/factory/belongs_to.spec.ts @@ -8,9 +8,9 @@ */ import { test } from '@japa/runner' -import type { BelongsTo } from '../../adonis-typings/relations.js' +import type { BelongsTo } from '../../src/types/relations.js' -import { FactoryManager } from '../../src/factory/index.js' +import { FactoryManager } from '../../src/factories/main.js' import { column, belongsTo } from '../../src/orm/decorators/index.js' import { diff --git a/test/factory/factory_builder.spec.ts b/test/factory/factory_builder.spec.ts index c668dcd5..1ad34fc6 100644 --- a/test/factory/factory_builder.spec.ts +++ b/test/factory/factory_builder.spec.ts @@ -11,9 +11,9 @@ import { test } from '@japa/runner' import { randomUUID } from 'node:crypto' import { column } from '../../src/orm/decorators/index.js' -import { FactoryManager } from '../../src/factory/index.js' -import { FactoryContext } from '../../src/factory/factory_context.js' -import { FactoryBuilder } from '../../src/factory/factory_builder.js' +import { FactoryManager } from '../../src/factories/main.js' +import { FactoryContext } from '../../src/factories/factory_context.js' +import { FactoryBuilder } from '../../src/factories/factory_builder.js' import { setup, diff --git a/test/factory/factory_model.spec.ts b/test/factory/factory_model.spec.ts index 49558722..7a9bab6e 100644 --- a/test/factory/factory_model.spec.ts +++ b/test/factory/factory_model.spec.ts @@ -9,11 +9,11 @@ import { test } from '@japa/runner' -import { FactoryManager } from '../../src/factory/index.js' -import type { HasOne } from '../../adonis-typings/relations.js' +import { FactoryManager } from '../../src/factories/main.js' +import type { HasOne } from '../../src/types/relations.js' import { column, hasOne } from '../../src/orm/decorators/index.js' -import { FactoryModel } from '../../src/factory/factory_model.js' -import { HasOne as FactoryHasOne } from '../../src/factory/relations/has_one.js' +import { FactoryModel } from '../../src/factories/factory_model.js' +import { HasOne as FactoryHasOne } from '../../src/factories/relations/has_one.js' import { setup, diff --git a/test/factory/has_many.spec.ts b/test/factory/has_many.spec.ts index 130556f0..b604aca4 100644 --- a/test/factory/has_many.spec.ts +++ b/test/factory/has_many.spec.ts @@ -8,9 +8,9 @@ */ import { test } from '@japa/runner' -import type { HasMany } from '../../adonis-typings/relations.js' +import type { HasMany } from '../../src/types/relations.js' -import { FactoryManager } from '../../src/factory/index.js' +import { FactoryManager } from '../../src/factories/main.js' import { column, hasMany } from '../../src/orm/decorators/index.js' import { diff --git a/test/factory/has_one.spec.ts b/test/factory/has_one.spec.ts index 592498ad..74e98b8d 100644 --- a/test/factory/has_one.spec.ts +++ b/test/factory/has_one.spec.ts @@ -8,9 +8,9 @@ */ import { test } from '@japa/runner' -import type { HasOne } from '../../adonis-typings/relations.js' +import type { HasOne } from '../../src/types/relations.js' -import { FactoryManager } from '../../src/factory/index.js' +import { FactoryManager } from '../../src/factories/main.js' import { column, hasOne } from '../../src/orm/decorators/index.js' import { diff --git a/test/factory/many_to_many.spec.ts b/test/factory/many_to_many.spec.ts index d7b800c4..96646cb8 100644 --- a/test/factory/many_to_many.spec.ts +++ b/test/factory/many_to_many.spec.ts @@ -7,9 +7,9 @@ * file that was distributed with this source code. */ import { test } from '@japa/runner' -import type { ManyToMany } from '../../adonis-typings/relations.js' +import type { ManyToMany } from '../../src/types/relations.js' -import { FactoryManager } from '../../src/factory/index.js' +import { FactoryManager } from '../../src/factories/main.js' import { column, manyToMany } from '../../src/orm/decorators/index.js' import { diff --git a/test/migrations/migration_source.spec.ts b/test/migrations/migration_source.spec.ts index ce17057c..7e451bb9 100644 --- a/test/migrations/migration_source.spec.ts +++ b/test/migrations/migration_source.spec.ts @@ -11,7 +11,7 @@ import { join } from 'node:path' import { test } from '@japa/runner' import { AppFactory } from '@adonisjs/core/factories/app' -import { MigrationSource } from '../../src/migrator/migration_source.js' +import { MigrationSource } from '../../src/migration/source.js' import { setup, getDb, resetTables } from '../../test-helpers/index.js' test.group('MigrationSource', (group) => { diff --git a/test/orm/base_model.spec.ts b/test/orm/base_model.spec.ts index 809b0fcf..1b957808 100644 --- a/test/orm/base_model.spec.ts +++ b/test/orm/base_model.spec.ts @@ -13,7 +13,7 @@ import lodash from '@poppinss/utils/lodash' import { AppFactory } from '@adonisjs/core/factories/app' import { ModelQueryBuilder } from '../../src/orm/query_builder/index.js' -import type { HasOne, HasMany, BelongsTo } from '../../adonis-typings/relations.js' +import type { HasOne, HasMany, BelongsTo } from '../../src/types/relations.js' import { column, @@ -50,11 +50,11 @@ import { cleanup as cleanupTables, } from '../../test-helpers/index.js' import { ModelPaginator } from '../../src/orm/paginator/index.js' -import { QueryClientContract } from '../../adonis-typings/database.js' +import { QueryClientContract } from '../../src/types/database.js' import { SimplePaginator } from '../../src/database/paginator/simple_paginator.js' -import { InsertQueryBuilderContract } from '../../adonis-typings/querybuilder.js' +import { InsertQueryBuilderContract } from '../../src/types/querybuilder.js' import { SnakeCaseNamingStrategy } from '../../src/orm/naming_strategies/snake_case.js' -import { ModelQueryBuilderContract, LucidModel, LucidRow } from '../../adonis-typings/model.js' +import { ModelQueryBuilderContract, LucidModel, LucidRow } from '../../src/types/model.js' test.group('Base model | boot', (group) => { group.setup(async () => { diff --git a/test/orm/base_model_options.spec.ts b/test/orm/base_model_options.spec.ts index add1aad0..ca529d24 100644 --- a/test/orm/base_model_options.spec.ts +++ b/test/orm/base_model_options.spec.ts @@ -8,7 +8,7 @@ */ import { test } from '@japa/runner' -import type { HasOne } from '../../adonis-typings/relations.js' +import type { HasOne } from '../../src/types/relations.js' import { column, hasOne } from '../../src/orm/decorators/index.js' import { diff --git a/test/orm/model_belongs_to.spec.ts b/test/orm/model_belongs_to.spec.ts index 722419cb..fab36948 100644 --- a/test/orm/model_belongs_to.spec.ts +++ b/test/orm/model_belongs_to.spec.ts @@ -8,7 +8,7 @@ */ import { test } from '@japa/runner' -import type { BelongsTo } from '../../adonis-typings/relations.js' +import type { BelongsTo } from '../../src/types/relations.js' import { scope } from '../../src/orm/base_model/index.js' import { column, belongsTo } from '../../src/orm/decorators/index.js' diff --git a/test/orm/model_has_many.spec.ts b/test/orm/model_has_many.spec.ts index 83e9a113..0fa44c65 100644 --- a/test/orm/model_has_many.spec.ts +++ b/test/orm/model_has_many.spec.ts @@ -8,7 +8,7 @@ */ import { test } from '@japa/runner' -import type { HasMany } from '../../adonis-typings/relations.js' +import type { HasMany } from '../../src/types/relations.js' import { scope } from '../../src/orm/base_model/index.js' import { column, hasMany } from '../../src/orm/decorators/index.js' diff --git a/test/orm/model_has_many_through.spec.ts b/test/orm/model_has_many_through.spec.ts index 320df360..415b3f27 100644 --- a/test/orm/model_has_many_through.spec.ts +++ b/test/orm/model_has_many_through.spec.ts @@ -8,7 +8,7 @@ */ import { test } from '@japa/runner' -import type { HasManyThrough } from '../../adonis-typings/relations.js' +import type { HasManyThrough } from '../../src/types/relations.js' import { scope } from '../../src/orm/base_model/index.js' import { hasManyThrough, column } from '../../src/orm/decorators/index.js' diff --git a/test/orm/model_has_one.spec.ts b/test/orm/model_has_one.spec.ts index ea40c7a8..a4636227 100644 --- a/test/orm/model_has_one.spec.ts +++ b/test/orm/model_has_one.spec.ts @@ -8,7 +8,7 @@ */ import { test } from '@japa/runner' -import type { HasOne, BelongsTo } from '../../adonis-typings/relations.js' +import type { HasOne, BelongsTo } from '../../src/types/relations.js' import { scope } from '../../src/orm/base_model/index.js' import { column, hasOne, belongsTo } from '../../src/orm/decorators/index.js' diff --git a/test/orm/model_many_to_many.spec.ts b/test/orm/model_many_to_many.spec.ts index 62b6f278..34b0bd1f 100644 --- a/test/orm/model_many_to_many.spec.ts +++ b/test/orm/model_many_to_many.spec.ts @@ -8,7 +8,7 @@ */ import { test } from '@japa/runner' -import type { ManyToMany } from '../../adonis-typings/relations.js' +import type { ManyToMany } from '../../src/types/relations.js' import { scope } from '../../src/orm/base_model/index.js' import { column, manyToMany } from '../../src/orm/decorators/index.js' diff --git a/test/seeders/seeders_runner.spec.ts b/test/seeders/seeders_runner.spec.ts index 13f969d4..7ea13b90 100644 --- a/test/seeders/seeders_runner.spec.ts +++ b/test/seeders/seeders_runner.spec.ts @@ -10,7 +10,7 @@ import { test } from '@japa/runner' import { AppFactory } from '@adonisjs/core/factories/app' -import { SeedsRunner } from '../../src/seeders_runner/index.js' +import { SeedsRunner } from '../../src/seeders/runner.js' import { getDb, setup, cleanup as cleanupTables } from '../../test-helpers/index.js' test.group('Seeds Runner', (group) => { diff --git a/test/seeders/seeders_source.spec.ts b/test/seeders/seeders_source.spec.ts index f2f66891..fa59c343 100644 --- a/test/seeders/seeders_source.spec.ts +++ b/test/seeders/seeders_source.spec.ts @@ -11,7 +11,7 @@ import { join } from 'node:path' import { test } from '@japa/runner' import { AppFactory } from '@adonisjs/core/factories/app' -import { SeedersSource } from '../../src/seeders_runner/seeders_source.js' +import { SeedersSource } from '../../src/seeders/source.js' import { getDb, setup, cleanup } from '../../test-helpers/index.js' test.group('Seeds Source', (group) => { diff --git a/test/utils.spec.ts b/test/utils.spec.ts index 422361da..052da69e 100644 --- a/test/utils.spec.ts +++ b/test/utils.spec.ts @@ -7,10 +7,8 @@ * file that was distributed with this source code. */ -/// - import { test } from '@japa/runner' -import { syncDiff } from '../src/utils' +import { syncDiff } from '../src/utils/index.js' test.group('Utils | syncDiff', () => { test('return ids to be added', ({ assert }) => { From 49b33b63f97f1c49671ec7a715a2a494746db755 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Tue, 19 Sep 2023 16:07:06 +0530 Subject: [PATCH 09/70] refactor: remove test utils and validator bindings for now --- example/index.ts | 45 +- index.ts | 10 + instructions.md | 52 -- instructions.ts | 222 ------ serve.ts | 18 - src/Bindings/Repl.ts | 84 -- src/Bindings/TestUtils.ts | 35 - src/Bindings/Validator.ts | 277 ------- src/TestUtils/Migration.ts | 41 - src/TestUtils/Seeder.ts | 40 - src/TestUtils/Truncator.ts | 40 - src/bindings/repl.ts | 83 ++ src/define_config.ts | 14 + test/bindings/validator.spec.ts | 1313 ------------------------------- test/database-provider.spec.ts | 118 --- 15 files changed, 129 insertions(+), 2263 deletions(-) create mode 100644 index.ts delete mode 100644 instructions.md delete mode 100644 instructions.ts delete mode 100644 serve.ts delete mode 100644 src/Bindings/Repl.ts delete mode 100644 src/Bindings/TestUtils.ts delete mode 100644 src/Bindings/Validator.ts delete mode 100644 src/TestUtils/Migration.ts delete mode 100644 src/TestUtils/Seeder.ts delete mode 100644 src/TestUtils/Truncator.ts create mode 100644 src/bindings/repl.ts create mode 100644 src/define_config.ts delete mode 100644 test/bindings/validator.spec.ts delete mode 100644 test/database-provider.spec.ts diff --git a/example/index.ts b/example/index.ts index ddb852d9..280e7b8c 100644 --- a/example/index.ts +++ b/example/index.ts @@ -1,10 +1,9 @@ import { DateTime } from 'luxon' -import { BaseModel } from '../src/orm/base_model/index.js' +import { BaseModel, scope } from '../src/orm/base_model/index.js' import { column, hasOne } from '../src/orm/decorators/index.js' import { HasOne } from '../src/types/relations.js' -import { scope } from '../src/helpers/scope.js' import { ModelQueryBuilderContract } from '../src/types/model.js' -// import Factory from '@ioc:Adonis/Lucid/Factory' +import factory from '../src/factories/main.js' enum ProfileTypes { TWITTER = 'TWITTER', @@ -51,36 +50,36 @@ User.create({ id: '1', username: 'virk' }) User.create({ id: '1', username: 'virk' }) User.create({ id: '1' }) -// const F = Factory.define(User, ({ faker }) => { -// return { -// username: faker.internet.userName(), -// } -// }) +const F = factory.define(User, ({ faker }) => { + return { + username: faker.internet.userName(), + } +}) -// const P = Factory.define(Profile, () => { -// return {} -// }) +const P = factory.define(Profile, () => { + return {} +}) -// const ProfileF = P.state('social', () => {}).build() +const ProfileF = P.state('social', () => {}).build() -// const UserF = F.state('active', (user) => { -// user.username = 'virk' -// }) -// .relation('profile', () => ProfileF) -// .build() +const UserF = F.state('active', (user) => { + user.username = 'virk' +}) + .relation('profile', () => ProfileF) + .build() -// UserF.with('profile', 1).merge({}) +UserF.with('profile', 1).merge({}) User.query().withCount('profile', (query) => { query.where('isActive', true).has('user', '>', 1) }) User.query().withCount('profile') -// User.query() -// .paginate(1, 1) -// .then((users) => { -// users.forEach((user) => user.username) -// }) +User.query() + .paginate(1, 1) + .then((users) => { + users.forEach((user) => user.username) + }) const user = new User() user.loadCount('profile') diff --git a/index.ts b/index.ts new file mode 100644 index 00000000..be550147 --- /dev/null +++ b/index.ts @@ -0,0 +1,10 @@ +/* + * @adonisjs/lucid + * + * (c) AdonisJS + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +export { defineConfig } from './src/define_config.js' diff --git a/instructions.md b/instructions.md deleted file mode 100644 index f7308b21..00000000 --- a/instructions.md +++ /dev/null @@ -1,52 +0,0 @@ -The package has been configured successfully. The database configuration stored inside `config/database.ts` file relies on the following environment variables and hence we recommend validating them. - -**Open the `env.ts` file and paste the following code inside the `Env.rules` object.** - -```ts -DB_CONNECTION: Env.schema.string(), -``` - -## Variables for the MYSQL driver - -```ts -MYSQL_HOST: Env.schema.string({ format: 'host' }), -MYSQL_PORT: Env.schema.number(), -MYSQL_USER: Env.schema.string(), -MYSQL_PASSWORD: Env.schema.string.optional(), -MYSQL_DB_NAME: Env.schema.string(), -``` - -- The `MYSQL_HOST` should always be present and formatted as a valid `host`. -- The `MYSQL_PORT` should always be present and a valid number. -- The `MYSQL_USER` and `MYSQL_PASSWORD` are required to authenticate with the database server. The password is marked as optional since many local database servers are configured to work without passwords. -- The `MYSQL_DB_NAME` is the database name you want to connect with. - -## Variables for the PostgreSQL driver - -```ts -PG_HOST: Env.schema.string({ format: 'host' }), -PG_PORT: Env.schema.number(), -PG_USER: Env.schema.string(), -PG_PASSWORD: Env.schema.string.optional(), -PG_DB_NAME: Env.schema.string(), -``` - -## Variables for the MSSQL driver - -```ts -MSSQL_SERVER: Env.schema.string({ format: 'host' }), -MSSQL_PORT: Env.schema.number(), -MSSQL_USER: Env.schema.string(), -MSSQL_PASSWORD: Env.schema.string.optional(), -MSSQL_DB_NAME: Env.schema.string(), -``` - -## Variables for the OracleDB driver - -```ts -ORACLE_HOST: Env.schema.string({ format: 'host' }), -ORACLE_PORT: Env.schema.number(), -ORACLE_USER: Env.schema.string(), -ORACLE_PASSWORD: Env.schema.string.optional(), -ORACLE_DB_NAME: Env.schema.string(), -``` diff --git a/instructions.ts b/instructions.ts deleted file mode 100644 index 06d8dcc0..00000000 --- a/instructions.ts +++ /dev/null @@ -1,222 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -import { join } from 'path' -import { mkdirSync, existsSync } from 'fs' -import * as sinkStatic from '@adonisjs/sink' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -/** - * Prompt choices for the database server selection - */ -const DB_SERVER_PROMPT_CHOICES = [ - { - name: 'sqlite' as const, - message: 'SQLite', - }, - { - name: 'mysql' as const, - message: 'MySQL / MariaDB', - }, - { - name: 'pg' as const, - message: 'PostgreSQL', - }, - { - name: 'oracle' as const, - message: 'OracleDB', - }, - { - name: 'mssql' as const, - message: 'Microsoft SQL Server', - }, -] - -/** - * Environment variables used by different database - * drivers - */ -const DB_SERVER_ENV_VALUES = { - sqlite: {}, - mysql: { - MYSQL_HOST: 'localhost', - MYSQL_PORT: 3306, - MYSQL_USER: 'lucid', - MYSQL_PASSWORD: '', - MYSQL_DB_NAME: 'lucid', - }, - pg: { - PG_HOST: 'localhost', - PG_PORT: 5432, - PG_USER: 'lucid', - PG_PASSWORD: '', - PG_DB_NAME: 'lucid', - }, - oracle: { - ORACLE_HOST: 'localhost', - ORACLE_PORT: 1521, - ORACLE_USER: 'lucid', - ORACLE_PASSWORD: '', - ORACLE_DB_NAME: 'lucid', - }, - mssql: { - MSSQL_SERVER: 'localhost', - MSSQL_PORT: 1433, - MSSQL_USER: 'lucid', - MSSQL_PASSWORD: '', - MSSQL_DB_NAME: 'lucid', - }, -} - -/** - * Packages required by different drivers - */ -const DB_DRIVER_PACKAGES = { - sqlite: 'sqlite3', - mysql: 'mysql2', - pg: 'pg', - oracle: 'oracledb', - mssql: 'mssql', -} - -/** - * Prompts user for the drivers they want to use - */ -function getDbDrivers(sink: typeof sinkStatic) { - return sink - .getPrompt() - .multiple('Select the database driver you want to use', DB_SERVER_PROMPT_CHOICES, { - validate(choices) { - return choices && choices.length ? true : 'Select atleast one database driver to continue' - }, - }) -} - -/** - * Returns absolute path to the stub relative from the templates - * directory - */ -function getStub(...relativePaths: string[]) { - return join(__dirname, 'templates', ...relativePaths) -} - -/** - * Instructions to be executed when setting up the package. - */ -export default async function instructions( - projectRoot: string, - app: ApplicationContract, - sink: typeof sinkStatic -) { - /** - * Get drivers - */ - const drivers = await getDbDrivers(sink) - - /** - * Create Config file - */ - const configPath = app.configPath('database.ts') - const databaseConfig = new sink.files.MustacheFile( - projectRoot, - configPath, - getStub('database.txt') - ) - - databaseConfig.overwrite = true - databaseConfig - .apply({ - sqlite: drivers.includes('sqlite'), - mysql: drivers.includes('mysql'), - psql: drivers.includes('pg'), - oracle: drivers.includes('oracle'), - mssql: drivers.includes('mssql'), - }) - .commit() - const configDir = app.directoriesMap.get('config') || 'config' - sink.logger.action('create').succeeded(`${configDir}/database.ts`) - - /** - * Setup .env file - */ - const env = new sink.files.EnvFile(projectRoot) - env.set('DB_CONNECTION', drivers[0]) - - /** - * Unset old values - */ - Object.keys(DB_SERVER_ENV_VALUES).forEach((driver) => { - Object.keys(DB_SERVER_ENV_VALUES[driver]).forEach((key) => { - env.unset(key) - }) - }) - drivers.forEach((driver) => { - Object.keys(DB_SERVER_ENV_VALUES[driver]).forEach((key) => { - env.set(key, DB_SERVER_ENV_VALUES[driver][key]) - }) - }) - - env.commit() - sink.logger.action('update').succeeded('.env,.env.example') - - /** - * Create tmp dir when sqlite is selected - */ - if (drivers.includes('sqlite') && !existsSync(app.tmpPath())) { - mkdirSync(app.tmpPath()) - const tmpDir = app.directoriesMap.get('tmp') || 'tmp' - sink.logger.action('create').succeeded(`./${tmpDir}`) - } - - /** - * Install required dependencies - */ - const pkg = new sink.files.PackageJsonFile(projectRoot) - - /** - * Remove existing dependencies - */ - Object.keys(DB_DRIVER_PACKAGES).forEach((driver) => { - if (!drivers.includes(driver as any)) { - pkg.uninstall(DB_DRIVER_PACKAGES[driver], false) - } - }) - - pkg.install('luxon', undefined, false) - drivers.forEach((driver) => { - pkg.install(DB_DRIVER_PACKAGES[driver], undefined, false) - }) - - const logLines = [ - `Installing: ${sink.logger.colors.gray(pkg.getInstalls(false).list.join(', '))}`, - ] - - /** - * Find the list of packages we have to remove - */ - const packagesToRemove = pkg - .getUninstalls(false) - .list.filter((name) => pkg.get(`dependencies.${name}`)) - - if (packagesToRemove.length) { - logLines.push(`Removing: ${sink.logger.colors.gray(packagesToRemove.join(', '))}`) - } - - const spinner = sink.logger.await(logLines.join(' ')) - - try { - await pkg.commitAsync() - spinner.update('Packages installed') - } catch (error) { - spinner.update('Unable to install packages') - sink.logger.fatal(error) - } - - spinner.stop() -} diff --git a/serve.ts b/serve.ts deleted file mode 100644 index ebce0a83..00000000 --- a/serve.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { setup, cleanup } from './test-helpers' - -setup(false) - .then(() => { - console.log('Tables created') - console.log('They will be removed upon existing this script gracefully.') - process.on('SIGTERM', async () => { - await cleanup() - console.log('Dropping tables') - process.exit(1) - }) - process.on('SIGINT', async () => { - await cleanup() - console.log('Dropping tables') - process.exit(1) - }) - }) - .catch(console.log) diff --git a/src/Bindings/Repl.ts b/src/Bindings/Repl.ts deleted file mode 100644 index 1586267f..00000000 --- a/src/Bindings/Repl.ts +++ /dev/null @@ -1,84 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -import { ReplContract } from '@ioc:Adonis/Addons/Repl' -import { requireAll } from '@poppinss/utils/build/helpers' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -/** - * Helper to define REPL state - */ -function setupReplState(repl: any, key: string, value: any) { - repl.server.context[key] = value - repl.notify( - `Loaded ${key} module. You can access it using the "${repl.colors.underline(key)}" variable` - ) -} - -/** - * Define REPL bindings - */ -export function defineReplBindings(app: ApplicationContract, Repl: ReplContract) { - /** - * Load all models to the models property - */ - Repl.addMethod( - 'loadModels', - (repl) => { - const modelsPath = app.resolveNamespaceDirectory('models') || 'app/Models' - console.log(repl.colors.dim(`recursively reading models from "${modelsPath}"`)) - - const modelsAbsPath = app.makePath(modelsPath) - setupReplState(repl, 'models', requireAll(modelsAbsPath)) - }, - { - description: 'Recursively load Lucid models to the "models" property', - } - ) - - /** - * Load database provider to the Db provider - */ - Repl.addMethod( - 'loadDb', - (repl) => { - setupReplState(repl, 'Db', app.container.use('Adonis/Lucid/Database')) - }, - { - description: 'Load database provider to the "Db" property', - } - ) - - /** - * Load all factories to the factories property - */ - Repl.addMethod( - 'loadFactories', - (repl) => { - const factoriesPath = app.resolveNamespaceDirectory('factories') || 'database/factories' - console.log(repl.colors.dim(`recursively reading factories from "${factoriesPath}"`)) - - const factoriesAbsPath = app.makePath(factoriesPath) - const loadedFactories = requireAll(factoriesAbsPath) - - if (!loadedFactories) { - return - } - - setupReplState( - repl, - 'factories', - Object.values(loadedFactories).reduce((acc, items) => ({ ...acc, ...items }), {}) - ) - }, - { - description: 'Recursively load factories to the "factories" property', - } - ) -} diff --git a/src/Bindings/TestUtils.ts b/src/Bindings/TestUtils.ts deleted file mode 100644 index 61e0bcd7..00000000 --- a/src/Bindings/TestUtils.ts +++ /dev/null @@ -1,35 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -import type { TestUtilsContract } from '@ioc:Adonis/Core/TestUtils' - -import type Ace from '@ioc:Adonis/Core/Ace' - -import { TestsSeeder } from '../TestUtils/Seeder' -import { TestsMigrator } from '../TestUtils/Migration' -import { TestsTruncator } from '../TestUtils/Truncator' - -/** - * Define database testing utilities - */ -export function defineTestUtils(testUtils: TestUtilsContract, ace: typeof Ace) { - testUtils.constructor.macro('db', (connectionName?: string) => { - return { - migrate() { - return new TestsMigrator(ace, connectionName).run() - }, - seed() { - return new TestsSeeder(ace, connectionName).run() - }, - truncate() { - return new TestsTruncator(ace, connectionName).run() - }, - } - }) -} diff --git a/src/Bindings/Validator.ts b/src/Bindings/Validator.ts deleted file mode 100644 index 35ca03f3..00000000 --- a/src/Bindings/Validator.ts +++ /dev/null @@ -1,277 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -import { DateTime } from 'luxon' -import { Exception } from '@poppinss/utils' -import { LoggerContract } from '@ioc:Adonis/Core/Logger' -import { DatabaseContract, DatabaseQueryBuilderContract } from '@ioc:Adonis/Lucid/Database' -import { - DbRowCheckOptions, - ValidationRuntimeOptions, - validator as validatorStatic, -} from '@ioc:Adonis/Core/Validator' - -/** - * Shape of constraint after normalization - */ -type NormalizedConstraint = { - key: string - operator: 'in' | 'eq' - value?: string | string[] - ref?: string -} - -/** - * Normalized validation options - */ -type NormalizedOptions = Omit & { - where: NormalizedConstraint[] - whereNot: NormalizedConstraint[] -} - -/** - * Checks for database rows for `exists` and `unique` rule. - */ -class DbRowCheck { - constructor( - private ruleName: 'exists' | 'unique', - private database: DatabaseContract, - private helpers: (typeof validatorStatic)['helpers'] - ) {} - - /** - * Applies user defined where constraints on the query builder - */ - private applyWhere( - query: DatabaseQueryBuilderContract, - constraints: NormalizedConstraint[], - refs: ValidationRuntimeOptions['refs'] - ) { - if (!constraints.length) { - return - } - - constraints.forEach(({ key, operator, value, ref }) => { - const val = ref ? refs[ref].value : value - - if (operator === 'in') { - query.whereIn(key, val as string[]) - } else { - query.where(key, val as string) - } - }) - } - - /** - * Applies user defined where not constraints on the query builder - */ - private applyWhereNot( - query: DatabaseQueryBuilderContract, - constraints: NormalizedConstraint[], - refs: ValidationRuntimeOptions['refs'] - ) { - if (!constraints.length) { - return - } - - constraints.forEach(({ key, operator, value, ref }) => { - const val = ref ? refs[ref].value : value - - if (operator === 'in') { - query.whereNotIn(key, val as string[]) - } else { - query.whereNot(key, val as string) - } - }) - } - - /** - * Normalizes constraints - */ - private normalizeConstraints(constraints: DbRowCheckOptions['where']) { - const normalized: NormalizedConstraint[] = [] - if (!constraints) { - return normalized - } - - /** - * Normalize object into an array of objects - */ - return Object.keys(constraints).reduce((result, key) => { - const value = constraints[key] - - if (this.helpers.isRef(value)) { - result.push({ key, ref: value.key, operator: Array.isArray(value.value) ? 'in' : 'eq' }) - } else { - result.push({ key, value, operator: Array.isArray(value) ? 'in' : 'eq' }) - } - - return result - }, normalized) - } - - /** - * Compile validation options - */ - public compile(options: DbRowCheckOptions) { - /** - * Ensure options are defined with table and column name - */ - if (!options || !options.table || !options.column) { - throw new Exception(`"${this.ruleName}" rule expects a "table" and a "column" name`) - } - - /** - * Emit warning - */ - if (options.constraints) { - process.emitWarning( - 'DeprecationWarning', - '"options.constraints" have been depreciated. Use "options.where" instead.' - ) - } - - return { - table: options.table, - column: options.column, - caseInsensitive: !!options.caseInsensitive, - connection: options.connection, - dateFormat: options.dateFormat, - where: this.normalizeConstraints(options.where || options.constraints), - whereNot: this.normalizeConstraints(options.whereNot), - } - } - - /** - * Validate value - */ - public async validate( - value: any, - { table, column, where, whereNot, connection, caseInsensitive, dateFormat }: NormalizedOptions, - { pointer, errorReporter, arrayExpressionPointer, refs }: ValidationRuntimeOptions - ) { - const client = this.database.connection(connection) - const query = client.from(table).select(1) - - /** - * Convert datetime to a string - */ - if (DateTime.isDateTime(value)) { - const format = dateFormat || client.dialect.dateTimeFormat - value = value.toFormat(format) - } - - /** - * https://www.sqlite.org/lang_corefunc.html#lower - * https://docs.aws.amazon.com/redshift/latest/dg/r_LOWER.html - * https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_lower - * https://www.postgresql.org/docs/9.1/functions-string.html - * https://docs.microsoft.com/en-us/sql/t-sql/functions/lower-transact-sql?view=sql-server-ver15 - * https://coderwall.com/p/6yhsuq/improve-case-insensitive-queries-in-postgres-using-smarter-indexes - */ - if (caseInsensitive) { - query.whereRaw(`lower(${column}) = ?`, [this.database.raw(`lower(?)`, [value])]) - } else { - query.where(column, value) - } - - this.applyWhere(query, where, refs) - this.applyWhereNot(query, whereNot, refs) - - const row = await query.first() - if (this.ruleName === 'exists') { - if (!row) { - errorReporter.report( - pointer, - this.ruleName, - `${this.ruleName} validation failure`, - arrayExpressionPointer - ) - } - return - } - - if (this.ruleName === 'unique') { - if (row) { - errorReporter.report( - pointer, - this.ruleName, - `${this.ruleName} validation failure`, - arrayExpressionPointer - ) - } - return - } - } -} - -/** - * Extends the validator by adding `unique` and `exists` - */ -export function extendValidator( - validator: typeof validatorStatic, - database: DatabaseContract, - logger: LoggerContract -) { - /** - * Exists rule to ensure the value exists in the database - */ - const existsChecker = new DbRowCheck('exists', database, validator.helpers) - - validator.rule>( - 'exists', - async (value, compiledOptions, options) => { - try { - await existsChecker.validate(value, compiledOptions, options) - } catch (error) { - logger.fatal({ err: error }, '"exists" validation rule failed') - options.errorReporter.report( - options.pointer, - 'exists', - 'exists validation failure', - options.arrayExpressionPointer - ) - } - }, - (options) => { - return { - compiledOptions: existsChecker.compile(options[0]), - async: true, - } - } - ) - - /** - * Unique rule to check if value is unique or not - */ - const uniqueChecker = new DbRowCheck('unique', database, validator.helpers) - - validator.rule>( - 'unique', - async (value, compiledOptions, options) => { - try { - await uniqueChecker.validate(value, compiledOptions, options) - } catch (error) { - logger.fatal({ err: error }, '"unique" validation rule failed') - options.errorReporter.report( - options.pointer, - 'unique', - 'unique validation failure', - options.arrayExpressionPointer - ) - } - }, - (options) => { - return { - compiledOptions: uniqueChecker.compile(options[0]), - async: true, - } - } - ) -} diff --git a/src/TestUtils/Migration.ts b/src/TestUtils/Migration.ts deleted file mode 100644 index 3621d8e6..00000000 --- a/src/TestUtils/Migration.ts +++ /dev/null @@ -1,41 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -import type Ace from '@ioc:Adonis/Core/Ace' - -/** - * Migrator class to be used for testing. - */ -export class TestsMigrator { - constructor( - private ace: typeof Ace, - private connectionName?: string - ) {} - - private async runCommand(commandName: string) { - const args: string[] = ['--compact-output'] - if (this.connectionName) { - args.push(`--connection=${this.connectionName}`) - } - - const command = await this.ace.exec(commandName, args) - if (command.exitCode) { - if (command.error) { - throw command.error - } else { - throw new Error(`"${commandName}" failed`) - } - } - } - - public async run() { - await this.runCommand('migration:run') - return () => this.runCommand('migration:rollback') - } -} diff --git a/src/TestUtils/Seeder.ts b/src/TestUtils/Seeder.ts deleted file mode 100644 index 08fea7f3..00000000 --- a/src/TestUtils/Seeder.ts +++ /dev/null @@ -1,40 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -import type Ace from '@ioc:Adonis/Core/Ace' - -/** - * Seeder class to be used for testing - */ -export class TestsSeeder { - constructor( - private ace: typeof Ace, - private connectionName?: string - ) {} - - private async runCommand(commandName: string) { - const args: string[] = ['--compact-output'] - if (this.connectionName) { - args.push(`--connection=${this.connectionName}`) - } - - const command = await this.ace.exec(commandName, args) - if (command.exitCode) { - if (command.error) { - throw command.error - } else { - throw new Error(`"${commandName}" failed`) - } - } - } - - public async run() { - await this.runCommand('db:seed') - } -} diff --git a/src/TestUtils/Truncator.ts b/src/TestUtils/Truncator.ts deleted file mode 100644 index fe48bfc1..00000000 --- a/src/TestUtils/Truncator.ts +++ /dev/null @@ -1,40 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -import type Ace from '@ioc:Adonis/Core/Ace' - -/** - * Migrator class to be used for testing. - */ -export class TestsTruncator { - constructor( - private ace: typeof Ace, - private connectionName?: string - ) {} - - private async runCommand(commandName: string, args: string[] = []) { - if (this.connectionName) { - args.push(`--connection=${this.connectionName}`) - } - - const command = await this.ace.exec(commandName, args) - if (command.exitCode) { - if (command.error) { - throw command.error - } else { - throw new Error(`"${commandName}" failed`) - } - } - } - - public async run() { - await this.runCommand('migration:run', ['--compact-output']) - return () => this.runCommand('db:truncate') - } -} diff --git a/src/bindings/repl.ts b/src/bindings/repl.ts new file mode 100644 index 00000000..55e73cf7 --- /dev/null +++ b/src/bindings/repl.ts @@ -0,0 +1,83 @@ +/* + * @adonisjs/lucid + * + * (c) Harminder Virk + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import type { Repl } from '@adonisjs/core/repl' +import type { ApplicationService } from '@adonisjs/core/types' + +/** + * Helper to define REPL state + */ +function setupReplState(repl: any, key: string, value: any) { + repl.server.context[key] = value + repl.notify( + `Loaded ${key} module. You can access it using the "${repl.colors.underline(key)}" variable` + ) +} + +/** + * Define REPL bindings + */ +export function defineReplBindings(app: ApplicationService, Repl: Repl) { + /** + * Load all models to the models property + */ + Repl.addMethod( + 'loadModels', + async (repl) => { + const modelsPath = app.modelsPath() + console.log( + repl.colors.dim(`recursively reading models from "${app.relativePath(modelsPath)}"`) + ) + + const { fsImportAll } = await import('@poppinss/utils') + setupReplState(repl, 'models', await fsImportAll(modelsPath)) + }, + { + description: 'Recursively load Lucid models to the "models" property', + } + ) + + /** + * Load database provider to the Db provider + */ + Repl.addMethod( + 'loadDb', + async (repl) => { + setupReplState(repl, 'db', await app.container.make('lucid.db')) + }, + { + description: 'Load database provider to the "db" property', + } + ) + + /** + * Load all factories to the factories property + */ + Repl.addMethod( + 'loadFactories', + async (repl) => { + const factoriesPath = app.factoriesPath() + console.log( + repl.colors.dim(`recursively reading models from "${app.relativePath(factoriesPath)}"`) + ) + + const { fsImportAll } = await import('@poppinss/utils') + const factories = await fsImportAll(factoriesPath, { ignoreMissingRoot: true }) + + if (!factories) { + return + } + + setupReplState(repl, 'factories', factories) + }, + { + description: 'Recursively load factories to the "factories" property', + } + ) +} diff --git a/src/define_config.ts b/src/define_config.ts new file mode 100644 index 00000000..e33a159f --- /dev/null +++ b/src/define_config.ts @@ -0,0 +1,14 @@ +/* + * @adonisjs/lucid + * + * (c) AdonisJS + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import { DatabaseConfig } from './types/database.js' + +export function defineConfig(config: DatabaseConfig): DatabaseConfig { + return config +} diff --git a/test/bindings/validator.spec.ts b/test/bindings/validator.spec.ts deleted file mode 100644 index 154cc5ca..00000000 --- a/test/bindings/validator.spec.ts +++ /dev/null @@ -1,1313 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -/// - -import { test } from '@japa/runner' -import { rules } from '@adonisjs/validator/build/src/Rules' -import { schema } from '@adonisjs/validator/build/src/Schema' -import { extendValidator } from '../../src/Bindings/Validator' -import { validator } from '@adonisjs/validator/build/src/Validator' - -import { fs, getDb, setup, cleanup, resetTables, setupApplication } from '../../test-helpers' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' -import { DateTime } from 'luxon' - -let app: ApplicationContract -let db: ReturnType - -test.group('Validator | exists', (group) => { - group.setup(async () => { - app = await setupApplication() - db = getDb(app) - await setup() - extendValidator(validator, db, app.logger) - }) - - group.teardown(async () => { - await cleanup() - await db.manager.closeAll() - await fs.cleanup() - }) - - group.each.teardown(async () => { - await resetTables() - db.connection().getReadClient().removeAllListeners() - }) - - test("must fail when row doesn't exists in the table", async ({ assert }) => { - assert.plan(1) - - try { - await validator.validate({ - schema: schema.create({ - id: schema.number([ - rules.exists({ - table: 'users', - column: 'id', - }), - ]), - }), - data: { id: 1 }, - }) - } catch (error) { - assert.deepEqual(error.messages, { - id: ['exists validation failure'], - }) - } - }) - - test('work fine when row exists', async ({ assert }) => { - assert.plan(2) - - const [row] = await db - .table<{ id: string } | number>('users') - .returning('id') - .insert({ email: 'virk@adonisjs.com', username: 'virk' }) - - db.connection() - .getReadClient() - .on('query', ({ sql, bindings }) => { - const { sql: knexSql, bindings: knexBindings } = db - .connection() - .getReadClient() - .select(1) - .from('users') - .where('id', typeof row === 'number' ? row : row.id) - .limit(1) - .toSQL() - .toNative() - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - }) - - await validator.validate({ - schema: schema.create({ - id: schema.number([ - rules.exists({ - table: 'users', - column: 'id', - }), - ]), - }), - data: { id: typeof row === 'number' ? row : row.id }, - }) - }) - - test('add where contraints', async ({ assert }) => { - assert.plan(3) - - const [row] = await db - .table<{ id: string } | number>('users') - .returning('id') - .insert({ email: 'virk@adonisjs.com', username: 'virk' }) - - db.connection() - .getReadClient() - .on('query', ({ sql, bindings }) => { - const { sql: knexSql, bindings: knexBindings } = db - .connection() - .getReadClient() - .select(1) - .from('users') - .where('id', typeof row === 'number' ? row : row.id) - .where('username', 'nikk') - .limit(1) - .toSQL() - .toNative() - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - }) - - try { - await validator.validate({ - schema: schema.create({ - id: schema.number([ - rules.exists({ - table: 'users', - column: 'id', - where: { - username: 'nikk', - }, - }), - ]), - }), - data: { id: typeof row === 'number' ? row : row.id }, - }) - } catch (error) { - assert.deepEqual(error.messages, { - id: ['exists validation failure'], - }) - } - }) - - test('add where contraints with refs', async ({ assert }) => { - assert.plan(3) - - const [row] = await db - .table<{ id: string } | number>('users') - .returning('id') - .insert({ email: 'virk@adonisjs.com', username: 'virk' }) - - db.connection() - .getReadClient() - .on('query', ({ sql, bindings }) => { - const { sql: knexSql, bindings: knexBindings } = db - .connection() - .getReadClient() - .select(1) - .from('users') - .where('id', typeof row === 'number' ? row : row.id) - .where('username', 'nikk') - .limit(1) - .toSQL() - .toNative() - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - }) - - try { - const refs = schema.refs({ - username: 'nikk', - }) - - await validator.validate({ - refs, - schema: schema.create({ - id: schema.number([ - rules.exists({ - table: 'users', - column: 'id', - where: { - username: refs.username, - }, - }), - ]), - }), - data: { id: typeof row === 'number' ? row : row.id }, - }) - } catch (error) { - assert.deepEqual(error.messages, { - id: ['exists validation failure'], - }) - } - }) - - test('add wherein contraints', async ({ assert }) => { - assert.plan(3) - - const [row] = await db - .table<{ id: string } | number>('users') - .returning('id') - .insert({ email: 'virk@adonisjs.com', username: 'virk' }) - - db.connection() - .getReadClient() - .on('query', ({ sql, bindings }) => { - const { sql: knexSql, bindings: knexBindings } = db - .connection() - .getReadClient() - .select(1) - .from('users') - .where('id', typeof row === 'number' ? row : row.id) - .whereIn('username', ['nikk', 'romain']) - .limit(1) - .toSQL() - .toNative() - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - }) - - try { - await validator.validate({ - schema: schema.create({ - id: schema.number([ - rules.exists({ - table: 'users', - column: 'id', - where: { - username: ['nikk', 'romain'], - }, - }), - ]), - }), - data: { id: typeof row === 'number' ? row : row.id }, - }) - } catch (error) { - assert.deepEqual(error.messages, { - id: ['exists validation failure'], - }) - } - }) - - test('add wherein contraints with refs', async ({ assert }) => { - assert.plan(3) - - const [row] = await db - .table<{ id: string } | number>('users') - .returning('id') - .insert({ email: 'virk@adonisjs.com', username: 'virk' }) - - db.connection() - .getReadClient() - .on('query', ({ sql, bindings }) => { - const { sql: knexSql, bindings: knexBindings } = db - .connection() - .getReadClient() - .select(1) - .from('users') - .where('id', typeof row === 'number' ? row : row.id) - .whereIn('username', ['nikk', 'romain']) - .limit(1) - .toSQL() - .toNative() - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - }) - - try { - const refs = schema.refs({ - username: ['nikk', 'romain'], - }) - - await validator.validate({ - refs, - schema: schema.create({ - id: schema.number([ - rules.exists({ - table: 'users', - column: 'id', - where: { - username: refs.username, - }, - }), - ]), - }), - data: { id: typeof row === 'number' ? row : row.id }, - }) - } catch (error) { - assert.deepEqual(error.messages, { - id: ['exists validation failure'], - }) - } - }) - - test('add where not constraints', async ({ assert }) => { - assert.plan(3) - - const [row] = await db - .table<{ id: string } | number>('users') - .returning('id') - .insert({ email: 'virk@adonisjs.com', username: 'virk' }) - - db.connection() - .getReadClient() - .on('query', ({ sql, bindings }) => { - const { sql: knexSql, bindings: knexBindings } = db - .connection() - .getReadClient() - .select(1) - .from('users') - .where('id', typeof row === 'number' ? row : row.id) - .whereNot('username', 'virk') - .limit(1) - .toSQL() - .toNative() - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - }) - - try { - await validator.validate({ - schema: schema.create({ - id: schema.number([ - rules.exists({ - table: 'users', - column: 'id', - whereNot: { - username: 'virk', - }, - }), - ]), - }), - data: { id: typeof row === 'number' ? row : row.id }, - }) - } catch (error) { - assert.deepEqual(error.messages, { - id: ['exists validation failure'], - }) - } - }) - - test('add where not constraints with refs', async ({ assert }) => { - assert.plan(3) - - const [row] = await db - .table<{ id: string } | number>('users') - .returning('id') - .insert({ email: 'virk@adonisjs.com', username: 'virk' }) - - db.connection() - .getReadClient() - .on('query', ({ sql, bindings }) => { - const { sql: knexSql, bindings: knexBindings } = db - .connection() - .getReadClient() - .select(1) - .from('users') - .where('id', typeof row === 'number' ? row : row.id) - .whereNot('username', 'virk') - .limit(1) - .toSQL() - .toNative() - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - }) - - try { - const refs = schema.refs({ - username: 'virk', - }) - - await validator.validate({ - refs, - schema: schema.create({ - id: schema.number([ - rules.exists({ - table: 'users', - column: 'id', - whereNot: { - username: refs.username, - }, - }), - ]), - }), - data: { id: typeof row === 'number' ? row : row.id }, - }) - } catch (error) { - assert.deepEqual(error.messages, { - id: ['exists validation failure'], - }) - } - }) - - test('add where not in constraints', async ({ assert }) => { - assert.plan(3) - - const [row] = await db - .table<{ id: string } | number>('users') - .returning('id') - .insert({ email: 'virk@adonisjs.com', username: 'virk' }) - - db.connection() - .getReadClient() - .on('query', ({ sql, bindings }) => { - const { sql: knexSql, bindings: knexBindings } = db - .connection() - .getReadClient() - .select(1) - .from('users') - .where('id', typeof row === 'number' ? row : row.id) - .whereNotIn('username', ['virk', 'nikk']) - .limit(1) - .toSQL() - .toNative() - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - }) - - try { - await validator.validate({ - schema: schema.create({ - id: schema.number([ - rules.exists({ - table: 'users', - column: 'id', - whereNot: { - username: ['virk', 'nikk'], - }, - }), - ]), - }), - data: { id: typeof row === 'number' ? row : row.id }, - }) - } catch (error) { - assert.deepEqual(error.messages, { - id: ['exists validation failure'], - }) - } - }) - - test('add where not in constraints with refs', async ({ assert }) => { - assert.plan(3) - - const [row] = await db - .table<{ id: string } | number>('users') - .returning('id') - .insert({ email: 'virk@adonisjs.com', username: 'virk' }) - - db.connection() - .getReadClient() - .on('query', ({ sql, bindings }) => { - const { sql: knexSql, bindings: knexBindings } = db - .connection() - .getReadClient() - .select(1) - .from('users') - .where('id', typeof row === 'number' ? row : row.id) - .whereNotIn('username', ['virk', 'nikk']) - .limit(1) - .toSQL() - .toNative() - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - }) - - try { - const refs = schema.refs({ - username: ['virk', 'nikk'], - }) - - await validator.validate({ - refs, - schema: schema.create({ - id: schema.number([ - rules.exists({ - table: 'users', - column: 'id', - whereNot: { - username: refs.username, - }, - }), - ]), - }), - data: { id: typeof row === 'number' ? row : row.id }, - }) - } catch (error) { - assert.deepEqual(error.messages, { - id: ['exists validation failure'], - }) - } - }) - - test('perform case-insensitive query', async ({ assert }) => { - assert.plan(2) - - await db.table('users').returning('id').insert({ email: 'virk@adonisjs.com', username: 'virk' }) - - db.connection() - .getReadClient() - .on('query', ({ sql, bindings }) => { - const { sql: knexSql, bindings: knexBindings } = db - .connection() - .getReadClient() - .select(1) - .from('users') - .whereRaw(`lower(username) = ?`, [db.connection().knexRawQuery(`lower(?)`, ['VIRK'])]) - .limit(1) - .toSQL() - .toNative() - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - }) - - await validator.validate({ - schema: schema.create({ - username: schema.string({}, [ - rules.exists({ - table: 'users', - caseInsensitive: true, - column: 'username', - }), - ]), - }), - data: { username: 'VIRK' }, - }) - }) - - test('do not report SQL errors to the validator', async ({ assert }) => { - assert.plan(1) - - try { - await validator.validate({ - schema: schema.create({ - username: schema.string({}, [ - rules.exists({ - table: 'invalid_users', - caseInsensitive: true, - column: 'username', - }), - ]), - }), - data: { username: 'VIRK' }, - }) - } catch (error) { - assert.deepEqual(error.messages, { - username: ['exists validation failure'], - }) - } - }) - - test('make correct sql query schema field is of date type', async ({ assert }) => { - assert.plan(3) - - let sql: any - let bindings: any - let knexSql: any - let knexBindings: any - - db.connection() - .getReadClient() - .on('query', (query) => { - sql = query.sql - bindings = query.bindings - - const client = db.connection() - - const knexQuery = client - .getReadClient() - .select(1) - .from('users') - .where( - 'created_at', - DateTime.fromISO('2020-10-20').toFormat(client.dialect.dateTimeFormat) - ) - .limit(1) - .toSQL() - .toNative() - - knexSql = knexQuery.sql - knexBindings = knexQuery.bindings - }) - - try { - await validator.validate({ - schema: schema.create({ - id: schema.date({}, [ - rules.exists({ - table: 'users', - column: 'created_at', - }), - ]), - }), - data: { id: '2020-10-20' }, - }) - } catch (error) { - assert.deepEqual(error.messages, { - id: ['exists validation failure'], - }) - } - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - }) - - test('define custom format datetime values', async ({ assert }) => { - assert.plan(3) - - let sql: any - let bindings: any - let knexSql: any - let knexBindings: any - - db.connection() - .getReadClient() - .on('query', (query) => { - sql = query.sql - bindings = query.bindings - - const knexQuery = db - .connection() - .getReadClient() - .select(1) - .from('users') - .where('created_at', '2020-10-20') - .limit(1) - .toSQL() - .toNative() - - knexSql = knexQuery.sql - knexBindings = knexQuery.bindings - }) - - try { - await validator.validate({ - schema: schema.create({ - id: schema.date({}, [ - rules.exists({ - table: 'users', - dateFormat: 'yyyy-LL-dd', - column: 'created_at', - }), - ]), - }), - data: { id: '2020-10-20' }, - }) - } catch (error) { - assert.deepEqual(error.messages, { - id: ['exists validation failure'], - }) - } - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - }) -}) - -test.group('Validator | unique', (group) => { - group.setup(async () => { - app = await setupApplication() - db = getDb(app) - await setup() - extendValidator(validator, db, app.logger) - }) - - group.teardown(async () => { - await cleanup() - await db.manager.closeAll() - await fs.cleanup() - }) - - group.each.teardown(async () => { - await resetTables() - db.connection().getReadClient().removeAllListeners() - }) - - test('must fail when row already exists in the table', async ({ assert }) => { - assert.plan(1) - - const [row] = await db - .table<{ id: string } | number>('users') - .returning('id') - .insert({ email: 'virk@adonisjs.com', username: 'virk' }) - - try { - await validator.validate({ - schema: schema.create({ - id: schema.number([ - rules.unique({ - table: 'users', - column: 'id', - }), - ]), - }), - data: { id: typeof row === 'number' ? row : row.id }, - }) - } catch (error) { - assert.deepEqual(error.messages, { - id: ['unique validation failure'], - }) - } - }) - - test('work fine when row is missing', async () => { - await validator.validate({ - schema: schema.create({ - id: schema.number([ - rules.unique({ - table: 'users', - column: 'id', - }), - ]), - }), - data: { id: 1 }, - }) - }) - - test('add where contraints', async ({ assert }) => { - assert.plan(3) - - const [row] = await db - .table<{ id: string } | number>('users') - .returning('id') - .insert({ email: 'virk@adonisjs.com', username: 'virk' }) - - db.connection() - .getReadClient() - .on('query', ({ sql, bindings }) => { - const { sql: knexSql, bindings: knexBindings } = db - .connection() - .getReadClient() - .select(1) - .from('users') - .where('id', typeof row === 'number' ? row : row.id) - .where('username', 'virk') - .limit(1) - .toSQL() - .toNative() - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - }) - - try { - await validator.validate({ - schema: schema.create({ - id: schema.number([ - rules.unique({ - table: 'users', - column: 'id', - where: { - username: 'virk', - }, - }), - ]), - }), - data: { id: typeof row === 'number' ? row : row.id }, - }) - } catch (error) { - assert.deepEqual(error.messages, { - id: ['unique validation failure'], - }) - } - }) - - test('add where contraints with refs', async ({ assert }) => { - assert.plan(3) - - const [row] = await db - .table<{ id: string } | number>('users') - .returning('id') - .insert({ email: 'virk@adonisjs.com', username: 'virk' }) - - db.connection() - .getReadClient() - .on('query', ({ sql, bindings }) => { - const { sql: knexSql, bindings: knexBindings } = db - .connection() - .getReadClient() - .select(1) - .from('users') - .where('id', typeof row === 'number' ? row : row.id) - .where('username', 'virk') - .limit(1) - .toSQL() - .toNative() - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - }) - - try { - const refs = schema.refs({ - username: 'virk', - }) - - await validator.validate({ - refs, - schema: schema.create({ - id: schema.number([ - rules.unique({ - table: 'users', - column: 'id', - where: { - username: refs.username, - }, - }), - ]), - }), - data: { id: typeof row === 'number' ? row : row.id }, - }) - } catch (error) { - assert.deepEqual(error.messages, { - id: ['unique validation failure'], - }) - } - }) - - test('add where in contraints', async ({ assert }) => { - assert.plan(3) - - const [row] = await db - .table<{ id: string } | number>('users') - .returning('id') - .insert({ email: 'virk@adonisjs.com', username: 'virk' }) - - db.connection() - .getReadClient() - .on('query', ({ sql, bindings }) => { - const { sql: knexSql, bindings: knexBindings } = db - .connection() - .getReadClient() - .select(1) - .from('users') - .where('id', typeof row === 'number' ? row : row.id) - .whereIn('username', ['virk', 'nikk']) - .limit(1) - .toSQL() - .toNative() - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - }) - - try { - await validator.validate({ - schema: schema.create({ - id: schema.number([ - rules.unique({ - table: 'users', - column: 'id', - where: { - username: ['virk', 'nikk'], - }, - }), - ]), - }), - data: { id: typeof row === 'number' ? row : row.id }, - }) - } catch (error) { - assert.deepEqual(error.messages, { - id: ['unique validation failure'], - }) - } - }) - - test('add where in contraints with refs', async ({ assert }) => { - assert.plan(3) - - const [row] = await db - .table<{ id: string } | number>('users') - .returning('id') - .insert({ email: 'virk@adonisjs.com', username: 'virk' }) - - db.connection() - .getReadClient() - .on('query', ({ sql, bindings }) => { - const { sql: knexSql, bindings: knexBindings } = db - .connection() - .getReadClient() - .select(1) - .from('users') - .where('id', typeof row === 'number' ? row : row.id) - .whereIn('username', ['virk', 'nikk']) - .limit(1) - .toSQL() - .toNative() - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - }) - - try { - const refs = schema.refs({ - username: ['virk', 'nikk'], - }) - - await validator.validate({ - refs, - schema: schema.create({ - id: schema.number([ - rules.unique({ - table: 'users', - column: 'id', - where: { - username: refs.username, - }, - }), - ]), - }), - data: { id: typeof row === 'number' ? row : row.id }, - }) - } catch (error) { - assert.deepEqual(error.messages, { - id: ['unique validation failure'], - }) - } - }) - - test('add whereNot contraints', async ({ assert }) => { - assert.plan(3) - - const [row] = await db - .table<{ id: string } | number>('users') - .returning('id') - .insert({ email: 'virk@adonisjs.com', username: 'virk' }) - - db.connection() - .getReadClient() - .on('query', ({ sql, bindings }) => { - const { sql: knexSql, bindings: knexBindings } = db - .connection() - .getReadClient() - .select(1) - .from('users') - .where('id', typeof row === 'number' ? row : row.id) - .whereNot('username', 'nikk') - .limit(1) - .toSQL() - .toNative() - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - }) - - try { - await validator.validate({ - schema: schema.create({ - id: schema.number([ - rules.unique({ - table: 'users', - column: 'id', - whereNot: { - username: 'nikk', - }, - }), - ]), - }), - data: { id: typeof row === 'number' ? row : row.id }, - }) - } catch (error) { - assert.deepEqual(error.messages, { - id: ['unique validation failure'], - }) - } - }) - - test('add whereNot contraints with refs', async ({ assert }) => { - assert.plan(3) - - const [row] = await db - .table<{ id: string } | number>('users') - .returning('id') - .insert({ email: 'virk@adonisjs.com', username: 'virk' }) - - db.connection() - .getReadClient() - .on('query', ({ sql, bindings }) => { - const { sql: knexSql, bindings: knexBindings } = db - .connection() - .getReadClient() - .select(1) - .from('users') - .where('id', typeof row === 'number' ? row : row.id) - .whereNot('username', 'nikk') - .limit(1) - .toSQL() - .toNative() - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - }) - - try { - const refs = schema.refs({ - username: 'nikk', - }) - - await validator.validate({ - refs, - schema: schema.create({ - id: schema.number([ - rules.unique({ - table: 'users', - column: 'id', - whereNot: { - username: refs.username, - }, - }), - ]), - }), - data: { id: typeof row === 'number' ? row : row.id }, - }) - } catch (error) { - assert.deepEqual(error.messages, { - id: ['unique validation failure'], - }) - } - }) - - test('add whereNot in contraints', async ({ assert }) => { - assert.plan(3) - - const [row] = await db - .table<{ id: string } | number>('users') - .returning('id') - .insert({ email: 'virk@adonisjs.com', username: 'virk', country_id: 4 }) - - db.connection() - .getReadClient() - .on('query', ({ sql, bindings }) => { - const { sql: knexSql, bindings: knexBindings } = db - .connection() - .getReadClient() - .select(1) - .from('users') - .where('id', typeof row === 'number' ? row : row.id) - .whereNotIn('country_id', [1, 2]) - .limit(1) - .toSQL() - .toNative() - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - }) - - try { - await validator.validate({ - schema: schema.create({ - id: schema.number([ - rules.unique({ - table: 'users', - column: 'id', - whereNot: { - country_id: [1, 2], - }, - }), - ]), - }), - data: { id: typeof row === 'number' ? row : row.id }, - }) - } catch (error) { - assert.deepEqual(error.messages, { - id: ['unique validation failure'], - }) - } - }) - - test('add whereNot in contraints with refs', async ({ assert }) => { - assert.plan(3) - - const [row] = await db - .table<{ id: string } | number>('users') - .returning('id') - .insert({ email: 'virk@adonisjs.com', username: 'virk', country_id: 4 }) - - db.connection() - .getReadClient() - .on('query', ({ sql, bindings }) => { - const { sql: knexSql, bindings: knexBindings } = db - .connection() - .getReadClient() - .select(1) - .from('users') - .where('id', typeof row === 'number' ? row : row.id) - .whereNotIn('country_id', [1, 2]) - .limit(1) - .toSQL() - .toNative() - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - }) - - try { - const refs = schema.refs({ - country: [1, 2], - }) - - await validator.validate({ - refs, - schema: schema.create({ - id: schema.number([ - rules.unique({ - table: 'users', - column: 'id', - whereNot: { - country_id: refs.country, - }, - }), - ]), - }), - data: { id: typeof row === 'number' ? row : row.id }, - }) - } catch (error) { - assert.deepEqual(error.messages, { - id: ['unique validation failure'], - }) - } - }) - - test('perform case-insensitive check', async ({ assert }) => { - assert.plan(3) - - await db.table('users').returning('id').insert({ email: 'virk@adonisjs.com', username: 'virk' }) - db.connection() - .getReadClient() - .on('query', ({ sql, bindings }) => { - const { sql: knexSql, bindings: knexBindings } = db - .connection() - .getReadClient() - .select(1) - .from('users') - .whereRaw(`lower(username) = ?`, [db.connection().knexRawQuery(`lower(?)`, ['VIRK'])]) - .limit(1) - .toSQL() - .toNative() - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - }) - - try { - await validator.validate({ - schema: schema.create({ - username: schema.string({}, [ - rules.unique({ - table: 'users', - column: 'username', - caseInsensitive: true, - }), - ]), - }), - data: { username: 'VIRK' }, - }) - } catch (error) { - assert.deepEqual(error.messages, { - username: ['unique validation failure'], - }) - } - }) - - test('do not report SQL errors to the validator', async ({ assert }) => { - assert.plan(1) - - try { - await validator.validate({ - schema: schema.create({ - username: schema.string({}, [ - rules.unique({ - table: 'invalid_users', - column: 'username', - caseInsensitive: true, - }), - ]), - }), - data: { username: 'VIRK' }, - }) - } catch (error) { - assert.deepEqual(error.messages, { - username: ['unique validation failure'], - }) - } - }) - - test('make correct sql query schema field is of date type', async ({ assert }) => { - assert.plan(3) - - await db - .table('users') - .insert({ email: 'virk@adonisjs.com', username: 'virk', created_at: '2020-10-20 00:00:00' }) - - let sql: any - let bindings: any - let knexSql: any - let knexBindings: any - - db.connection() - .getReadClient() - .on('query', (query) => { - sql = query.sql - bindings = query.bindings - - const client = db.connection() - - const knexQuery = client - .getReadClient() - .select(1) - .from('users') - .where( - 'created_at', - DateTime.fromISO('2020-10-20').toFormat(client.dialect.dateTimeFormat) - ) - .limit(1) - .toSQL() - .toNative() - - knexSql = knexQuery.sql - knexBindings = knexQuery.bindings - }) - - try { - await validator.validate({ - schema: schema.create({ - id: schema.date({}, [ - rules.unique({ - table: 'users', - column: 'created_at', - }), - ]), - }), - data: { id: '2020-10-20' }, - }) - } catch (error) { - assert.deepEqual(error.messages, { - id: ['unique validation failure'], - }) - } - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - }) - - test('define custom format datetime values', async ({ assert }) => { - assert.plan(3) - - await db - .table('users') - .insert({ email: 'virk@adonisjs.com', username: 'virk', created_at: '2020-10-20' }) - - let sql: any - let bindings: any - let knexSql: any - let knexBindings: any - - db.connection() - .getReadClient() - .on('query', (query) => { - sql = query.sql - bindings = query.bindings - - const knexQuery = db - .connection() - .getReadClient() - .select(1) - .from('users') - .where('created_at', '2020-10-20') - .limit(1) - .toSQL() - .toNative() - - knexSql = knexQuery.sql - knexBindings = knexQuery.bindings - }) - - try { - await validator.validate({ - schema: schema.create({ - id: schema.date({}, [ - rules.unique({ - table: 'users', - dateFormat: 'yyyy-LL-dd', - column: 'created_at', - }), - ]), - }), - data: { id: '2020-10-20' }, - }) - } catch (error) { - assert.deepEqual(error.messages, { - id: ['unique validation failure'], - }) - } - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - }) -}) diff --git a/test/database-provider.spec.ts b/test/database-provider.spec.ts deleted file mode 100644 index b1b2f23c..00000000 --- a/test/database-provider.spec.ts +++ /dev/null @@ -1,118 +0,0 @@ -/* - * @adonisjs/session - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -import { test } from '@japa/runner' - -import { Database } from '../src/Database' -import { scope } from '../src/Helpers/scope' -import { BaseSeeder } from '../src/BaseSeeder' -import { FactoryManager } from '../src/Factory' -import { BaseModel } from '../src/Orm/BaseModel' -import { ModelPaginator } from '../src/Orm/Paginator' -import * as decorators from '../src/Orm/Decorators' -import { SnakeCaseNamingStrategy } from '../src/Orm/NamingStrategies/SnakeCase' - -import { setupApplication, fs } from '../test-helpers' - -test.group('Database Provider', (group) => { - group.each.teardown(async () => { - await fs.cleanup() - }) - - test('register database provider', async ({ assert }) => { - const app = await setupApplication( - { - connection: 'sqlite', - connections: { - sqlite: {}, - }, - }, - ['../../providers/DatabaseProvider'] - ) - - assert.instanceOf(app.container.use('Adonis/Lucid/Database'), Database) - assert.deepEqual(app.container.use('Adonis/Lucid/Orm'), { - BaseModel, - ModelPaginator, - SnakeCaseNamingStrategy, - scope, - ...decorators, - }) - assert.isTrue(app.container.hasBinding('Adonis/Lucid/Schema')) - assert.instanceOf(app.container.use('Adonis/Lucid/Factory'), FactoryManager) - assert.deepEqual(app.container.use('Adonis/Lucid/Seeder'), BaseSeeder) - }) - - test('register health checker', async ({ assert }) => { - const app = await setupApplication( - { - connection: 'sqlite', - connections: { - sqlite: { - healthCheck: true, - }, - }, - }, - ['../../providers/DatabaseProvider'] - ) - - const HealthCheck = app.container.use('Adonis/Core/HealthCheck') - assert.equal(HealthCheck['healthCheckers']['lucid'], 'Adonis/Lucid/Database') - }) - - test('register validator rules', async ({ assert }) => { - const app = await setupApplication( - { - connection: 'sqlite', - connections: { - sqlite: {}, - }, - }, - ['../../providers/DatabaseProvider'] - ) - - const Validator = app.container.use('Adonis/Core/Validator') - assert.property(Validator['rules'], 'unique') - assert.property(Validator['rules'], 'exists') - }) - - test('register repl bindings in repl environment', async ({ assert }) => { - const app = await setupApplication( - { - connection: 'sqlite', - connections: { - sqlite: {}, - }, - }, - ['../../providers/DatabaseProvider'], - 'repl' - ) - - const Repl = app.container.use('Adonis/Addons/Repl') - assert.property(Repl['customMethods'], 'loadModels') - assert.property(Repl['customMethods'], 'loadDb') - }) - - test('register test utils', async ({ assert }) => { - const app = await setupApplication( - { - connection: 'sqlite', - connections: { - sqlite: { - healthCheck: true, - }, - }, - }, - ['../../providers/DatabaseProvider'] - ) - - const TestUtils = app.container.use('Adonis/Core/TestUtils') - assert.properties(TestUtils.db(), ['seed', 'migrate']) - }) -}) From 3a219a663e29b983ccddb4610e8ceab000832bf1 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Tue, 19 Sep 2023 16:20:12 +0530 Subject: [PATCH 10/70] test: fix breaking tests --- src/database/paginator/simple_paginator.ts | 2 +- src/types/relations.ts | 1 + test/commands/migration/fresh.spec.ts | 4 +- test/commands/migration/refresh.spec.ts | 8 +- test/commands/migration/reset.spec.ts | 2 +- test/commands/migration/run.spec.ts | 16 +-- test/migrations/migrator.spec.ts | 58 +++++------ test/orm/base_model.spec.ts | 115 ++------------------- test/orm/model_has_many_through.spec.ts | 11 +- 9 files changed, 59 insertions(+), 158 deletions(-) diff --git a/src/database/paginator/simple_paginator.ts b/src/database/paginator/simple_paginator.ts index 72afda9c..d9cae8b8 100644 --- a/src/database/paginator/simple_paginator.ts +++ b/src/database/paginator/simple_paginator.ts @@ -9,7 +9,7 @@ import { stringify } from 'qs' import { SimplePaginatorContract, SimplePaginatorMetaKeys } from '../../types/querybuilder.js' -import { SnakeCaseNamingStrategy } from '../../Orm/naming_strategies/snake_case.js' +import { SnakeCaseNamingStrategy } from '../../orm/naming_strategies/snake_case.js' /** * Simple paginator works with the data set provided by the standard diff --git a/src/types/relations.ts b/src/types/relations.ts index 49f2ebcb..c05dc1dd 100644 --- a/src/types/relations.ts +++ b/src/types/relations.ts @@ -470,6 +470,7 @@ export interface ManyToManyRelationContract< readonly pivotTable: string pivotColumns: string[] relatedKeyColumnName: string + localKeyColumnName: string /** * Set related models as a relationship on the parent model diff --git a/test/commands/migration/fresh.spec.ts b/test/commands/migration/fresh.spec.ts index 67d0e6cb..7598fd4b 100644 --- a/test/commands/migration/fresh.spec.ts +++ b/test/commands/migration/fresh.spec.ts @@ -32,7 +32,7 @@ test.group('migrate:fresh', (group) => { await fs.create( 'database/migrations/fresh_cmd_users.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -87,7 +87,7 @@ test.group('migrate:fresh', (group) => { await fs.create( 'database/migrations/fresh_cmd_users_v1.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { diff --git a/test/commands/migration/refresh.spec.ts b/test/commands/migration/refresh.spec.ts index 5ffde438..c3f4e9fc 100644 --- a/test/commands/migration/refresh.spec.ts +++ b/test/commands/migration/refresh.spec.ts @@ -31,7 +31,7 @@ test.group('migration:refresh', (group) => { await fs.create( 'database/migrations/refresh_cmd_users.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -49,7 +49,7 @@ test.group('migration:refresh', (group) => { await fs.create( 'database/migrations/refresh_cmd_posts.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class Account extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -100,7 +100,7 @@ test.group('migration:refresh', (group) => { await fs.create( 'database/migrations/refres_cmd_users_v1.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -118,7 +118,7 @@ test.group('migration:refresh', (group) => { await fs.create( 'database/migrations/posts.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class Account extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { diff --git a/test/commands/migration/reset.spec.ts b/test/commands/migration/reset.spec.ts index ee9f6e97..6098ea75 100644 --- a/test/commands/migration/reset.spec.ts +++ b/test/commands/migration/reset.spec.ts @@ -31,7 +31,7 @@ test.group('migration:reset', (group) => { await fs.create( 'database/migrations/reset_cmd_users.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { diff --git a/test/commands/migration/run.spec.ts b/test/commands/migration/run.spec.ts index c46ed5d2..b5938325 100644 --- a/test/commands/migration/run.spec.ts +++ b/test/commands/migration/run.spec.ts @@ -33,7 +33,7 @@ test.group('migration:run', (group) => { await fs.create( 'database/migrations/run_cmd_users.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -80,7 +80,7 @@ test.group('migration:run', (group) => { await fs.create( 'database/migrations/run_cmd_users_v1.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -114,7 +114,7 @@ test.group('migration:run', (group) => { await fs.create( 'database/migrations/run_cmd_users_v2.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -160,7 +160,7 @@ test.group('migration:run', (group) => { await fs.create( 'database/migrations/run_cmd_users_v3.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -198,7 +198,7 @@ test.group('migration:run', (group) => { await fs.create( 'database/migrations/run_cmd_users_v4.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { @@ -213,7 +213,7 @@ test.group('migration:run', (group) => { await fs.create( 'database/migrations/run_cmd_clients_v4.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class Client extends Schema { public async up () { @@ -243,7 +243,7 @@ test.group('migration:run', (group) => { await fs.create( 'database/migrations/run_cmd_users_v5.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { @@ -258,7 +258,7 @@ test.group('migration:run', (group) => { await fs.create( 'database/migrations/run_cmd_clients_v5.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class Client extends Schema { public async up () { diff --git a/test/migrations/migrator.spec.ts b/test/migrations/migrator.spec.ts index 2d2718a7..2d0a08db 100644 --- a/test/migrations/migrator.spec.ts +++ b/test/migrations/migrator.spec.ts @@ -62,7 +62,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v1.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -115,7 +115,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v2.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -130,7 +130,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v2.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -190,7 +190,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v3.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -204,7 +204,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v3.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -277,7 +277,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v4.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -291,7 +291,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v4.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -351,7 +351,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v5.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -368,7 +368,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v5.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -411,7 +411,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v6.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -432,7 +432,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v6.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -489,7 +489,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v7.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -510,7 +510,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v7.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -563,7 +563,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v8.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -584,7 +584,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v8.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -648,7 +648,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v9.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -669,7 +669,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v9.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -751,7 +751,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v10.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -772,7 +772,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v10.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -839,7 +839,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v11.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -857,7 +857,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v11.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -907,7 +907,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v12.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -925,7 +925,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v12.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -961,7 +961,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v13.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -975,7 +975,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v13.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -1165,7 +1165,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v14.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -1187,7 +1187,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v14.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -1236,7 +1236,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v15.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -1299,7 +1299,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v16.ts', ` - import { Schema } from '../../../../src/schema/index.js' + import { Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { diff --git a/test/orm/base_model.spec.ts b/test/orm/base_model.spec.ts index 1b957808..afb1910e 100644 --- a/test/orm/base_model.spec.ts +++ b/test/orm/base_model.spec.ts @@ -49,12 +49,10 @@ import { sleep, cleanup as cleanupTables, } from '../../test-helpers/index.js' +import { LucidRow } from '../../src/types/model.js' import { ModelPaginator } from '../../src/orm/paginator/index.js' -import { QueryClientContract } from '../../src/types/database.js' import { SimplePaginator } from '../../src/database/paginator/simple_paginator.js' -import { InsertQueryBuilderContract } from '../../src/types/querybuilder.js' import { SnakeCaseNamingStrategy } from '../../src/orm/naming_strategies/snake_case.js' -import { ModelQueryBuilderContract, LucidModel, LucidRow } from '../../src/types/model.js' test.group('Base model | boot', (group) => { group.setup(async () => { @@ -402,7 +400,7 @@ test.group('Base Model | getter-setters', (group) => { class User extends BaseModel { @column() - public set username(value: any) { + set username(value: any) { this.$setAttribute('username', value.toUpperCase()) } } @@ -462,7 +460,7 @@ test.group('Base Model | getter-setters', (group) => { class User extends BaseModel { @column() - public get username() { + get username() { return this.$getAttribute('username').toUpperCase() } } @@ -522,7 +520,7 @@ test.group('Base Model | getter-setters', (group) => { class User extends BaseModel { @column({ isPrimary: true }) - public get id() { + get id() { return String(this.$getAttribute('id')) } @@ -546,7 +544,7 @@ test.group('Base Model | getter-setters', (group) => { class User extends BaseModel { @column({ isPrimary: true }) - public get id() { + get id() { return String(this.$getAttribute('id')) } @@ -574,11 +572,11 @@ test.group('Base Model | getter-setters', (group) => { class User extends BaseModel { @column() - public get preferences(): object { + get preferences(): object { return this.$getAttribute('preferences') } - public set preferences(value: object) { + set preferences(value: object) { this.$setAttribute('preferences', lodash.merge(this.preferences, value)) } } @@ -782,7 +780,7 @@ test.group('Base Model | dirty', (group) => { const BaseModel = getBaseModel(adapter, app) class Location { - public isDirty = false + isDirty = false constructor( public state: string, public country: string @@ -797,7 +795,7 @@ test.group('Base Model | dirty', (group) => { declare age: number @column() - public location: any + location: any } User.$adapter = adapter @@ -5622,101 +5620,6 @@ test.group('Base Model | hooks', (group) => { }) }) -test.group('Base model | extend', (group) => { - group.setup(async () => { - await setup() - }) - - group.teardown(async () => { - await cleanupTables() - }) - - test('extend model query builder', async ({ fs, assert }) => { - const app = new AppFactory().create(fs.baseUrl, () => {}) - await app.init() - const db = getDb() - const adapter = ormAdapter(db) - - const BaseModel = getBaseModel(adapter, app) - - class User extends BaseModel { - @column({ isPrimary: true }) - declare id: number - - @column() - declare username: string - } - User.boot() - - db.ModelQueryBuilder.macro('whereActive', function () { - this.where('is_active', true) - return this - }) - - const knexClient = db.connection().getReadClient() - const { sql, bindings } = User.query()['whereActive']().toSQL() - const { sql: knexSql, bindings: knexBindings } = knexClient - .from('users') - .where('is_active', true) - .toSQL() - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - }) - - test('extend model insert query builder', async ({ fs, assert }) => { - const app = new AppFactory().create(fs.baseUrl, () => {}) - await app.init() - const db = getDb() - const adapter = ormAdapter(db) - - const BaseModel = getBaseModel(adapter, app) - - class User extends BaseModel { - @column({ isPrimary: true }) - declare id: number - - @column() - declare username: string - - $getQueryFor( - action: 'insert', - client: QueryClientContract - ): InsertQueryBuilderContract - $getQueryFor( - action: 'update' | 'delete' | 'refresh', - client: QueryClientContract - ): ModelQueryBuilderContract - $getQueryFor( - _: 'insert' | 'update' | 'delete' | 'refresh', - client: QueryClientContract - ): InsertQueryBuilderContract | ModelQueryBuilderContract { - return client.insertQuery().table('users').withId() - } - } - User.boot() - - db.InsertQueryBuilder.macro('withId', function (this: InsertQueryBuilderContract) { - this.knexQuery.returning('id') - return this - }) - - const knexClient = db.connection().getReadClient() - const user = new User() - - const { sql, bindings } = user.$getQueryFor('insert', db.connection()).insert({ id: 1 }).toSQL() - - const { sql: knexSql, bindings: knexBindings } = knexClient - .from('users') - .returning('id') - .insert({ id: 1 }) - .toSQL() - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - }) -}) - test.group('Base Model | aggregates', (group) => { group.setup(async () => { await setup() diff --git a/test/orm/model_has_many_through.spec.ts b/test/orm/model_has_many_through.spec.ts index 415b3f27..751a544f 100644 --- a/test/orm/model_has_many_through.spec.ts +++ b/test/orm/model_has_many_through.spec.ts @@ -58,7 +58,7 @@ test.group('Model | Has Many Through | Options', (group) => { } catch ({ message }) { assert.equal( message, - 'E_MISSING_MODEL_ATTRIBUTE: "Country.posts" expects "id" to exist on "Country" model, but is missing' + '"Country.posts" expects "id" to exist on "Country" model, but is missing' ) } }) @@ -92,7 +92,7 @@ test.group('Model | Has Many Through | Options', (group) => { } catch ({ message }) { assert.equal( message, - 'E_MISSING_MODEL_ATTRIBUTE: "Country.posts" expects "countryId" to exist on "User" model, but is missing' + '"Country.posts" expects "countryId" to exist on "User" model, but is missing' ) } }) @@ -127,10 +127,7 @@ test.group('Model | Has Many Through | Options', (group) => { Country.boot() Country.$getRelation('posts')!.boot() } catch ({ message }) { - assert.equal( - message, - 'E_MISSING_MODEL_ATTRIBUTE: "Country.posts" expects "id" to exist on "User" model, but is missing' - ) + assert.equal(message, '"Country.posts" expects "id" to exist on "User" model, but is missing') } }) @@ -169,7 +166,7 @@ test.group('Model | Has Many Through | Options', (group) => { } catch ({ message }) { assert.equal( message, - 'E_MISSING_MODEL_ATTRIBUTE: "Country.posts" expects "userId" to exist on "Post" model, but is missing' + '"Country.posts" expects "userId" to exist on "Post" model, but is missing' ) } }) From 1417942906435800436c0c1cfb8fc03897afc11a Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Tue, 19 Sep 2023 17:28:03 +0530 Subject: [PATCH 11/70] feat: add configure instructions --- commands/index.ts | 24 --- commands/migration/{base.ts => _base.ts} | 0 commands/migration/rollback.ts | 2 +- commands/migration/run.ts | 2 +- configure.ts | 131 +++++++++++++++++ index.ts | 2 + package.json | 24 ++- stubs/config.stub | 71 +++++++++ stubs/database.txt | 177 ----------------------- stubs/seeder.txt | 7 - test-helpers/index.ts | 7 +- test/configure.spec.ts | 107 ++++++++++++++ 12 files changed, 339 insertions(+), 215 deletions(-) delete mode 100644 commands/index.ts rename commands/migration/{base.ts => _base.ts} (100%) create mode 100644 configure.ts create mode 100644 stubs/config.stub delete mode 100644 stubs/database.txt delete mode 100644 stubs/seeder.txt create mode 100644 test/configure.spec.ts diff --git a/commands/index.ts b/commands/index.ts deleted file mode 100644 index e0bcead3..00000000 --- a/commands/index.ts +++ /dev/null @@ -1,24 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -export default [ - '@adonisjs/lucid/build/commands/DbSeed', - '@adonisjs/lucid/build/commands/DbWipe', - '@adonisjs/lucid/build/commands/DbTruncate', - '@adonisjs/lucid/build/commands/MakeModel', - '@adonisjs/lucid/build/commands/MakeMigration', - '@adonisjs/lucid/build/commands/MakeSeeder', - '@adonisjs/lucid/build/commands/MakeFactory', - '@adonisjs/lucid/build/commands/Migration/Run', - '@adonisjs/lucid/build/commands/Migration/Rollback', - '@adonisjs/lucid/build/commands/Migration/Status', - '@adonisjs/lucid/build/commands/Migration/Reset', - '@adonisjs/lucid/build/commands/Migration/Refresh', - '@adonisjs/lucid/build/commands/Migration/Fresh', -] diff --git a/commands/migration/base.ts b/commands/migration/_base.ts similarity index 100% rename from commands/migration/base.ts rename to commands/migration/_base.ts diff --git a/commands/migration/rollback.ts b/commands/migration/rollback.ts index 9e373acf..e177bddd 100644 --- a/commands/migration/rollback.ts +++ b/commands/migration/rollback.ts @@ -9,7 +9,7 @@ import { flags } from '@adonisjs/core/ace' -import MigrationsBase from './base.js' +import MigrationsBase from './_base.js' import { MigrationRunner } from '../../src/migration/runner.js' /** diff --git a/commands/migration/run.ts b/commands/migration/run.ts index 7366140c..f3d428ef 100644 --- a/commands/migration/run.ts +++ b/commands/migration/run.ts @@ -8,7 +8,7 @@ */ import { flags } from '@adonisjs/core/ace' -import MigrationsBase from './base.js' +import MigrationsBase from './_base.js' import { MigrationRunner } from '../../src/migration/runner.js' /** diff --git a/configure.ts b/configure.ts new file mode 100644 index 00000000..835bb53e --- /dev/null +++ b/configure.ts @@ -0,0 +1,131 @@ +/* + * @adonisjs/lucid + * + * (c) AdonisJS + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import type Configure from '@adonisjs/core/commands/configure' + +/** + * We only allow configuring the one's thoroughly tested + * inside the Lucid codebase. Knex supports more and one + * can reference knex docs to configure additional + * dialects. + */ +const DIALECTS = ['sqlite', 'mysql', 'postgres', 'mssql'] as const +const DIALECTS_INFO: { + [K in (typeof DIALECTS)[number]]: { + envVars?: Record + envValidations?: Record + pkg: string + } +} = { + sqlite: { + pkg: 'sqlite3', + }, + mysql: { + pkg: 'mysql2', + envVars: { + DB_HOST: '127.0.0.1', + DB_PORT: 3306, + DB_USER: 'root', + DB_PASSWORD: '', + DB_DATABASE: '', + }, + envValidations: { + DB_HOST: `Env.schema.string({ format: 'host' })`, + DB_PORT: `Env.schema.number()`, + DB_USER: 'Env.schema.string()', + DB_PASSWORD: 'Env.schema.string()', + DB_DATABASE: 'Env.schema.string()', + }, + }, + postgres: { + envVars: { + DB_HOST: '127.0.0.1', + DB_PORT: 5432, + DB_USER: 'postgres', + DB_PASSWORD: '', + DB_DATABASE: '', + }, + envValidations: { + DB_HOST: `Env.schema.string({ format: 'host' })`, + DB_PORT: `Env.schema.number()`, + DB_USER: 'Env.schema.string()', + DB_PASSWORD: 'Env.schema.string()', + DB_DATABASE: 'Env.schema.string()', + }, + pkg: 'pg', + }, + mssql: { + envVars: { + DB_HOST: '127.0.0.1', + DB_PORT: 1433, + DB_USER: 'sa', + DB_PASSWORD: '', + DB_DATABASE: '', + }, + envValidations: { + DB_HOST: `Env.schema.string({ format: 'host' })`, + DB_PORT: `Env.schema.number()`, + DB_USER: 'Env.schema.string()', + DB_PASSWORD: 'Env.schema.string()', + DB_DATABASE: 'Env.schema.string()', + }, + pkg: 'tedious', + }, +} + +/** + * Configures the package + */ +export async function configure(command: Configure) { + const codemods = await command.createCodemods() + await codemods.updateRcFile((rcFile) => { + rcFile.addProvider('@adonisjs/lucid/database_provider') + }) + + /** + * Prompt to select the dialect to use + */ + const dialect = + (await command.prompt.choice('Select the database you want to use', DIALECTS, { + hint: 'You can always change it later', + })) || 'postgres' + + const { pkg, envVars, envValidations } = DIALECTS_INFO[dialect] + + /** + * Define environment variables + */ + if (envVars) { + codemods.defineEnvVariables(envVars) + } + + /** + * Define environment validations + */ + if (envValidations) { + codemods.defineEnvValidations({ + variables: envValidations, + leadingComment: 'Variables for configuring ally package', + }) + } + + /** + * Publish config + */ + await command.publishStub('config.stub', { dialect: dialect }) + + /** + * Prompt to install package + */ + if (await command.prompt.confirm(`Do you want to install npm package "${pkg}"?`)) { + await command.installPackages([{ name: pkg, isDevDependency: false }]) + } else { + command.listPackagesToInstall([{ name: pkg, isDevDependency: false }]) + } +} diff --git a/index.ts b/index.ts index be550147..c0d9fb6e 100644 --- a/index.ts +++ b/index.ts @@ -7,4 +7,6 @@ * file that was distributed with this source code. */ +export { configure } from './configure.js' +export { stubsRoot } from './stubs/main.js' export { defineConfig } from './src/define_config.js' diff --git a/package.json b/package.json index 6aee925e..3d3adfb7 100644 --- a/package.json +++ b/package.json @@ -5,15 +5,28 @@ "engines": { "node": ">=18.16.0" }, + "files": [ + "build/commands", + "build/providers", + "build/services", + "build/src", + "build/stubs", + "build/index.d.ts", + "build/index.js", + "build/configure.d.ts", + "build/configure.js" + ], "type": "module", "exports": { "./schema": "./build/src/schema/main.js", + "./commands": "./build/commands/main.js", "./factories": "./build/src/factories/main.js", "./database": "./build/src/database/main.js", "./orm": "./build/src/orm/main.js", "./seeders": "./build/src/seeders/main.js", "./services/*": "./build/services/*.js", - "./types/*": "./build/types/*.js" + "./types/*": "./build/types/*.js", + "./database_provider": "./build/providers/database_provider.js" }, "scripts": { "pretest": "npm run lint", @@ -26,8 +39,9 @@ "test:docker": "npm run test:mysql && npm run test:mysql_legacy && npm run test:pg && npm run test:mssql", "lint": "eslint . --ext=.ts", "clean": "del-cli build", - "compile": "npm run lint && npm run clean && tsc && npm run copyfiles", - "copyfiles": "copyfiles \"templates/**/*.txt\" \"instructions.md\" build", + "compile": "npm run lint && npm run clean && tsc", + "postcompile": "npm run copy:templates && npm run index:commands", + "copy:templates": "copyfiles \"stubs/**/**/*.stub\" build", "build": "npm run compile", "release": "np", "version": "npm run build", @@ -35,7 +49,8 @@ "sync-labels": "github-label-sync --labels ./node_modules/@adonisjs/mrm-preset/gh-labels.json adonisjs/lucid", "format": "prettier --write .", "prepublishOnly": "npm run build", - "test": "c8 npm run test:docker" + "test": "c8 npm run test:docker", + "index:commands": "adonis-kit index build/commands" }, "dependencies": { "@faker-js/faker": "^8.0.1", @@ -53,6 +68,7 @@ "tarn": "^3.0.2" }, "devDependencies": { + "@adonisjs/assembler": "^6.1.3-22", "@adonisjs/core": "^6.1.5-26", "@adonisjs/eslint-config": "^1.1.8", "@adonisjs/prettier-config": "^1.1.8", diff --git a/stubs/config.stub b/stubs/config.stub new file mode 100644 index 00000000..e14263fc --- /dev/null +++ b/stubs/config.stub @@ -0,0 +1,71 @@ +--- +to: {{ app.configPath('database.ts') }} +--- +import env from '#start/env' +import app from '@adonisjs/core/services/app' +import { defineConfig } from '@adonisjs/lucid' + +const allyConfig = defineConfig({ + connection: '{{ dialect }}', + + connections: { + {{#if dialect === 'sqlite'}} + sqlite: { + client: 'sqlite', + connection: { + filename: app.tmpPath('db.sqlite3') + }, + useNullAsDefault: true, + migrations: { + naturalSort: true, + paths: ['database/migrations'], + }, + } + {{#elif dialect === 'postgres'}} + postgres: { + client: 'pg', + connection: { + host: env.get('DB_HOST'), + port: env.get('DB_PORT'), + user: env.get('DB_USER'), + password: env.get('DB_PASSWORD'), + database: env.get('DB_DATABASE'), + }, + migrations: { + naturalSort: true, + paths: ['database/migrations'], + } + } + {{#elif dialect === 'mysql'}} + mysql: { + client: 'mysql2', + connection: { + host: env.get('DB_HOST'), + port: env.get('DB_PORT'), + user: env.get('DB_USER'), + password: env.get('DB_PASSWORD'), + database: env.get('DB_DATABASE'), + }, + migrations: { + naturalSort: true, + paths: ['database/migrations'], + } + } + {{#elif dialect === 'mssql'}} + mssql: { + client: 'tedious', + connection: { + server: env.get('DB_HOST'), + port: env.get('DB_PORT'), + user: env.get('DB_USER'), + password: env.get('DB_PASSWORD'), + database: env.get('DB_DATABASE'), + }, + migrations: { + naturalSort: true, + paths: ['database/migrations'], + } + } + {{/if}} + } +}) diff --git a/stubs/database.txt b/stubs/database.txt deleted file mode 100644 index fa8be808..00000000 --- a/stubs/database.txt +++ /dev/null @@ -1,177 +0,0 @@ -/** - * Config source: https://git.io/JesV9 - * - * Feel free to let us know via PR, if you find something broken in this config - * file. - */ - -import Env from '@ioc:Adonis/Core/Env' -{{#sqlite}} -import Application from '@ioc:Adonis/Core/Application' -{{/sqlite}} -import type { DatabaseConfig } from '@ioc:Adonis/Lucid/Database' - -const databaseConfig: DatabaseConfig = { - /* - |-------------------------------------------------------------------------- - | Connection - |-------------------------------------------------------------------------- - | - | The primary connection for making database queries across the application - | You can use any key from the `connections` object defined in this same - | file. - | - */ - connection: Env.get('DB_CONNECTION'), - - connections: { - {{#sqlite}} - /* - |-------------------------------------------------------------------------- - | SQLite - |-------------------------------------------------------------------------- - | - | Configuration for the SQLite database. Make sure to install the driver - | from npm when using this connection - | - | npm i sqlite3 - | - */ - sqlite: { - client: 'sqlite', - connection: { - filename: Application.tmpPath('db.sqlite3'), - }, - pool: { - afterCreate: (conn, cb) => { - conn.run('PRAGMA foreign_keys=true', cb) - } - }, - migrations: { - naturalSort: true, - }, - useNullAsDefault: true, - healthCheck: false, - debug: false, - }, - - {{/sqlite}} - {{#mysql}} - /* - |-------------------------------------------------------------------------- - | MySQL config - |-------------------------------------------------------------------------- - | - | Configuration for MySQL database. Make sure to install the driver - | from npm when using this connection - | - | npm i mysql2 - | - */ - mysql: { - client: 'mysql2', - connection: { - host: Env.get('MYSQL_HOST'), - port: Env.get('MYSQL_PORT'), - user: Env.get('MYSQL_USER'), - password: Env.get('MYSQL_PASSWORD', ''), - database: Env.get('MYSQL_DB_NAME'), - }, - migrations: { - naturalSort: true, - }, - healthCheck: false, - debug: false, - }, - - {{/mysql}} - {{#psql}} - /* - |-------------------------------------------------------------------------- - | PostgreSQL config - |-------------------------------------------------------------------------- - | - | Configuration for PostgreSQL database. Make sure to install the driver - | from npm when using this connection - | - | npm i pg - | - */ - pg: { - client: 'pg', - connection: { - host: Env.get('PG_HOST'), - port: Env.get('PG_PORT'), - user: Env.get('PG_USER'), - password: Env.get('PG_PASSWORD', ''), - database: Env.get('PG_DB_NAME'), - }, - migrations: { - naturalSort: true, - }, - healthCheck: false, - debug: false, - }, - - {{/psql}} - {{#oracle}} - /* - |-------------------------------------------------------------------------- - | OracleDB config - |-------------------------------------------------------------------------- - | - | Configuration for Oracle database. Make sure to install the driver - | from npm when using this connection - | - | npm i oracledb - | - */ - oracle: { - client: 'oracledb', - connection: { - host: Env.get('ORACLE_HOST'), - port: Env.get('ORACLE_PORT'), - user: Env.get('ORACLE_USER'), - password: Env.get('ORACLE_PASSWORD', ''), - database: Env.get('ORACLE_DB_NAME'), - }, - migrations: { - naturalSort: true, - }, - healthCheck: false, - debug: false, - }, - - {{/oracle}} - {{#mssql}} - /* - |-------------------------------------------------------------------------- - | MSSQL config - |-------------------------------------------------------------------------- - | - | Configuration for MSSQL database. Make sure to install the driver - | from npm when using this connection - | - | npm i tedious - | - */ - mssql: { - client: 'mssql', - connection: { - user: Env.get('MSSQL_USER'), - port: Env.get('MSSQL_PORT'), - server: Env.get('MSSQL_SERVER'), - password: Env.get('MSSQL_PASSWORD', ''), - database: Env.get('MSSQL_DB_NAME'), - }, - migrations: { - naturalSort: true, - }, - healthCheck: false, - debug: false, - } - {{/mssql}} - } -} - -export default databaseConfig diff --git a/stubs/seeder.txt b/stubs/seeder.txt deleted file mode 100644 index a06b3f4e..00000000 --- a/stubs/seeder.txt +++ /dev/null @@ -1,7 +0,0 @@ -import BaseSeeder from '@ioc:Adonis/Lucid/Seeder' - -export default class extends BaseSeeder { - public async run () { - // Write your database queries inside the run method - } -} diff --git a/test-helpers/index.ts b/test-helpers/index.ts index a1406e15..4e0243be 100644 --- a/test-helpers/index.ts +++ b/test-helpers/index.ts @@ -16,7 +16,12 @@ import { Logger } from '@adonisjs/core/logger' import { Emitter } from '@adonisjs/core/events' import { AppFactory } from '@adonisjs/core/factories/app' -import { ConnectionConfig, ConnectionContract, DatabaseConfig, QueryClientContract } from '../src/types/database.js' +import { + ConnectionConfig, + ConnectionContract, + DatabaseConfig, + QueryClientContract, +} from '../src/types/database.js' import { RawQueryBuilderContract, diff --git a/test/configure.spec.ts b/test/configure.spec.ts new file mode 100644 index 00000000..125ed701 --- /dev/null +++ b/test/configure.spec.ts @@ -0,0 +1,107 @@ +/* + * @adonisjs/lucid + * + * (c) AdonisJS + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import { test } from '@japa/runner' +import { fileURLToPath } from 'node:url' +import { IgnitorFactory } from '@adonisjs/core/factories' +import Configure from '@adonisjs/core/commands/configure' + +const BASE_URL = new URL('./tmp/', import.meta.url) + +test.group('Configure', (group) => { + group.each.setup(({ context }) => { + context.fs.baseUrl = BASE_URL + context.fs.basePath = fileURLToPath(BASE_URL) + }) + + test('create config file and register provider', async ({ fs, assert }) => { + const ignitor = new IgnitorFactory() + .withCoreProviders() + .withCoreConfig() + .create(BASE_URL, { + importer: (filePath) => { + if (filePath.startsWith('./') || filePath.startsWith('../')) { + return import(new URL(filePath, BASE_URL).href) + } + + return import(filePath) + }, + }) + + const app = ignitor.createApp('web') + await app.init() + await app.boot() + + await fs.create('.env', '') + await fs.createJson('tsconfig.json', {}) + await fs.create('start/env.ts', `export default Env.create(new URL('./'), {})`) + await fs.create('adonisrc.ts', `export default defineConfig({})`) + + const ace = await app.container.make('ace') + ace.prompt.trap('Select the database you want to use').chooseOption(2) + ace.prompt.trap('Do you want to install npm package "pg"?').reject() + + const command = await ace.create(Configure, ['../../index.js']) + await command.exec() + + await assert.fileExists('config/database.ts') + await assert.fileExists('adonisrc.ts') + await assert.fileContains('adonisrc.ts', '@adonisjs/lucid/database_provider') + await assert.fileContains('config/database.ts', 'defineConfig({') + + await assert.fileContains('.env', 'DB_HOST') + await assert.fileContains('.env', 'DB_PORT') + await assert.fileContains('.env', 'DB_USER') + await assert.fileContains('.env', 'DB_PASSWORD') + await assert.fileContains('.env', 'DB_DATABASE') + + await assert.fileContains('start/env.ts', `DB_HOST: Env.schema.string({ format: 'host' })`) + await assert.fileContains('start/env.ts', 'DB_PORT: Env.schema.number()') + await assert.fileContains('start/env.ts', 'DB_USER: Env.schema.string()') + await assert.fileContains('start/env.ts', 'DB_PASSWORD: Env.schema.string()') + await assert.fileContains('start/env.ts', 'DB_DATABASE: Env.schema.string()') + }).timeout(6000) + + test('do not define env vars for sqlite dialect', async ({ fs, assert }) => { + const ignitor = new IgnitorFactory() + .withCoreProviders() + .withCoreConfig() + .create(BASE_URL, { + importer: (filePath) => { + if (filePath.startsWith('./') || filePath.startsWith('../')) { + return import(new URL(filePath, BASE_URL).href) + } + + return import(filePath) + }, + }) + + const app = ignitor.createApp('web') + await app.init() + await app.boot() + + await fs.createJson('tsconfig.json', {}) + await fs.create('adonisrc.ts', `export default defineConfig({})`) + + const ace = await app.container.make('ace') + ace.prompt.trap('Select the database you want to use').chooseOption(0) + ace.prompt.trap('Do you want to install npm package "sqlite3"?').reject() + + const command = await ace.create(Configure, ['../../index.js']) + await command.exec() + + await assert.fileExists('config/database.ts') + await assert.fileExists('adonisrc.ts') + await assert.fileContains('adonisrc.ts', '@adonisjs/lucid/database_provider') + await assert.fileContains('config/database.ts', 'defineConfig({') + + await assert.fileNotExists('.env') + await assert.fileNotExists('start/env.ts') + }).timeout(6000) +}) From 9472db97eeea6d40485b442d539172494664b343 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Tue, 19 Sep 2023 17:40:49 +0530 Subject: [PATCH 12/70] ci: fix env vars --- .github/workflows/test.yml | 18 +++++++++++++---- test-helpers/index.ts | 40 +++++++++++++------------------------- 2 files changed, 28 insertions(+), 30 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 096083b8..a61b7ffa 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -35,9 +35,11 @@ jobs: postgres: image: postgres:${{ matrix.postgres-version }} env: - POSTGRES_DB: lucid - POSTGRES_USER: virk - POSTGRES_PASSWORD: password + PG_HOST: localhost + PG_PASSWORD: secret + PG_DATABASE: lucid + PG_PORT: 5432 + PG_USER: virk ports: - 5432:5432 steps: @@ -61,9 +63,17 @@ jobs: mysql: image: mysql:${{ matrix.mysql.version }} env: + MYSQL_HOST: localhost + MYSQL_PASSWORD: secret MYSQL_DATABASE: lucid + MYSQL_PORT: 3306 MYSQL_USER: virk - MYSQL_PASSWORD: password + MYSQL_ROOT_PASSWORD: password + LEGACY_MYSQL_HOST: localhost + LEGACY_MYSQL_PASSWORD: secret + LEGACY_MYSQL_DATABASE: lucid + LEGACY_MYSQL_PORT: 3306 + LEGACY_MYSQL_USER: virk MYSQL_ROOT_PASSWORD: password ports: - '3306:3306' diff --git a/test-helpers/index.ts b/test-helpers/index.ts index 4e0243be..fafd3c90 100644 --- a/test-helpers/index.ts +++ b/test-helpers/index.ts @@ -8,18 +8,20 @@ */ import dotenv from 'dotenv' -import { join } from 'node:path' import { Chance } from 'chance' +import { join } from 'node:path' import knex, { Knex } from 'knex' +import { fileURLToPath } from 'node:url' import { getActiveTest } from '@japa/runner' import { Logger } from '@adonisjs/core/logger' import { Emitter } from '@adonisjs/core/events' +import { Application } from '@adonisjs/core/app' import { AppFactory } from '@adonisjs/core/factories/app' import { + DatabaseConfig, ConnectionConfig, ConnectionContract, - DatabaseConfig, QueryClientContract, } from '../src/types/database.js' @@ -29,31 +31,17 @@ import { DatabaseQueryBuilderContract, } from '../src/types/querybuilder.js' -import { MigratorOptions } from '../src/types/migrator.js' -import { LucidRow, LucidModel, AdapterContract } from '../src/types/model.js' - -import { fileURLToPath } from 'node:url' -import { QueryClient } from '../src/query_client/index.js' +import { Schema } from '../src/schema/main.js' import { Database } from '../src/database/main.js' -import { DatabaseQueryBuilder } from '../src/database/query_builder/database.js' +import { Adapter } from '../src/orm/adapter/index.js' +import { BaseModel } from '../src/orm/base_model/index.js' +import { QueryClient } from '../src/query_client/index.js' +import { MigratorOptions } from '../src/types/migrator.js' +import { MigrationRunner } from '../src/migration/runner.js' import { RawQueryBuilder } from '../src/database/query_builder/raw.js' import { InsertQueryBuilder } from '../src/database/query_builder/insert.js' -import { MigrationRunner } from '../src/migration/runner.js' -import { Application } from '@adonisjs/core/app' -import { Schema } from '../src/schema/main.js' -import { BaseModel } from '../src/orm/base_model/index.js' -import { Adapter } from '../src/orm/adapter/index.js' - -// import { Schema } from '../src/Schema' -// import { Migrator } from '../src/Migrator' -// import { Adapter } from '../src/Orm/Adapter' -// import { Database } from '../src/Database/index' -// import { QueryClient } from '../src/QueryClient' -// import { BaseModel } from '../src/Orm/BaseModel' -// import { FactoryModel } from '../src/Factory/FactoryModel' -// import { RawQueryBuilder } from '../src/Database/QueryBuilder/Raw' -// import { InsertQueryBuilder } from '../src/Database/QueryBuilder/Insert' -// import { DatabaseQueryBuilder } from '../src/Database/QueryBuilder/Database' +import { LucidRow, LucidModel, AdapterContract } from '../src/types/model.js' +import { DatabaseQueryBuilder } from '../src/database/query_builder/database.js' dotenv.config() export const APP_ROOT = new URL('./tmp', import.meta.url) @@ -136,9 +124,9 @@ export function getConfig(): ConnectionConfig { return { client: 'mssql', connection: { - user: process.env.MSSQL_USER as string, - port: Number(process.env.MSSQL_PORT! as string), server: process.env.MSSQL_HOST as string, + port: Number(process.env.MSSQL_PORT! as string), + user: process.env.MSSQL_USER as string, password: process.env.MSSQL_PASSWORD as string, database: 'master', options: { From cabefba04e89b218e12acc139c133803f1d4c447 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Tue, 19 Sep 2023 17:42:20 +0530 Subject: [PATCH 13/70] ci: fix env vars --- .github/workflows/test.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index a61b7ffa..c0240802 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -74,7 +74,6 @@ jobs: LEGACY_MYSQL_DATABASE: lucid LEGACY_MYSQL_PORT: 3306 LEGACY_MYSQL_USER: virk - MYSQL_ROOT_PASSWORD: password ports: - '3306:3306' steps: From 25d6e87001faa110246947f7b092b5f3c5865c74 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Tue, 19 Sep 2023 17:48:07 +0530 Subject: [PATCH 14/70] fix: env variables --- .env | 17 ----------------- .github/workflows/test.yml | 20 ++++++-------------- 2 files changed, 6 insertions(+), 31 deletions(-) diff --git a/.env b/.env index b2c94830..3e9e75cb 100644 --- a/.env +++ b/.env @@ -4,12 +4,6 @@ LEGACY_MYSQL_DATABASE=lucid LEGACY_MYSQL_PORT=3306 LEGACY_MYSQL_USER=virk -LEGACY_MYSQL_READ_REPLICA_HOST=localhost -LEGACY_MYSQL_READ_REPLICA_PASSWORD=secret -LEGACY_MYSQL_READ_REPLICA_DATABASE=lucid -LEGACY_MYSQL_READ_REPLICA_PORT=3307 -LEGACY_MYSQL_READ_REPLICA_USER=virk - MYSQL_HOST=localhost MYSQL_PASSWORD=secret MYSQL_DATABASE=lucid @@ -22,18 +16,7 @@ PG_DATABASE=lucid PG_PORT=5432 PG_USER=virk -PG_READ_REPLICA_HOST=localhost -PG_READ_REPLICA_PASSWORD=secret -PG_READ_REPLICA_DATABASE=lucid -PG_READ_REPLICA_PORT=5433 -PG_READ_REPLICA_USER=virk - MSSQL_HOST=localhost MSSQL_PASSWORD=secrearandom&233passwordt MSSQL_PORT=1433 MSSQL_USER=sa - -MSSQL_READ_REPLICA_HOST=localhost -MSSQL_READ_REPLICA_PASSWORD=secrearandom&233passwordt -MSSQL_READ_REPLICA_PORT=1434 -MSSQL_READ_REPLICA_USER=sa diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c0240802..052844d3 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -35,11 +35,9 @@ jobs: postgres: image: postgres:${{ matrix.postgres-version }} env: - PG_HOST: localhost - PG_PASSWORD: secret - PG_DATABASE: lucid - PG_PORT: 5432 - PG_USER: virk + POSTGRES_DB: lucid + POSTGRES_USER: virk + POSTGRES_PASSWORD: secret ports: - 5432:5432 steps: @@ -63,17 +61,11 @@ jobs: mysql: image: mysql:${{ matrix.mysql.version }} env: - MYSQL_HOST: localhost - MYSQL_PASSWORD: secret MYSQL_DATABASE: lucid - MYSQL_PORT: 3306 MYSQL_USER: virk - MYSQL_ROOT_PASSWORD: password - LEGACY_MYSQL_HOST: localhost - LEGACY_MYSQL_PASSWORD: secret - LEGACY_MYSQL_DATABASE: lucid - LEGACY_MYSQL_PORT: 3306 - LEGACY_MYSQL_USER: virk + MYSQL_PASSWORD: secret + MYSQL_ROOT_PASSWORD: secret + MYSQL_PORT: 3306 ports: - '3306:3306' steps: From f41bd1772a0cfc62e98f5d7d054c7f59d011e5ca Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Tue, 19 Sep 2023 17:53:42 +0530 Subject: [PATCH 15/70] fix: path for sqlite and mssql db password --- .github/workflows/test.yml | 3 ++- .gitignore | 3 --- test-helpers/tmp/.gitignore | 1 + 3 files changed, 3 insertions(+), 4 deletions(-) create mode 100644 test-helpers/tmp/.gitignore diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 052844d3..5a12ddd4 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -68,6 +68,7 @@ jobs: MYSQL_PORT: 3306 ports: - '3306:3306' + - '3308:3306' steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 @@ -105,7 +106,7 @@ jobs: mssql: image: mcr.microsoft.com/mssql/server:2019-latest env: - SA_PASSWORD: 'arandom&233password' + SA_PASSWORD: 'secrearandom&233passwordt' ACCEPT_EULA: 'Y' ports: - '1433:1433' diff --git a/.gitignore b/.gitignore index e2ff0c3b..335a36e2 100644 --- a/.gitignore +++ b/.gitignore @@ -5,8 +5,6 @@ npm-debug.log .idea out .nyc_output -test-helpers/tmp -test/functional/database .DS_STORE .vscode/ *.sublime-project @@ -16,4 +14,3 @@ build dist yarn.lock shrinkwrap.yaml -test/__app diff --git a/test-helpers/tmp/.gitignore b/test-helpers/tmp/.gitignore new file mode 100644 index 00000000..9b1dffd9 --- /dev/null +++ b/test-helpers/tmp/.gitignore @@ -0,0 +1 @@ +*.sqlite From e50c45dcf573f02115e06bfcea7556cfb6408e79 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Tue, 19 Sep 2023 17:56:50 +0530 Subject: [PATCH 16/70] ci: update typecheck job's command --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 5a12ddd4..caadecf0 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -22,7 +22,7 @@ jobs: with: node-version: 20 - run: npm install - - run: npx tsc + - run: npm run typecheck test-postgres: runs-on: ubuntu-latest From 98d74e9be93e9de8046dd270fb861c11db8351c8 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Tue, 19 Sep 2023 18:04:50 +0530 Subject: [PATCH 17/70] docs: update README --- README.md | 60 ++++++++++++++++++++++--------------------------------- 1 file changed, 24 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 8a84fa76..e77d7e81 100644 --- a/README.md +++ b/README.md @@ -1,53 +1,41 @@ -
- -
+# @adonisjs/lucid
-
-

SQL ORM

-

Lucid is the official SQL ORM for AdonisJS. It comes with an Active Record ORM, Query Builder, Migrations, Seeds and Factories

-
+[![gh-workflow-image]][gh-workflow-url] [![npm-image]][npm-url] ![][typescript-image] [![license-image]][license-url] -
+## Introduction +SQL ORM for AdonisJS built on top of Knex. Comes with a db query builder, Active record ORM, migrations, seeders and model factories. + +## Official Documentation +The documentation is available on the [AdonisJS website](https://docs.adonisjs.com/guides/database/introduction) + +## Contributing +One of the primary goals of AdonisJS is to have a vibrant community of users and contributors who believes in the principles of the framework. -
+We encourage you to read the [contribution guide](https://github.com/adonisjs/.github/blob/main/docs/CONTRIBUTING.md) before contributing to the framework. -[![gh-workflow-image]][gh-workflow-url] [![typescript-image]][typescript-url] [![npm-image]][npm-url] [![license-image]][license-url] [![synk-image]][synk-url] +### Run tests locally +Easiest way to run tests is to launch the redis cluster using docker-compose and `docker-compose.yml` file. -
+```sh +docker-compose up +npm run test +``` - +## Code of Conduct +In order to ensure that the AdonisJS community is welcoming to all, please review and abide by the [Code of Conduct](https://github.com/adonisjs/.github/blob/main/docs/CODE_OF_CONDUCT.md). -
- Built with ❤︎ by Harminder Virk -
+## License +AdonisJS Redis is open-sourced software licensed under the [MIT license](LICENSE.md). [gh-workflow-image]: https://img.shields.io/github/actions/workflow/status/adonisjs/lucid/test.yml?style=for-the-badge [gh-workflow-url]: https://github.com/adonisjs/lucid/actions/workflows/test.yml "Github action" -[typescript-image]: https://img.shields.io/badge/Typescript-294E80.svg?style=for-the-badge&logo=typescript -[typescript-url]: "typescript" - [npm-image]: https://img.shields.io/npm/v/@adonisjs/lucid/latest.svg?style=for-the-badge&logo=npm [npm-url]: https://www.npmjs.com/package/@adonisjs/lucid/v/latest "npm" -[license-image]: https://img.shields.io/npm/l/@adonisjs/lucid?color=blueviolet&style=for-the-badge -[license-url]: LICENSE.md "license" +[typescript-image]: https://img.shields.io/badge/Typescript-294E80.svg?style=for-the-badge&logo=typescript -[synk-image]: https://img.shields.io/snyk/vulnerabilities/github/adonisjs/lucid?label=Synk%20Vulnerabilities&style=for-the-badge -[synk-url]: https://snyk.io/test/github/adonisjs/lucid?targetFile=package.json "synk" +[license-url]: LICENSE.md +[license-image]: https://img.shields.io/github/license/adonisjs/lucid?style=for-the-badge From c9d28af8df523e067d68054cb0ce658f39c1f2c4 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Tue, 19 Sep 2023 18:07:59 +0530 Subject: [PATCH 18/70] chore: update dependencies and peer dependencies --- package.json | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 3d3adfb7..56cb4bb8 100644 --- a/package.json +++ b/package.json @@ -59,9 +59,9 @@ "@poppinss/utils": "^6.5.0-6", "fast-deep-equal": "^3.1.3", "igniculus": "^1.5.0", + "kleur": "^4.1.5", "knex": "^2.4.2", "knex-dynamic-connection": "^3.1.0", - "luxon": "^3.3.0", "pretty-hrtime": "^1.0.3", "qs": "^6.11.2", "slash": "^5.1.0", @@ -96,6 +96,7 @@ "fs-extra": "^11.1.1", "github-label-sync": "^2.3.1", "husky": "^8.0.3", + "luxon": "^3.4.3", "mysql2": "^3.3.1", "np": "^8.0.4", "pg": "^8.11.0", @@ -106,6 +107,19 @@ "ts-node": "^10.9.1", "typescript": "^5.2.2" }, + "peerDependencies": { + "@adonisjs/assembler": "^6.1.3-22", + "@adonisjs/core": "^6.1.5-26", + "luxon": "^3.4.3" + }, + "peerDependenciesMeta": { + "@adonisjs/assembler": { + "optional": true + }, + "luxon": { + "optional": true + } + }, "license": "MIT", "author": "virk,adonisjs", "homepage": "https://github.com/adonisjs/lucid#readme", From 09b60357975dcc2966a67eecf39aadaf58ceef13 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Wed, 20 Sep 2023 08:01:44 +0530 Subject: [PATCH 19/70] chore(release): 19.0.0-0 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 56cb4bb8..b2a52461 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@adonisjs/lucid", - "version": "18.4.0", + "version": "19.0.0-0", "description": "SQL ORM built on top of Active Record pattern", "engines": { "node": ">=18.16.0" From e4bd8873398413fce41000b38709de1a01281897 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Wed, 20 Sep 2023 08:40:38 +0530 Subject: [PATCH 20/70] fix: bug fixes from the last release --- commands/db_seed.ts | 5 +++-- commands/db_truncate.ts | 5 +++-- commands/db_wipe.ts | 5 +++-- commands/make_factory.ts | 3 ++- commands/make_migration.ts | 7 ++++--- commands/make_model.ts | 5 +++-- commands/make_seeder.ts | 5 +++++ commands/migration/fresh.ts | 5 +++-- commands/migration/refresh.ts | 5 +++-- commands/migration/reset.ts | 5 +++-- commands/migration/rollback.ts | 5 +++-- commands/migration/run.ts | 5 +++-- commands/migration/status.ts | 5 +++-- configure.ts | 25 ++++++++++++++++--------- package.json | 2 ++ src/migration/runner.ts | 8 ++++---- src/schema/main.ts | 4 ++-- stubs/config.stub | 23 +++++++++++++---------- stubs/make/factory/main.stub | 2 +- stubs/make/migration/alter.stub | 4 ++-- stubs/make/migration/create.stub | 4 ++-- stubs/make/seeder/main.stub | 2 +- test-helpers/index.ts | 4 ++-- 23 files changed, 86 insertions(+), 57 deletions(-) diff --git a/commands/db_seed.ts b/commands/db_seed.ts index 8693fe8b..04c79eb4 100644 --- a/commands/db_seed.ts +++ b/commands/db_seed.ts @@ -14,12 +14,13 @@ import { BaseCommand, flags } from '@adonisjs/core/ace' import { FileNode } from '../src/types/database.js' import { SeederFileNode } from '../src/types/seeder.js' import type { SeedsRunner } from '../src/seeders/runner.js' +import { CommandOptions } from '@adonisjs/core/types/ace' export default class DbSeed extends BaseCommand { static commandName = 'db:seed' static description = 'Execute database seeders' - static settings = { - loadApp: true, + static options: CommandOptions = { + startApp: true, } private declare seeder: SeedsRunner diff --git a/commands/db_truncate.ts b/commands/db_truncate.ts index 4a0211cd..e4102555 100644 --- a/commands/db_truncate.ts +++ b/commands/db_truncate.ts @@ -9,12 +9,13 @@ import { BaseCommand, flags } from '@adonisjs/core/ace' import { QueryClientContract } from '../src/types/database.js' +import { CommandOptions } from '@adonisjs/core/types/ace' export default class DbTruncate extends BaseCommand { static commandName = 'db:truncate' static description = 'Truncate all tables in database' - static settings = { - loadApp: true, + static options: CommandOptions = { + startApp: true, } /** diff --git a/commands/db_wipe.ts b/commands/db_wipe.ts index 5aa727c1..1e6bf516 100644 --- a/commands/db_wipe.ts +++ b/commands/db_wipe.ts @@ -9,12 +9,13 @@ import { BaseCommand, flags } from '@adonisjs/core/ace' import { QueryClientContract } from '../src/types/database.js' +import { CommandOptions } from '@adonisjs/core/types/ace' export default class DbWipe extends BaseCommand { static commandName = 'db:wipe' static description = 'Drop all tables, views and types in database' - static settings = { - loadApp: true, + static options: CommandOptions = { + startApp: true, } /** diff --git a/commands/make_factory.ts b/commands/make_factory.ts index 51f8edf8..d8370fc9 100644 --- a/commands/make_factory.ts +++ b/commands/make_factory.ts @@ -7,6 +7,7 @@ * file that was distributed with this source code. */ +import { CommandOptions } from '@adonisjs/core/types/ace' import { stubsRoot } from '../stubs/main.js' import { args, BaseCommand } from '@adonisjs/core/ace' @@ -17,7 +18,7 @@ export default class MakeFactory extends BaseCommand { static commandName = 'make:factory' static description = 'Make a new factory' - static options = { + static options: CommandOptions = { allowUnknownFlags: true, } diff --git a/commands/make_migration.ts b/commands/make_migration.ts index a2235849..afed06d2 100644 --- a/commands/make_migration.ts +++ b/commands/make_migration.ts @@ -7,14 +7,15 @@ * file that was distributed with this source code. */ +import { CommandOptions } from '@adonisjs/core/types/ace' import { stubsRoot } from '../stubs/main.js' import { args, BaseCommand, flags } from '@adonisjs/core/ace' export default class MakeMigration extends BaseCommand { static commandName = 'make:migration' static description = 'Make a new migration file' - static settings = { - loadApp: true, + static options: CommandOptions = { + startApp: true, allowUnknownFlags: true, } @@ -115,7 +116,7 @@ export default class MakeMigration extends BaseCommand { const prefix = new Date().getTime() const action = this.alter ? 'alter' : 'create' const tableName = this.app.generators.tableName(entity.name) - const fileName = `${prefix}_${action}_${tableName}_table` + const fileName = `${prefix}_${action}_${tableName}_table.ts` const codemods = await this.createCodemods() await codemods.makeUsingStub(stubsRoot, `make/migration/${action}.stub`, { diff --git a/commands/make_model.ts b/commands/make_model.ts index 3f41fe52..5991064b 100644 --- a/commands/make_model.ts +++ b/commands/make_model.ts @@ -9,12 +9,13 @@ import { BaseCommand, args, flags } from '@adonisjs/core/ace' import { stubsRoot } from '../stubs/main.js' +import { CommandOptions } from '@adonisjs/core/types/ace' export default class MakeModel extends BaseCommand { static commandName = 'make:model' static description = 'Make a new Lucid model' - static settings = { - loadApp: true, + static options: CommandOptions = { + allowUnknownFlags: true, } /** diff --git a/commands/make_seeder.ts b/commands/make_seeder.ts index 57a36b6b..915b01e5 100644 --- a/commands/make_seeder.ts +++ b/commands/make_seeder.ts @@ -9,11 +9,16 @@ import { BaseCommand, args } from '@adonisjs/core/ace' import { stubsRoot } from '../stubs/main.js' +import { CommandOptions } from '@adonisjs/core/types/ace' export default class MakeSeeder extends BaseCommand { static commandName = 'make:seeder' static description = 'Make a new Seeder file' + static options: CommandOptions = { + allowUnknownFlags: true, + } + /** * The name of the seeder file. */ diff --git a/commands/migration/fresh.ts b/commands/migration/fresh.ts index 3fec73b7..97bc5771 100644 --- a/commands/migration/fresh.ts +++ b/commands/migration/fresh.ts @@ -8,6 +8,7 @@ */ import { flags, BaseCommand } from '@adonisjs/core/ace' +import { CommandOptions } from '@adonisjs/core/types/ace' /** * This command reset the database by rolling back to batch 0 and then @@ -16,8 +17,8 @@ import { flags, BaseCommand } from '@adonisjs/core/ace' export default class Refresh extends BaseCommand { static commandName = 'migration:fresh' static description = 'Drop all tables and re-migrate the database' - static settings = { - loadApp: true, + static options: CommandOptions = { + startApp: true, } /** diff --git a/commands/migration/refresh.ts b/commands/migration/refresh.ts index f996c5fb..dc7f7bf4 100644 --- a/commands/migration/refresh.ts +++ b/commands/migration/refresh.ts @@ -8,6 +8,7 @@ */ import { flags, BaseCommand } from '@adonisjs/core/ace' +import { CommandOptions } from '@adonisjs/core/types/ace' /** * This command reset the database by rolling back to batch 0 and then @@ -16,8 +17,8 @@ import { flags, BaseCommand } from '@adonisjs/core/ace' export default class Refresh extends BaseCommand { static commandName = 'migration:refresh' static description = 'Rollback and migrate database' - static settings = { - loadApp: true, + static options: CommandOptions = { + startApp: true, } /** diff --git a/commands/migration/reset.ts b/commands/migration/reset.ts index 2599e023..0aa98bd2 100644 --- a/commands/migration/reset.ts +++ b/commands/migration/reset.ts @@ -8,6 +8,7 @@ */ import { BaseCommand, flags } from '@adonisjs/core/ace' +import { CommandOptions } from '@adonisjs/core/types/ace' /** * This command resets the database by rolling back to batch 0. Same @@ -16,8 +17,8 @@ import { BaseCommand, flags } from '@adonisjs/core/ace' export default class Reset extends BaseCommand { static commandName = 'migration:reset' static description = 'Rollback all migrations' - static settings = { - loadApp: true, + static options: CommandOptions = { + startApp: true, } /** diff --git a/commands/migration/rollback.ts b/commands/migration/rollback.ts index e177bddd..56ba5f30 100644 --- a/commands/migration/rollback.ts +++ b/commands/migration/rollback.ts @@ -11,6 +11,7 @@ import { flags } from '@adonisjs/core/ace' import MigrationsBase from './_base.js' import { MigrationRunner } from '../../src/migration/runner.js' +import { CommandOptions } from '@adonisjs/core/types/ace' /** * The command is meant to migrate the database by executing migrations @@ -19,8 +20,8 @@ import { MigrationRunner } from '../../src/migration/runner.js' export default class Migrate extends MigrationsBase { static commandName = 'migration:rollback' static description = 'Rollback migrations to a specific batch number' - static settings = { - loadApp: true, + static options: CommandOptions = { + startApp: true, } private migrator?: MigrationRunner diff --git a/commands/migration/run.ts b/commands/migration/run.ts index f3d428ef..e7b0a0cc 100644 --- a/commands/migration/run.ts +++ b/commands/migration/run.ts @@ -10,6 +10,7 @@ import { flags } from '@adonisjs/core/ace' import MigrationsBase from './_base.js' import { MigrationRunner } from '../../src/migration/runner.js' +import { CommandOptions } from '@adonisjs/core/types/ace' /** * The command is meant to migrate the database by executing migrations @@ -18,8 +19,8 @@ import { MigrationRunner } from '../../src/migration/runner.js' export default class Migrate extends MigrationsBase { static commandName = 'migration:run' static description = 'Migrate database by running pending migrations' - static settings = { - loadApp: true, + static options: CommandOptions = { + startApp: true, } private migrator?: MigrationRunner diff --git a/commands/migration/status.ts b/commands/migration/status.ts index 2f16f7d0..729e799c 100644 --- a/commands/migration/status.ts +++ b/commands/migration/status.ts @@ -10,6 +10,7 @@ import { flags, BaseCommand } from '@adonisjs/core/ace' import { MigrationListNode } from '../../src/types/migrator.js' import { MigrationRunner } from '../../src/migration/runner.js' +import { CommandOptions } from '@adonisjs/core/types/ace' /** * The command is meant to migrate the database by execute migrations @@ -18,8 +19,8 @@ import { MigrationRunner } from '../../src/migration/runner.js' export default class Status extends BaseCommand { static commandName = 'migration:status' static description = 'View migrations status' - static settings = { - loadApp: true, + static options: CommandOptions = { + startApp: true, } private migrator?: MigrationRunner diff --git a/configure.ts b/configure.ts index 835bb53e..9073cb72 100644 --- a/configure.ts +++ b/configure.ts @@ -39,7 +39,7 @@ const DIALECTS_INFO: { DB_HOST: `Env.schema.string({ format: 'host' })`, DB_PORT: `Env.schema.number()`, DB_USER: 'Env.schema.string()', - DB_PASSWORD: 'Env.schema.string()', + DB_PASSWORD: 'Env.schema.string.optional()', DB_DATABASE: 'Env.schema.string()', }, }, @@ -55,7 +55,7 @@ const DIALECTS_INFO: { DB_HOST: `Env.schema.string({ format: 'host' })`, DB_PORT: `Env.schema.number()`, DB_USER: 'Env.schema.string()', - DB_PASSWORD: 'Env.schema.string()', + DB_PASSWORD: 'Env.schema.string.optional()', DB_DATABASE: 'Env.schema.string()', }, pkg: 'pg', @@ -72,7 +72,7 @@ const DIALECTS_INFO: { DB_HOST: `Env.schema.string({ format: 'host' })`, DB_PORT: `Env.schema.number()`, DB_USER: 'Env.schema.string()', - DB_PASSWORD: 'Env.schema.string()', + DB_PASSWORD: 'Env.schema.string.optional()', DB_DATABASE: 'Env.schema.string()', }, pkg: 'tedious', @@ -84,9 +84,6 @@ const DIALECTS_INFO: { */ export async function configure(command: Configure) { const codemods = await command.createCodemods() - await codemods.updateRcFile((rcFile) => { - rcFile.addProvider('@adonisjs/lucid/database_provider') - }) /** * Prompt to select the dialect to use @@ -97,6 +94,16 @@ export async function configure(command: Configure) { })) || 'postgres' const { pkg, envVars, envValidations } = DIALECTS_INFO[dialect] + const installNpmDriver = await command.prompt.confirm( + `Do you want to install npm package "${pkg}"?` + ) + + /** + * Register provider + */ + await codemods.updateRcFile((rcFile) => { + rcFile.addProvider('@adonisjs/lucid/database_provider') + }) /** * Define environment variables @@ -111,7 +118,7 @@ export async function configure(command: Configure) { if (envValidations) { codemods.defineEnvValidations({ variables: envValidations, - leadingComment: 'Variables for configuring ally package', + leadingComment: 'Variables for configuring database connection', }) } @@ -121,9 +128,9 @@ export async function configure(command: Configure) { await command.publishStub('config.stub', { dialect: dialect }) /** - * Prompt to install package + * Install package or show steps to install package */ - if (await command.prompt.confirm(`Do you want to install npm package "${pkg}"?`)) { + if (installNpmDriver) { await command.installPackages([{ name: pkg, isDevDependency: false }]) } else { command.listPackagesToInstall([{ name: pkg, isDevDependency: false }]) diff --git a/package.json b/package.json index b2a52461..74fd558d 100644 --- a/package.json +++ b/package.json @@ -5,6 +5,7 @@ "engines": { "node": ">=18.16.0" }, + "main": "./build/index.js", "files": [ "build/commands", "build/providers", @@ -18,6 +19,7 @@ ], "type": "module", "exports": { + ".": "./build/index.js", "./schema": "./build/src/schema/main.js", "./commands": "./build/commands/main.js", "./factories": "./build/src/factories/main.js", diff --git a/src/migration/runner.ts b/src/migration/runner.ts index 8775ce53..56261c32 100644 --- a/src/migration/runner.ts +++ b/src/migration/runner.ts @@ -23,7 +23,7 @@ import { import { MigrationSource } from './source.js' import { Database } from '../database/main.js' import { Application } from '@adonisjs/core/app' -import { Schema } from '../schema/main.js' +import { BaseSchema } from '../schema/main.js' /** * Migrator exposes the API to execute migrations using the schema files @@ -210,10 +210,10 @@ export class MigrationRunner extends EventEmitter { * Returns the migration source by ensuring value is a class constructor and * has disableTransactions property. */ - private async getMigrationSource(migration: FileNode): Promise { + private async getMigrationSource(migration: FileNode): Promise { const source = await migration.getSource() if (typeof source === 'function' && 'disableTransactions' in source) { - return source as typeof Schema + return source as typeof BaseSchema } throw new Error(`Invalid schema class exported by "${migration.name}"`) @@ -225,7 +225,7 @@ export class MigrationRunner extends EventEmitter { */ private async executeMigration(migration: FileNode) { const SchemaClass = await this.getMigrationSource(migration) - const client = await this.getClient(Schema.disableTransactions) + const client = await this.getClient(BaseSchema.disableTransactions) try { const schema = new SchemaClass(client, migration.name, this.dryRun) diff --git a/src/schema/main.ts b/src/schema/main.ts index 23632114..d9d01796 100644 --- a/src/schema/main.ts +++ b/src/schema/main.ts @@ -10,8 +10,8 @@ import type { Knex } from 'knex' import { Exception } from '@poppinss/utils' import { getDDLMethod } from '../utils/index.js' -import { QueryReporter } from '../query_reporter/index.js' import type { DeferCallback } from '../types/schema.js' +import { QueryReporter } from '../query_reporter/index.js' import type { QueryClientContract } from '../types/database.js' import type { RawQueryBindings } from '../types/querybuilder.js' @@ -19,7 +19,7 @@ import type { RawQueryBindings } from '../types/querybuilder.js' * Exposes the API to define table schema using deferred database * calls. */ -export class Schema { +export abstract class BaseSchema { /** * All calls to `schema` and `defer` are tracked to be * executed later diff --git a/stubs/config.stub b/stubs/config.stub index e14263fc..076ab773 100644 --- a/stubs/config.stub +++ b/stubs/config.stub @@ -2,12 +2,13 @@ to: {{ app.configPath('database.ts') }} --- import env from '#start/env' +{{#if dialect === 'sqlite'}} import app from '@adonisjs/core/services/app' +{{/if}} import { defineConfig } from '@adonisjs/lucid' -const allyConfig = defineConfig({ +const dbConfig = defineConfig({ connection: '{{ dialect }}', - connections: { {{#if dialect === 'sqlite'}} sqlite: { @@ -20,7 +21,7 @@ const allyConfig = defineConfig({ naturalSort: true, paths: ['database/migrations'], }, - } + }, {{#elif dialect === 'postgres'}} postgres: { client: 'pg', @@ -34,8 +35,8 @@ const allyConfig = defineConfig({ migrations: { naturalSort: true, paths: ['database/migrations'], - } - } + }, + }, {{#elif dialect === 'mysql'}} mysql: { client: 'mysql2', @@ -49,8 +50,8 @@ const allyConfig = defineConfig({ migrations: { naturalSort: true, paths: ['database/migrations'], - } - } + }, + }, {{#elif dialect === 'mssql'}} mssql: { client: 'tedious', @@ -64,8 +65,10 @@ const allyConfig = defineConfig({ migrations: { naturalSort: true, paths: ['database/migrations'], - } - } + }, + }, {{/if}} - } + }, }) + +export default dbConfig diff --git a/stubs/make/factory/main.stub b/stubs/make/factory/main.stub index fe2522b8..8a9e426b 100644 --- a/stubs/make/factory/main.stub +++ b/stubs/make/factory/main.stub @@ -10,7 +10,7 @@ import factory from '@adonisjs/lucid/factories' import {{ modelName }} from '{{ modelImportPath }}' export const {{ factoryName }} = factory - .define({{ modelName }}, ({ faker }) => { + .define({{ modelName }}, async ({ faker }) => { return {} }) .build() diff --git a/stubs/make/migration/alter.stub b/stubs/make/migration/alter.stub index 34120a3b..5b20b1bd 100644 --- a/stubs/make/migration/alter.stub +++ b/stubs/make/migration/alter.stub @@ -6,12 +6,12 @@ import { BaseSchema } from '@adonisjs/lucid/schema' export default class extends BaseSchema { protected tableName = '{{ migration.tableName }}' - async up () { + async up() { this.schema.alterTable(this.tableName, (table) => { }) } - async down () { + async down() { this.schema.alterTable(this.tableName) } } diff --git a/stubs/make/migration/create.stub b/stubs/make/migration/create.stub index b57f2390..12c582d1 100644 --- a/stubs/make/migration/create.stub +++ b/stubs/make/migration/create.stub @@ -6,7 +6,7 @@ import { BaseSchema } from '@adonisjs/lucid/schema' export default class extends BaseSchema { protected tableName = '{{ migration.tableName }}' - async up () { + async up() { this.schema.createTable(this.tableName, (table) => { table.increments('id') @@ -18,7 +18,7 @@ export default class extends BaseSchema { }) } - async down () { + async down() { this.schema.dropTable(this.tableName) } } diff --git a/stubs/make/seeder/main.stub b/stubs/make/seeder/main.stub index 1be66bba..e520f649 100644 --- a/stubs/make/seeder/main.stub +++ b/stubs/make/seeder/main.stub @@ -5,7 +5,7 @@ to: {{ app.seedersPath(entity.path, seederFileName) }} import { BaseSeeder } from '@adonisjs/lucid/seeders' export default class extends BaseSeeder { - async run () { + async run() { // Write your database queries inside the run method } } diff --git a/test-helpers/index.ts b/test-helpers/index.ts index fafd3c90..38438009 100644 --- a/test-helpers/index.ts +++ b/test-helpers/index.ts @@ -31,7 +31,7 @@ import { DatabaseQueryBuilderContract, } from '../src/types/querybuilder.js' -import { Schema } from '../src/schema/main.js' +import { BaseSchema } from '../src/schema/main.js' import { Database } from '../src/database/main.js' import { Adapter } from '../src/orm/adapter/index.js' import { BaseModel } from '../src/orm/base_model/index.js' @@ -534,7 +534,7 @@ export function mapToObj(collection: Map): T { * Returns the base schema class typed to it's interface */ export function getBaseSchema() { - return Schema + return BaseSchema } /** From 054554f63804fe9490ce83693d3dc9bbe60f3e61 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Wed, 20 Sep 2023 08:53:22 +0530 Subject: [PATCH 21/70] refactor: remove container dependency --- src/orm/adapter/index.ts | 2 +- src/orm/base_model/index.ts | 9 - src/schema/main.ts | 2 +- src/types/model.ts | 3 - test-helpers/index.ts | 3 +- test/commands/db_wipe.spec.ts | 4 +- test/commands/migration/fresh.spec.ts | 4 +- test/commands/migration/refresh.spec.ts | 8 +- test/commands/migration/reset.spec.ts | 4 +- test/commands/migration/run.spec.ts | 16 +- test/factory/belongs_to.spec.ts | 14 +- test/factory/factory_builder.spec.ts | 86 ++--- test/factory/factory_model.spec.ts | 20 +- test/factory/has_many.spec.ts | 22 +- test/factory/has_one.spec.ts | 12 +- test/factory/many_to_many.spec.ts | 16 +- test/fixtures/config/app.ts | 216 ------------ test/fixtures/config/database.ts | 6 - test/migrations/migrator.spec.ts | 66 ++-- test/orm/adapter.spec.ts | 20 +- test/orm/base_model.spec.ts | 440 ++++++++++++------------ test/orm/base_model_options.spec.ts | 80 ++--- test/orm/model_belongs_to.spec.ts | 102 +++--- test/orm/model_has_many.spec.ts | 182 +++++----- test/orm/model_has_many_through.spec.ts | 108 +++--- test/orm/model_has_one.spec.ts | 116 +++---- test/orm/model_many_to_many.spec.ts | 280 +++++++-------- test/orm/model_query_builder.spec.ts | 30 +- 28 files changed, 818 insertions(+), 1053 deletions(-) delete mode 100644 test/fixtures/config/app.ts delete mode 100644 test/fixtures/config/database.ts diff --git a/src/orm/adapter/index.ts b/src/orm/adapter/index.ts index edb4cb46..4751cce4 100644 --- a/src/orm/adapter/index.ts +++ b/src/orm/adapter/index.ts @@ -8,9 +8,9 @@ */ import { Exception } from '@poppinss/utils' -import { LucidRow, LucidModel, AdapterContract, ModelAdapterOptions } from '../../types/model.js' import { isObject } from '../../utils/index.js' import type { Database } from '../../database/main.js' +import { LucidRow, LucidModel, AdapterContract, ModelAdapterOptions } from '../../types/model.js' /** * Adapter exposes the API to make database queries and constructor diff --git a/src/orm/base_model/index.ts b/src/orm/base_model/index.ts index c62a2733..328f4b38 100644 --- a/src/orm/base_model/index.ts +++ b/src/orm/base_model/index.ts @@ -11,7 +11,6 @@ import { DateTime } from 'luxon' import equal from 'fast-deep-equal' import Hooks from '@poppinss/hooks' import lodash from '@poppinss/utils/lodash' -import type { Container } from '@adonisjs/core/container' import { Exception, defineStaticProperty } from '@poppinss/utils' import { QueryClientContract, TransactionClientContract } from '../../types/database.js' @@ -93,14 +92,6 @@ class BaseModelImpl implements LucidRow { */ static namingStrategy = new SnakeCaseNamingStrategy() - /** - * The container required to resolve hooks - * - * NOTE: Container is a singleton and share among all the models, unless - * a user wants to swap the container for a given model - */ - static $container: Container - /** * Primary key is required to build relationships across models */ diff --git a/src/schema/main.ts b/src/schema/main.ts index d9d01796..3c45851a 100644 --- a/src/schema/main.ts +++ b/src/schema/main.ts @@ -19,7 +19,7 @@ import type { RawQueryBindings } from '../types/querybuilder.js' * Exposes the API to define table schema using deferred database * calls. */ -export abstract class BaseSchema { +export class BaseSchema { /** * All calls to `schema` and `defer` are tracked to be * executed later diff --git a/src/types/model.ts b/src/types/model.ts index de877857..90dbc2f1 100644 --- a/src/types/model.ts +++ b/src/types/model.ts @@ -37,7 +37,6 @@ import { WithAggregate, WithCount, } from './relations.js' -import { Container } from '@adonisjs/core/container' /** * ------------------------------------------------------ @@ -732,8 +731,6 @@ export interface LucidModel { */ readonly booted: boolean - $container: Container - /** * A map of defined columns */ diff --git a/test-helpers/index.ts b/test-helpers/index.ts index 38438009..0ad47835 100644 --- a/test-helpers/index.ts +++ b/test-helpers/index.ts @@ -420,9 +420,8 @@ export function ormAdapter(db: Database) { /** * Returns the base model with the adapter attached to it */ -export function getBaseModel(adapter: AdapterContract, application: Application) { +export function getBaseModel(adapter: AdapterContract) { BaseModel.$adapter = adapter - BaseModel.$container = application.container return BaseModel } diff --git a/test/commands/db_wipe.spec.ts b/test/commands/db_wipe.spec.ts index 7fc61321..d73355bf 100644 --- a/test/commands/db_wipe.spec.ts +++ b/test/commands/db_wipe.spec.ts @@ -29,8 +29,8 @@ test.group('db:wipe and migrate:fresh', (group) => { await fs.create( 'database/migrations/users.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { BaseSchema as Schema } from '../../../../src/schema/index.js' + export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() diff --git a/test/commands/migration/fresh.spec.ts b/test/commands/migration/fresh.spec.ts index 7598fd4b..a85672c7 100644 --- a/test/commands/migration/fresh.spec.ts +++ b/test/commands/migration/fresh.spec.ts @@ -32,7 +32,7 @@ test.group('migrate:fresh', (group) => { await fs.create( 'database/migrations/fresh_cmd_users.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -87,7 +87,7 @@ test.group('migrate:fresh', (group) => { await fs.create( 'database/migrations/fresh_cmd_users_v1.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { diff --git a/test/commands/migration/refresh.spec.ts b/test/commands/migration/refresh.spec.ts index c3f4e9fc..e835395d 100644 --- a/test/commands/migration/refresh.spec.ts +++ b/test/commands/migration/refresh.spec.ts @@ -31,7 +31,7 @@ test.group('migration:refresh', (group) => { await fs.create( 'database/migrations/refresh_cmd_users.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -49,7 +49,7 @@ test.group('migration:refresh', (group) => { await fs.create( 'database/migrations/refresh_cmd_posts.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class Account extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -100,7 +100,7 @@ test.group('migration:refresh', (group) => { await fs.create( 'database/migrations/refres_cmd_users_v1.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -118,7 +118,7 @@ test.group('migration:refresh', (group) => { await fs.create( 'database/migrations/posts.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class Account extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { diff --git a/test/commands/migration/reset.spec.ts b/test/commands/migration/reset.spec.ts index 6098ea75..267f7125 100644 --- a/test/commands/migration/reset.spec.ts +++ b/test/commands/migration/reset.spec.ts @@ -31,7 +31,7 @@ test.group('migration:reset', (group) => { await fs.create( 'database/migrations/reset_cmd_users.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -49,7 +49,7 @@ test.group('migration:reset', (group) => { await fs.create( 'database/migrations/reset_cmd_posts.ts', ` - import { Schema } from '../../../../src/Schema' + import { BaseSchema as Schema } from '../../../../src/Schema' export default class Account extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { diff --git a/test/commands/migration/run.spec.ts b/test/commands/migration/run.spec.ts index b5938325..41242cc8 100644 --- a/test/commands/migration/run.spec.ts +++ b/test/commands/migration/run.spec.ts @@ -33,7 +33,7 @@ test.group('migration:run', (group) => { await fs.create( 'database/migrations/run_cmd_users.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -80,7 +80,7 @@ test.group('migration:run', (group) => { await fs.create( 'database/migrations/run_cmd_users_v1.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -114,7 +114,7 @@ test.group('migration:run', (group) => { await fs.create( 'database/migrations/run_cmd_users_v2.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -160,7 +160,7 @@ test.group('migration:run', (group) => { await fs.create( 'database/migrations/run_cmd_users_v3.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -198,7 +198,7 @@ test.group('migration:run', (group) => { await fs.create( 'database/migrations/run_cmd_users_v4.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { @@ -213,7 +213,7 @@ test.group('migration:run', (group) => { await fs.create( 'database/migrations/run_cmd_clients_v4.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class Client extends Schema { public async up () { @@ -243,7 +243,7 @@ test.group('migration:run', (group) => { await fs.create( 'database/migrations/run_cmd_users_v5.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { @@ -258,7 +258,7 @@ test.group('migration:run', (group) => { await fs.create( 'database/migrations/run_cmd_clients_v5.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class Client extends Schema { public async up () { diff --git a/test/factory/belongs_to.spec.ts b/test/factory/belongs_to.spec.ts index 2b8caf34..3a1de55c 100644 --- a/test/factory/belongs_to.spec.ts +++ b/test/factory/belongs_to.spec.ts @@ -43,7 +43,7 @@ test.group('Factory | BelongTo | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -101,7 +101,7 @@ test.group('Factory | BelongTo | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -165,7 +165,7 @@ test.group('Factory | BelongTo | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -248,7 +248,7 @@ test.group('Factory | BelongTo | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -308,7 +308,7 @@ test.group('Factory | BelongTo | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -366,7 +366,7 @@ test.group('Factory | BelongTo | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ columnName: 'user_id' }) @@ -424,7 +424,7 @@ test.group('Factory | BelongTo | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(3) diff --git a/test/factory/factory_builder.spec.ts b/test/factory/factory_builder.spec.ts index 1ad34fc6..f5e2945c 100644 --- a/test/factory/factory_builder.spec.ts +++ b/test/factory/factory_builder.spec.ts @@ -45,7 +45,7 @@ test.group('Factory | Factory Builder | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -76,7 +76,7 @@ test.group('Factory | Factory Builder | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -110,7 +110,7 @@ test.group('Factory | Factory Builder | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -144,7 +144,7 @@ test.group('Factory | Factory Builder | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -176,7 +176,7 @@ test.group('Factory | Factory Builder | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -209,7 +209,7 @@ test.group('Factory | Factory Builder | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -244,7 +244,7 @@ test.group('Factory | Factory Builder | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -284,7 +284,7 @@ test.group('Factory | Factory Builder | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -324,7 +324,7 @@ test.group('Factory | Factory Builder | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -366,7 +366,7 @@ test.group('Factory | Factory Builder | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -398,7 +398,7 @@ test.group('Factory | Factory Builder | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(6) @@ -437,7 +437,7 @@ test.group('Factory | Factory Builder | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(6) @@ -476,7 +476,7 @@ test.group('Factory | Factory Builder | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(3) @@ -515,7 +515,7 @@ test.group('Factory | Factory Builder | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -554,7 +554,7 @@ test.group('Factory | Factory Builder | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -590,7 +590,7 @@ test.group('Factory | Factory Builder | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -622,7 +622,7 @@ test.group('Factory | Factory Builder | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -668,7 +668,7 @@ test.group('Factory | Factory Builder | makeMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -704,7 +704,7 @@ test.group('Factory | Factory Builder | makeMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -741,7 +741,7 @@ test.group('Factory | Factory Builder | makeMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -779,7 +779,7 @@ test.group('Factory | Factory Builder | makeMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -819,7 +819,7 @@ test.group('Factory | Factory Builder | makeMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(15) @@ -863,7 +863,7 @@ test.group('Factory | Factory Builder | makeMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(15) @@ -907,7 +907,7 @@ test.group('Factory | Factory Builder | makeMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(15) @@ -954,7 +954,7 @@ test.group('Factory | Factory Builder | makeMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(13) @@ -999,7 +999,7 @@ test.group('Factory | Factory Builder | makeMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1032,7 +1032,7 @@ test.group('Factory | Factory Builder | makeMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1076,7 +1076,7 @@ test.group('Factory | Factory Builder | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1106,7 +1106,7 @@ test.group('Factory | Factory Builder | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1136,7 +1136,7 @@ test.group('Factory | Factory Builder | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1167,7 +1167,7 @@ test.group('Factory | Factory Builder | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1198,7 +1198,7 @@ test.group('Factory | Factory Builder | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(4) @@ -1236,7 +1236,7 @@ test.group('Factory | Factory Builder | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(6) const stack: string[] = [] @@ -1282,7 +1282,7 @@ test.group('Factory | Factory Builder | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(3) @@ -1321,7 +1321,7 @@ test.group('Factory | Factory Builder | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(3) @@ -1362,7 +1362,7 @@ test.group('Factory | Factory Builder | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(6) @@ -1406,7 +1406,7 @@ test.group('Factory | Factory Builder | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1451,7 +1451,7 @@ test.group('Factory | Factory Builder | createMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1484,7 +1484,7 @@ test.group('Factory | Factory Builder | createMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1517,7 +1517,7 @@ test.group('Factory | Factory Builder | createMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1552,7 +1552,7 @@ test.group('Factory | Factory Builder | createMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1586,7 +1586,7 @@ test.group('Factory | Factory Builder | createMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(11) @@ -1630,7 +1630,7 @@ test.group('Factory | Factory Builder | createMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) let index = 0 diff --git a/test/factory/factory_model.spec.ts b/test/factory/factory_model.spec.ts index 7a9bab6e..2bc0b880 100644 --- a/test/factory/factory_model.spec.ts +++ b/test/factory/factory_model.spec.ts @@ -45,7 +45,7 @@ test.group('Factory | Factory Model', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -64,7 +64,7 @@ test.group('Factory | Factory Model', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -84,7 +84,7 @@ test.group('Factory | Factory Model', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -115,7 +115,7 @@ test.group('Factory | Factory Model', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -135,7 +135,7 @@ test.group('Factory | Factory Model', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -157,7 +157,7 @@ test.group('Factory | Factory Model', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -192,7 +192,7 @@ test.group('Factory | Factory Model', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel {} Profile.boot() @@ -223,7 +223,7 @@ test.group('Factory | Factory Model', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -246,7 +246,7 @@ test.group('Factory | Factory Model', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel {} Profile.boot() @@ -277,7 +277,7 @@ test.group('Factory | Factory Model', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel {} Profile.boot() diff --git a/test/factory/has_many.spec.ts b/test/factory/has_many.spec.ts index b604aca4..78c302d8 100644 --- a/test/factory/has_many.spec.ts +++ b/test/factory/has_many.spec.ts @@ -43,7 +43,7 @@ test.group('Factory | HasMany | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -103,7 +103,7 @@ test.group('Factory | HasMany | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -160,7 +160,7 @@ test.group('Factory | HasMany | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -220,7 +220,7 @@ test.group('Factory | HasMany | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -304,7 +304,7 @@ test.group('Factory | HasMany | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -365,7 +365,7 @@ test.group('Factory | HasMany | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -422,7 +422,7 @@ test.group('Factory | HasMany | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -483,7 +483,7 @@ test.group('Factory | HasMany | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column({ columnName: 'user_id' }) @@ -540,7 +540,7 @@ test.group('Factory | HasMany | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(3) @@ -598,7 +598,7 @@ test.group('Factory | HasMany | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -664,7 +664,7 @@ test.group('Factory | HasMany | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Comment extends BaseModel { @column() diff --git a/test/factory/has_one.spec.ts b/test/factory/has_one.spec.ts index 74e98b8d..6852f1ac 100644 --- a/test/factory/has_one.spec.ts +++ b/test/factory/has_one.spec.ts @@ -43,7 +43,7 @@ test.group('Factory | HasOne | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -102,7 +102,7 @@ test.group('Factory | HasOne | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -177,7 +177,7 @@ test.group('Factory | HasOne | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -237,7 +237,7 @@ test.group('Factory | HasOne | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -293,7 +293,7 @@ test.group('Factory | HasOne | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ columnName: 'user_id' }) @@ -346,7 +346,7 @@ test.group('Factory | HasOne | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(3) diff --git a/test/factory/many_to_many.spec.ts b/test/factory/many_to_many.spec.ts index 96646cb8..8b2d82d3 100644 --- a/test/factory/many_to_many.spec.ts +++ b/test/factory/many_to_many.spec.ts @@ -42,7 +42,7 @@ test.group('Factory | ManyToMany | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -99,7 +99,7 @@ test.group('Factory | ManyToMany | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -157,7 +157,7 @@ test.group('Factory | ManyToMany | make', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -234,7 +234,7 @@ test.group('Factory | ManyToMany | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -296,7 +296,7 @@ test.group('Factory | ManyToMany | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -352,7 +352,7 @@ test.group('Factory | ManyToMany | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -412,7 +412,7 @@ test.group('Factory | ManyToMany | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(4) @@ -472,7 +472,7 @@ test.group('Factory | ManyToMany | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) diff --git a/test/fixtures/config/app.ts b/test/fixtures/config/app.ts deleted file mode 100644 index ec4a98c9..00000000 --- a/test/fixtures/config/app.ts +++ /dev/null @@ -1,216 +0,0 @@ -/** - * Config source: https://git.io/JfefZ - * - * Feel free to let us know via PR, if you find something broken in this config - * file. - */ - -/* -|-------------------------------------------------------------------------- -| Application secret key -|-------------------------------------------------------------------------- -| -| The secret to encrypt and sign different values in your application. -| Make sure to keep the `APP_KEY` as an environment variable and secure. -| -| Note: Changing the application key for an existing app will make all -| the cookies invalid and also the existing encrypted data will not -| be decrypted. -| -*/ -export const appKey: string = 'alongrandomsecretkey' - -/* -|-------------------------------------------------------------------------- -| Http server configuration -|-------------------------------------------------------------------------- -| -| The configuration for the HTTP(s) server. Make sure to go through all -| the config properties to make keep server secure. -| -*/ -export const http = { - /* - |-------------------------------------------------------------------------- - | Allow method spoofing - |-------------------------------------------------------------------------- - | - | Method spoofing enables defining custom HTTP methods using a query string - | `_method`. This is usually required when you are making traditional - | form requests and wants to use HTTP verbs like `PUT`, `DELETE` and - | so on. - | - */ - allowMethodSpoofing: false, - - /* - |-------------------------------------------------------------------------- - | Subdomain offset - |-------------------------------------------------------------------------- - */ - subdomainOffset: 2, - - /* - |-------------------------------------------------------------------------- - | Request Ids - |-------------------------------------------------------------------------- - | - | Setting this value to `true` will generate a unique request id for each - | HTTP request and set it as `x-request-id` header. - | - */ - generateRequestId: false, - - /* - |-------------------------------------------------------------------------- - | Trusting proxy servers - |-------------------------------------------------------------------------- - | - | Define the proxy servers that AdonisJs must trust for reading `X-Forwarded` - | headers. - | - */ - trustProxy: () => true, - - /* - |-------------------------------------------------------------------------- - | Generating Etag - |-------------------------------------------------------------------------- - | - | Whether or not to generate an etag for every response. - | - */ - etag: false, - - /* - |-------------------------------------------------------------------------- - | JSONP Callback - |-------------------------------------------------------------------------- - */ - jsonpCallbackName: 'callback', - - /* - |-------------------------------------------------------------------------- - | Cookie settings - |-------------------------------------------------------------------------- - */ - cookie: { - domain: '', - path: '/', - maxAge: '2h', - httpOnly: true, - secure: false, - sameSite: false, - }, - - /* - |-------------------------------------------------------------------------- - | Force content negotiation to JSON - |-------------------------------------------------------------------------- - | - | The internals of the framework relies on the content negotiation to - | detect the best possible response type for a given HTTP request. - | - | However, it is a very common these days that API servers always wants to - | make response in JSON regardless of the existence of the `Accept` header. - | - | By setting `forceContentNegotiationToJSON = true`, you negotiate with the - | server in advance to always return JSON without relying on the client - | to set the header explicitly. - | - */ - forceContentNegotiationToJSON: true, -} - -/* -|-------------------------------------------------------------------------- -| Logger -|-------------------------------------------------------------------------- -*/ -export const logger = { - /* - |-------------------------------------------------------------------------- - | Application name - |-------------------------------------------------------------------------- - | - | The name of the application you want to add to the log. It is recommended - | to always have app name in every log line. - | - | The `APP_NAME` environment variable is automatically set by AdonisJS by - | reading the `name` property from the `package.json` file. - | - */ - name: 'AdonisJS', - - /* - |-------------------------------------------------------------------------- - | Toggle logger - |-------------------------------------------------------------------------- - | - | Enable or disable logger application wide - | - */ - enabled: true, - - /* - |-------------------------------------------------------------------------- - | Logging level - |-------------------------------------------------------------------------- - | - | The level from which you want the logger to flush logs. It is recommended - | to make use of the environment variable, so that you can define log levels - | at deployment level and not code level. - | - */ - level: 'info', - - /* - |-------------------------------------------------------------------------- - | Pretty print - |-------------------------------------------------------------------------- - | - | It is highly advised NOT to use `prettyPrint` in production, since it - | can have huge impact on performance. - | - */ - prettyPrint: false, -} - -/* -|-------------------------------------------------------------------------- -| Profiler -|-------------------------------------------------------------------------- -*/ -export const profiler = { - /* - |-------------------------------------------------------------------------- - | Toggle profiler - |-------------------------------------------------------------------------- - | - | Enable or disable profiler - | - */ - enabled: true, - - /* - |-------------------------------------------------------------------------- - | Blacklist actions/row labels - |-------------------------------------------------------------------------- - | - | Define an array of actions or row labels that you want to disable from - | getting profiled. - | - */ - blacklist: [], - - /* - |-------------------------------------------------------------------------- - | Whitelist actions/row labels - |-------------------------------------------------------------------------- - | - | Define an array of actions or row labels that you want to whitelist for - | the profiler. When whitelist is defined, then `blacklist` is ignored. - | - */ - whitelist: [], -} diff --git a/test/fixtures/config/database.ts b/test/fixtures/config/database.ts deleted file mode 100644 index b1c89f87..00000000 --- a/test/fixtures/config/database.ts +++ /dev/null @@ -1,6 +0,0 @@ -export const connection = 'sqlite' -export const connections = { - sqlite: { - healthCheck: true, - }, -} diff --git a/test/migrations/migrator.spec.ts b/test/migrations/migrator.spec.ts index 2d0a08db..0b7c76ea 100644 --- a/test/migrations/migrator.spec.ts +++ b/test/migrations/migrator.spec.ts @@ -62,7 +62,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v1.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -115,7 +115,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v2.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -130,7 +130,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v2.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -190,7 +190,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v3.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -204,7 +204,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v3.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -277,7 +277,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v4.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -291,7 +291,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v4.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -351,7 +351,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v5.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -368,7 +368,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v5.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -411,7 +411,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v6.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -432,7 +432,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v6.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -489,7 +489,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v7.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -510,7 +510,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v7.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -563,7 +563,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v8.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -584,7 +584,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v8.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -648,7 +648,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v9.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -669,7 +669,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v9.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -751,7 +751,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v10.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -772,7 +772,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v10.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -839,7 +839,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v11.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -857,7 +857,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v11.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -907,7 +907,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v12.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -925,7 +925,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v12.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -961,7 +961,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v13.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -975,7 +975,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v13.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -1043,7 +1043,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/12_users.ts', ` - import { Schema } from '../../../../../src/Schema' + import { BaseSchema as Schema } from '../../../../../src/Schema' module.exports = class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -1060,7 +1060,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/1_accounts.ts', ` - import { Schema } from '../../../../../src/Schema' + import { BaseSchema as Schema } from '../../../../../src/Schema' module.exports = class User extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -1104,7 +1104,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/1/12_users.ts', ` - import { Schema } from '../../../../../src/Schema' + import { BaseSchema as Schema } from '../../../../../src/Schema' module.exports = class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -1121,7 +1121,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/12/1_accounts.ts', ` - import { Schema } from '../../../../../src/Schema' + import { BaseSchema as Schema } from '../../../../../src/Schema' module.exports = class User extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -1165,7 +1165,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v14.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -1187,7 +1187,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/accounts_v14.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { @@ -1236,7 +1236,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v15.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { @@ -1299,7 +1299,7 @@ test.group('Migrator', (group) => { await fs.create( 'database/migrations/users_v16.ts', ` - import { Schema } from '../../../../src/schema/main.js' + import { BaseSchema as Schema } from '../../../../src/schema/main.js' export default class extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { diff --git a/test/orm/adapter.spec.ts b/test/orm/adapter.spec.ts index e30b691b..5780c098 100644 --- a/test/orm/adapter.spec.ts +++ b/test/orm/adapter.spec.ts @@ -27,7 +27,7 @@ test.group('Adapter', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -56,7 +56,7 @@ test.group('Adapter', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -90,7 +90,7 @@ test.group('Adapter', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -124,7 +124,7 @@ test.group('Adapter', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -160,7 +160,7 @@ test.group('Adapter', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -196,7 +196,7 @@ test.group('Adapter', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -232,7 +232,7 @@ test.group('Adapter', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -263,7 +263,7 @@ test.group('Adapter', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -301,7 +301,7 @@ test.group('Adapter', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -341,7 +341,7 @@ test.group('Adapter', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' diff --git a/test/orm/base_model.spec.ts b/test/orm/base_model.spec.ts index afb1910e..bc5f0026 100644 --- a/test/orm/base_model.spec.ts +++ b/test/orm/base_model.spec.ts @@ -68,7 +68,7 @@ test.group('Base model | boot', (group) => { const adapter = new FakeAdapter() await app.init() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -93,7 +93,7 @@ test.group('Base model | boot', (group) => { const adapter = new FakeAdapter() await app.init() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -117,7 +117,7 @@ test.group('Base model | boot', (group) => { const adapter = new FakeAdapter() await app.init() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -141,7 +141,7 @@ test.group('Base model | boot', (group) => { const adapter = new FakeAdapter() await app.init() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -163,7 +163,7 @@ test.group('Base model | boot', (group) => { const adapter = new FakeAdapter() await app.init() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -181,7 +181,7 @@ test.group('Base model | boot', (group) => { const app = new AppFactory().create(fs.baseUrl, () => {}) const adapter = new FakeAdapter() await app.init() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static table = 'my_users' @@ -201,7 +201,7 @@ test.group('Base model | boot', (group) => { const app = new AppFactory().create(fs.baseUrl, () => {}) const adapter = new FakeAdapter() await app.init() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel {} @@ -215,7 +215,7 @@ test.group('Base model | boot', (group) => { const app = new AppFactory().create(fs.baseUrl, () => {}) const adapter = new FakeAdapter() await app.init() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static $increments = false @@ -235,7 +235,7 @@ test.group('Base model | boot', (group) => { const app = new AppFactory().create(fs.baseUrl, () => {}) const adapter = new FakeAdapter() await app.init() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static $increments = false @@ -255,7 +255,7 @@ test.group('Base model | boot', (group) => { const app = new AppFactory().create(fs.baseUrl, () => {}) const adapter = new FakeAdapter() await app.init() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static $increments = false @@ -275,7 +275,7 @@ test.group('Base model | boot', (group) => { const app = new AppFactory().create(fs.baseUrl, () => {}) const adapter = new FakeAdapter() await app.init() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static $increments = false @@ -295,7 +295,7 @@ test.group('Base model | boot', (group) => { const app = new AppFactory().create(fs.baseUrl, () => {}) const adapter = new FakeAdapter() await app.init() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static $increments = false @@ -315,7 +315,7 @@ test.group('Base model | boot', (group) => { const app = new AppFactory().create(fs.baseUrl, () => {}) const adapter = new FakeAdapter() await app.init() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static $increments = false @@ -347,7 +347,7 @@ test.group('Base Model | options', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -377,7 +377,7 @@ test.group('Base Model | getter-setters', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -396,7 +396,7 @@ test.group('Base Model | getter-setters', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -417,7 +417,7 @@ test.group('Base Model | getter-setters', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { declare username: string @@ -437,7 +437,7 @@ test.group('Base Model | getter-setters', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -456,7 +456,7 @@ test.group('Base Model | getter-setters', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -477,7 +477,7 @@ test.group('Base Model | getter-setters', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { username = 'virk' @@ -494,7 +494,7 @@ test.group('Base Model | getter-setters', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -516,7 +516,7 @@ test.group('Base Model | getter-setters', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -540,7 +540,7 @@ test.group('Base Model | getter-setters', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -568,7 +568,7 @@ test.group('Base Model | getter-setters', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -627,7 +627,7 @@ test.group('Base Model | dirty', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -647,7 +647,7 @@ test.group('Base Model | dirty', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -670,7 +670,7 @@ test.group('Base Model | dirty', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -693,7 +693,7 @@ test.group('Base Model | dirty', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -715,7 +715,7 @@ test.group('Base Model | dirty', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -745,7 +745,7 @@ test.group('Base Model | dirty', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -777,7 +777,7 @@ test.group('Base Model | dirty', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Location { isDirty = false @@ -832,7 +832,7 @@ test.group('Base Model | persist', (group) => { const adapter = new FakeAdapter() await app.init() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -875,7 +875,7 @@ test.group('Base Model | persist', (group) => { const adapter = new FakeAdapter() await app.init() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -913,7 +913,7 @@ test.group('Base Model | persist', (group) => { const adapter = new FakeAdapter() await app.init() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -948,7 +948,7 @@ test.group('Base Model | persist', (group) => { const adapter = new FakeAdapter() await app.init() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -981,7 +981,7 @@ test.group('Base Model | persist', (group) => { const adapter = new FakeAdapter() await app.init() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -1021,7 +1021,7 @@ test.group('Base Model | persist', (group) => { const adapter = new FakeAdapter() await app.init() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -1050,7 +1050,7 @@ test.group('Base Model | persist', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1086,7 +1086,7 @@ test.group('Base Model | persist', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1140,7 +1140,7 @@ test.group('Base Model | persist', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1180,7 +1180,7 @@ test.group('Base Model | persist', (group) => { const app = new AppFactory().create(fs.baseUrl, () => {}) await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -1216,7 +1216,7 @@ test.group('Base Model | persist', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1254,7 +1254,7 @@ test.group('Base Model | persist', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1288,7 +1288,7 @@ test.group('Base Model | persist', (group) => { const db = await getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static table = 'uuid_users' @@ -1334,7 +1334,7 @@ test.group('Base Model | persist', (group) => { const db = await getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static table = 'uuid_users' @@ -1380,7 +1380,7 @@ test.group('Self assign primary key', () => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static selfAssignPrimaryKey = true @@ -1419,7 +1419,7 @@ test.group('Self assign primary key', () => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static selfAssignPrimaryKey = true @@ -1475,7 +1475,7 @@ test.group('Base Model | create from adapter results', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -1503,7 +1503,7 @@ test.group('Base Model | create from adapter results', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -1531,7 +1531,7 @@ test.group('Base Model | create from adapter results', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -1553,7 +1553,7 @@ test.group('Base Model | create from adapter results', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -1587,7 +1587,7 @@ test.group('Base Model | create from adapter results', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -1625,7 +1625,7 @@ test.group('Base Model | create from adapter results', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -1653,7 +1653,7 @@ test.group('Base Model | create from adapter results', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -1679,7 +1679,7 @@ test.group('Base Model | create from adapter results', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -1717,7 +1717,7 @@ test.group('Base Model | delete', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -1745,7 +1745,7 @@ test.group('Base Model | delete', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -1771,7 +1771,7 @@ test.group('Base Model | serializeAttributes', () => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -1789,7 +1789,7 @@ test.group('Base Model | serializeAttributes', () => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ serialize: (value) => value.toUpperCase() }) @@ -1807,7 +1807,7 @@ test.group('Base Model | serializeAttributes', () => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ serializeAs: 'uname' }) @@ -1825,7 +1825,7 @@ test.group('Base Model | serializeAttributes', () => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ serializeAs: null }) @@ -1843,7 +1843,7 @@ test.group('Base Model | serializeAttributes', () => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -1865,7 +1865,7 @@ test.group('Base Model | serializeAttributes', () => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -1892,7 +1892,7 @@ test.group('Base Model | serializeAttributes', () => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -1923,7 +1923,7 @@ test.group('Base Model | serializeAttributes', () => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -1945,7 +1945,7 @@ test.group('Base Model | serializeAttributes', () => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ serialize: (value) => value.toUpperCase() }) @@ -1963,7 +1963,7 @@ test.group('Base Model | serializeAttributes', () => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ serializeAs: 'uname' }) @@ -1981,7 +1981,7 @@ test.group('Base Model | serializeAttributes', () => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ serializeAs: null }) @@ -1999,7 +1999,7 @@ test.group('Base Model | serializeAttributes', () => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -2021,7 +2021,7 @@ test.group('Base Model | serializeAttributes', () => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -2054,7 +2054,7 @@ test.group('Base Model | serializeRelations', () => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -2091,7 +2091,7 @@ test.group('Base Model | serializeRelations', () => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -2128,7 +2128,7 @@ test.group('Base Model | serializeRelations', () => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -2160,7 +2160,7 @@ test.group('Base Model | serializeRelations', () => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -2194,7 +2194,7 @@ test.group('Base Model | serializeRelations', () => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -2231,7 +2231,7 @@ test.group('Base Model | serializeRelations', () => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -2263,7 +2263,7 @@ test.group('Base Model | serializeRelations', () => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -2309,7 +2309,7 @@ test.group('Base Model | serializeRelations', () => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -2354,7 +2354,7 @@ test.group('Base Model | serializeRelations', () => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -2405,7 +2405,7 @@ test.group('Base Model | toJSON', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -2423,7 +2423,7 @@ test.group('Base Model | toJSON', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ serializeAs: 'theUsername' }) @@ -2441,7 +2441,7 @@ test.group('Base Model | toJSON', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ serializeAs: null }) @@ -2459,7 +2459,7 @@ test.group('Base Model | toJSON', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -2482,7 +2482,7 @@ test.group('Base Model | toJSON', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -2505,7 +2505,7 @@ test.group('Base Model | toJSON', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -2533,7 +2533,7 @@ test.group('Base Model | toJSON', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { serializeExtras = true @@ -2565,7 +2565,7 @@ test.group('Base Model | toJSON', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { serializeExtras() { @@ -2603,7 +2603,7 @@ test.group('Base Model | toJSON', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -2624,7 +2624,7 @@ test.group('Base Model | toJSON', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -2657,7 +2657,7 @@ test.group('BaseModel | cache', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -2686,7 +2686,7 @@ test.group('BaseModel | cache', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -2727,7 +2727,7 @@ test.group('BaseModel | fill/merge', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -2744,7 +2744,7 @@ test.group('BaseModel | fill/merge', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -2767,7 +2767,7 @@ test.group('BaseModel | fill/merge', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -2785,7 +2785,7 @@ test.group('BaseModel | fill/merge', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -2808,7 +2808,7 @@ test.group('BaseModel | fill/merge', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -2831,7 +2831,7 @@ test.group('BaseModel | fill/merge', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -2854,7 +2854,7 @@ test.group('BaseModel | fill/merge', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -2883,7 +2883,7 @@ test.group('BaseModel | fill/merge', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -2900,7 +2900,7 @@ test.group('BaseModel | fill/merge', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -2926,7 +2926,7 @@ test.group('BaseModel | fill/merge', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -2952,7 +2952,7 @@ test.group('BaseModel | fill/merge', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Super extends BaseModel { foo!: string @@ -2993,7 +2993,7 @@ test.group('Base | apdater', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -3023,7 +3023,7 @@ test.group('Base | apdater', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -3058,7 +3058,7 @@ test.group('Base | apdater', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -3093,7 +3093,7 @@ test.group('Base | apdater', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ columnName: 'first_name' }) @@ -3133,7 +3133,7 @@ test.group('Base Model | sideloaded', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -3155,7 +3155,7 @@ test.group('Base Model | sideloaded', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -3175,7 +3175,7 @@ test.group('Base Model | sideloaded', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -3211,7 +3211,7 @@ test.group('Base Model | relations', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -3243,7 +3243,7 @@ test.group('Base Model | relations', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -3275,7 +3275,7 @@ test.group('Base Model | relations', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -3311,7 +3311,7 @@ test.group('Base Model | relations', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -3360,7 +3360,7 @@ test.group('Base Model | relations', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -3428,7 +3428,7 @@ test.group('Base Model | relations', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -3464,7 +3464,7 @@ test.group('Base Model | relations', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -3502,7 +3502,7 @@ test.group('Base Model | relations', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -3544,7 +3544,7 @@ test.group('Base Model | relations', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -3588,7 +3588,7 @@ test.group('Base Model | relations', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -3622,7 +3622,7 @@ test.group('Base Model | relations', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -3670,7 +3670,7 @@ test.group('Base Model | fetch', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -3698,7 +3698,7 @@ test.group('Base Model | fetch', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -3724,7 +3724,7 @@ test.group('Base Model | fetch', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -3754,7 +3754,7 @@ test.group('Base Model | fetch', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -3784,7 +3784,7 @@ test.group('Base Model | fetch', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -3820,7 +3820,7 @@ test.group('Base Model | fetch', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -3853,7 +3853,7 @@ test.group('Base Model | fetch', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -3886,7 +3886,7 @@ test.group('Base Model | fetch', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -3920,7 +3920,7 @@ test.group('Base Model | fetch', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -3978,7 +3978,7 @@ test.group('Base Model | fetch', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -4018,7 +4018,7 @@ test.group('Base Model | fetch', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -4057,7 +4057,7 @@ test.group('Base Model | fetch', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -4097,7 +4097,7 @@ test.group('Base Model | fetch', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -4151,7 +4151,7 @@ test.group('Base Model | fetch', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -4214,7 +4214,7 @@ test.group('Base Model | fetch', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -4270,7 +4270,7 @@ test.group('Base Model | fetch', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -4335,7 +4335,7 @@ test.group('Base Model | fetch', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -4396,7 +4396,7 @@ test.group('Base Model | fetch', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -4447,7 +4447,7 @@ test.group('Base Model | fetch', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -4493,7 +4493,7 @@ test.group('Base Model | fetch', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -4547,7 +4547,7 @@ test.group('Base Model | fetch', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -4611,7 +4611,7 @@ test.group('Base Model | fetch', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -4687,7 +4687,7 @@ test.group('Base Model | fetch', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -4746,7 +4746,7 @@ test.group('Base Model | fetch', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -4804,7 +4804,7 @@ test.group('Base Model | fetch', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -4879,7 +4879,7 @@ test.group('Base Model | hooks', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) const stack: string[] = [] @@ -4942,7 +4942,7 @@ test.group('Base Model | hooks', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5002,7 +5002,7 @@ test.group('Base Model | hooks', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5042,7 +5042,7 @@ test.group('Base Model | hooks', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5082,7 +5082,7 @@ test.group('Base Model | hooks', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5138,7 +5138,7 @@ test.group('Base Model | hooks', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5204,7 +5204,7 @@ test.group('Base Model | hooks', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5243,7 +5243,7 @@ test.group('Base Model | hooks', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5294,7 +5294,7 @@ test.group('Base Model | hooks', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5328,7 +5328,7 @@ test.group('Base Model | hooks', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5361,7 +5361,7 @@ test.group('Base Model | hooks', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5396,7 +5396,7 @@ test.group('Base Model | hooks', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5431,7 +5431,7 @@ test.group('Base Model | hooks', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5466,7 +5466,7 @@ test.group('Base Model | hooks', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5504,7 +5504,7 @@ test.group('Base Model | hooks', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5537,7 +5537,7 @@ test.group('Base Model | hooks', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5570,7 +5570,7 @@ test.group('Base Model | hooks', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5599,7 +5599,7 @@ test.group('Base Model | hooks', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5639,7 +5639,7 @@ test.group('Base Model | aggregates', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5673,7 +5673,7 @@ test.group('Base Model | aggregates', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5721,7 +5721,7 @@ test.group('Base Model | date', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5747,7 +5747,7 @@ test.group('Base Model | date', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5773,7 +5773,7 @@ test.group('Base Model | date', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5800,7 +5800,7 @@ test.group('Base Model | date', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5834,7 +5834,7 @@ test.group('Base Model | date', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5869,7 +5869,7 @@ test.group('Base Model | date', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5902,7 +5902,7 @@ test.group('Base Model | date', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5932,7 +5932,7 @@ test.group('Base Model | date', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5963,7 +5963,7 @@ test.group('Base Model | date', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -5993,7 +5993,7 @@ test.group('Base Model | date', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6025,7 +6025,7 @@ test.group('Base Model | date', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6057,7 +6057,7 @@ test.group('Base Model | date', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6089,7 +6089,7 @@ test.group('Base Model | date', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6113,7 +6113,7 @@ test.group('Base Model | date', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6137,7 +6137,7 @@ test.group('Base Model | date', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6164,7 +6164,7 @@ test.group('Base Model | date', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6210,7 +6210,7 @@ test.group('Base Model | datetime', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6236,7 +6236,7 @@ test.group('Base Model | datetime', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6262,7 +6262,7 @@ test.group('Base Model | datetime', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6288,7 +6288,7 @@ test.group('Base Model | datetime', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6327,7 +6327,7 @@ test.group('Base Model | datetime', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6357,7 +6357,7 @@ test.group('Base Model | datetime', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6389,7 +6389,7 @@ test.group('Base Model | datetime', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6421,7 +6421,7 @@ test.group('Base Model | datetime', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6453,7 +6453,7 @@ test.group('Base Model | datetime', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6477,7 +6477,7 @@ test.group('Base Model | datetime', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6502,7 +6502,7 @@ test.group('Base Model | datetime', (group) => { await app.init() const adapter = new FakeAdapter() - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6535,7 +6535,7 @@ test.group('Base Model | datetime', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6563,7 +6563,7 @@ test.group('Base Model | datetime', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6601,7 +6601,7 @@ test.group('Base Model | datetime', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6635,7 +6635,7 @@ test.group('Base Model | datetime', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6671,7 +6671,7 @@ test.group('Base Model | datetime', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6706,7 +6706,7 @@ test.group('Base Model | datetime', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6748,7 +6748,7 @@ test.group('Base Model | paginate', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6796,7 +6796,7 @@ test.group('Base Model | paginate', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6841,7 +6841,7 @@ test.group('Base Model | paginate', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6889,7 +6889,7 @@ test.group('Base Model | paginate', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -6950,7 +6950,7 @@ test.group('Base Model | paginate', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -7014,7 +7014,7 @@ test.group('Base Model | toObject', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -7033,7 +7033,7 @@ test.group('Base Model | toObject', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ serializeAs: 'theUserName', columnName: 'user_name' }) @@ -7052,7 +7052,7 @@ test.group('Base Model | toObject', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -7076,7 +7076,7 @@ test.group('Base Model | toObject', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column() @@ -7100,7 +7100,7 @@ test.group('Base Model | toObject', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -7140,7 +7140,7 @@ test.group('Base Model | toObject', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Comment extends BaseModel { @column() @@ -7218,7 +7218,7 @@ test.group('Base model | inheritance', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class MyBaseModel extends BaseModel { static primaryKey = 'user_id' @@ -7244,7 +7244,7 @@ test.group('Base model | inheritance', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class MyBaseModel extends BaseModel { static primaryKey = 'user_id' @@ -7272,7 +7272,7 @@ test.group('Base model | inheritance', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class MyBaseModel extends BaseModel { static table = 'foo' @@ -7298,7 +7298,7 @@ test.group('Base model | inheritance', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class MyBaseModel extends BaseModel { @column({ isPrimary: true }) @@ -7401,7 +7401,7 @@ test.group('Base model | inheritance', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class MyBaseModel extends BaseModel { @column({ isPrimary: true }) @@ -7507,7 +7507,7 @@ test.group('Base model | inheritance', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class MyBaseModel extends BaseModel { @computed() @@ -7609,7 +7609,7 @@ test.group('Base model | inheritance', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class MyBaseModel extends BaseModel { @computed() @@ -7704,7 +7704,7 @@ test.group('Base model | inheritance', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -7746,7 +7746,7 @@ test.group('Base model | inheritance', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class SocialProfile extends BaseModel { @column() @@ -7802,7 +7802,7 @@ test.group('Base model | inheritance', (group) => { const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -7854,7 +7854,7 @@ test.group('Base model | inheritance', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class MyBaseModel extends BaseModel { static boot() { diff --git a/test/orm/base_model_options.spec.ts b/test/orm/base_model_options.spec.ts index ca529d24..c327d8c3 100644 --- a/test/orm/base_model_options.spec.ts +++ b/test/orm/base_model_options.spec.ts @@ -39,7 +39,7 @@ test.group('Model options | QueryBuilder', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -64,7 +64,7 @@ test.group('Model options | QueryBuilder', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -88,7 +88,7 @@ test.group('Model options | QueryBuilder', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -120,7 +120,7 @@ test.group('Model options | QueryBuilder', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -166,7 +166,7 @@ test.group('Model options | Adapter', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -189,7 +189,7 @@ test.group('Model options | Adapter', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -214,7 +214,7 @@ test.group('Model options | Adapter', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -254,7 +254,7 @@ test.group('Model options | Model.find', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -277,7 +277,7 @@ test.group('Model options | Model.find', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -315,7 +315,7 @@ test.group('Model options | Model.findOrFail', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -338,7 +338,7 @@ test.group('Model options | Model.findOrFail', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -376,7 +376,7 @@ test.group('Model options | Model.findMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -399,7 +399,7 @@ test.group('Model options | Model.findMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -437,7 +437,7 @@ test.group('Model options | Model.firstOrCreate', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -465,7 +465,7 @@ test.group('Model options | Model.firstOrCreate', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -493,7 +493,7 @@ test.group('Model options | Model.firstOrCreate', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -520,7 +520,7 @@ test.group('Model options | Model.firstOrCreate', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -547,7 +547,7 @@ test.group('Model options | Model.firstOrCreate', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -576,7 +576,7 @@ test.group('Model options | Model.firstOrCreate', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -618,7 +618,7 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -647,7 +647,7 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -674,7 +674,7 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -702,7 +702,7 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -731,7 +731,7 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -765,7 +765,7 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -815,7 +815,7 @@ test.group('Model options | Model.updateOrCreateMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -845,7 +845,7 @@ test.group('Model options | Model.updateOrCreateMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -873,7 +873,7 @@ test.group('Model options | Model.updateOrCreateMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -901,7 +901,7 @@ test.group('Model options | Model.updateOrCreateMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -930,7 +930,7 @@ test.group('Model options | Model.updateOrCreateMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -964,7 +964,7 @@ test.group('Model options | Model.updateOrCreateMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { static$table = 'users' @@ -1014,7 +1014,7 @@ test.group('Model options | Query Builder Preloads', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -1053,7 +1053,7 @@ test.group('Model options | Query Builder Preloads', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -1095,7 +1095,7 @@ test.group('Model options | Query Builder Preloads', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -1136,7 +1136,7 @@ test.group('Model options | Query Builder Preloads', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -1182,7 +1182,7 @@ test.group('Model options | Query Builder Preloads', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -1229,7 +1229,7 @@ test.group('Model options | Query Builder Preloads', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -1292,7 +1292,7 @@ test.group('Model options | Model Preloads', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -1332,7 +1332,7 @@ test.group('Model options | Model Preloads', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -1371,7 +1371,7 @@ test.group('Model options | Model Preloads', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) diff --git a/test/orm/model_belongs_to.spec.ts b/test/orm/model_belongs_to.spec.ts index fab36948..f9bcad53 100644 --- a/test/orm/model_belongs_to.spec.ts +++ b/test/orm/model_belongs_to.spec.ts @@ -39,7 +39,7 @@ test.group('Model | BelongsTo | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) try { class User extends BaseModel {} @@ -64,7 +64,7 @@ test.group('Model | BelongsTo | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) try { class User extends BaseModel { @@ -94,7 +94,7 @@ test.group('Model | BelongsTo | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -119,7 +119,7 @@ test.group('Model | BelongsTo | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -147,7 +147,7 @@ test.group('Model | BelongsTo | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -172,7 +172,7 @@ test.group('Model | BelongsTo | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -197,7 +197,7 @@ test.group('Model | BelongsTo | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -237,7 +237,7 @@ test.group('Model | BelongsTo | Set Relations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -269,7 +269,7 @@ test.group('Model | BelongsTo | Set Relations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -308,7 +308,7 @@ test.group('Model | BelongsTo | Set Relations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -365,7 +365,7 @@ test.group('Model | BelongsTo | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -402,7 +402,7 @@ test.group('Model | BelongsTo | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -444,7 +444,7 @@ test.group('Model | BelongsTo | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -487,7 +487,7 @@ test.group('Model | BelongsTo | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -538,7 +538,7 @@ test.group('Model | BelongsTo | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -582,7 +582,7 @@ test.group('Model | BelongsTo | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -631,7 +631,7 @@ test.group('Model | BelongsTo | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -680,7 +680,7 @@ test.group('Model | BelongsTo | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -721,7 +721,7 @@ test.group('Model | BelongsTo | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -769,7 +769,7 @@ test.group('Model | BelongsTo | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -835,7 +835,7 @@ test.group('Model | BelongsTo | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -866,7 +866,7 @@ test.group('Model | BelongsTo | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -896,7 +896,7 @@ test.group('Model | BelongsTo | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -926,7 +926,7 @@ test.group('Model | BelongsTo | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -969,7 +969,7 @@ test.group('Model | BelongsTo | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1014,7 +1014,7 @@ test.group('Model | BelongsTo | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1063,7 +1063,7 @@ test.group('Model | BelongsTo | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1114,7 +1114,7 @@ test.group('Model | BelongsTo | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1167,7 +1167,7 @@ test.group('Model | BelongsTo | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1220,7 +1220,7 @@ test.group('Model | BelongsTo | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1301,7 +1301,7 @@ test.group('Model | BelongsTo | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1382,7 +1382,7 @@ test.group('Model | BelongsTo | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1466,7 +1466,7 @@ test.group('Model | BelongsTo | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1496,7 +1496,7 @@ test.group('Model | BelongsTo | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1527,7 +1527,7 @@ test.group('Model | BelongsTo | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1569,7 +1569,7 @@ test.group('Model | BelongsTo | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1600,7 +1600,7 @@ test.group('Model | BelongsTo | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1634,7 +1634,7 @@ test.group('Model | BelongsTo | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1682,7 +1682,7 @@ test.group('Model | BelongsTo | has', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1732,7 +1732,7 @@ test.group('Model | BelongsTo | whereHas', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1800,7 +1800,7 @@ test.group('Model | BelongsTo | associate', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1844,7 +1844,7 @@ test.group('Model | BelongsTo | associate', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1901,7 +1901,7 @@ test.group('Model | BelongsTo | dissociate', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1965,7 +1965,7 @@ test.group('Model | BelongsTo | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -2009,7 +2009,7 @@ test.group('Model | BelongsTo | clone', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -2060,7 +2060,7 @@ test.group('Model | BelongsTo | scopes', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -2106,7 +2106,7 @@ test.group('Model | BelongsTo | scopes', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -2169,7 +2169,7 @@ test.group('Model | BelongsTo | onQuery', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -2210,7 +2210,7 @@ test.group('Model | BelongsTo | onQuery', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -2255,7 +2255,7 @@ test.group('Model | BelongsTo | onQuery', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -2294,7 +2294,7 @@ test.group('Model | BelongsTo | onQuery', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) diff --git a/test/orm/model_has_many.spec.ts b/test/orm/model_has_many.spec.ts index 0fa44c65..bf5632e0 100644 --- a/test/orm/model_has_many.spec.ts +++ b/test/orm/model_has_many.spec.ts @@ -39,7 +39,7 @@ test.group('Model | HasMany | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(1) @@ -63,7 +63,7 @@ test.group('Model | HasMany | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(1) @@ -94,7 +94,7 @@ test.group('Model | HasMany | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -120,7 +120,7 @@ test.group('Model | HasMany | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -149,7 +149,7 @@ test.group('Model | HasMany | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -175,7 +175,7 @@ test.group('Model | HasMany | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column({ columnName: 'user_id' }) @@ -201,7 +201,7 @@ test.group('Model | HasMany | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column({ columnName: 'user_id' }) @@ -240,7 +240,7 @@ test.group('Model | HasMany | Set Relations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -273,7 +273,7 @@ test.group('Model | HasMany | Set Relations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -311,7 +311,7 @@ test.group('Model | HasMany | Set Relations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -372,7 +372,7 @@ test.group('Model | HasMany | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -411,7 +411,7 @@ test.group('Model | HasMany | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -452,7 +452,7 @@ test.group('Model | HasMany | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -498,7 +498,7 @@ test.group('Model | HasMany | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -535,7 +535,7 @@ test.group('Model | HasMany | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -582,7 +582,7 @@ test.group('Model | HasMany | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -639,7 +639,7 @@ test.group('Model | HasMany | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -677,7 +677,7 @@ test.group('Model | HasMany | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -720,7 +720,7 @@ test.group('Model | HasMany | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -763,7 +763,7 @@ test.group('Model | HasMany | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -804,7 +804,7 @@ test.group('Model | HasMany | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -845,7 +845,7 @@ test.group('Model | HasMany | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -905,7 +905,7 @@ test.group('Model | HasMany | aggregates', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -954,7 +954,7 @@ test.group('Model | HasMany | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -1006,7 +1006,7 @@ test.group('Model | HasMany | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -1040,7 +1040,7 @@ test.group('Model | HasMany | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column({ isPrimary: true }) @@ -1102,7 +1102,7 @@ test.group('Model | HasMany | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column({ isPrimary: true }) @@ -1162,7 +1162,7 @@ test.group('Model | HasMany | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column({ isPrimary: true }) @@ -1221,7 +1221,7 @@ test.group('Model | HasMany | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column({ isPrimary: true }) @@ -1280,7 +1280,7 @@ test.group('Model | HasMany | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(1) @@ -1337,7 +1337,7 @@ test.group('Model | HasMany | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Comment extends BaseModel { @column({ isPrimary: true }) @@ -1419,7 +1419,7 @@ test.group('Model | HasMany | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Comment extends BaseModel { @column({ isPrimary: true }) @@ -1510,7 +1510,7 @@ test.group('Model | HasMany | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Comment extends BaseModel { @column({ isPrimary: true }) @@ -1596,7 +1596,7 @@ test.group('Model | HasMany | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -1639,7 +1639,7 @@ test.group('Model | HasMany | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -1692,7 +1692,7 @@ test.group('Model | HasMany | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -1747,7 +1747,7 @@ test.group('Model | HasMany | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -1802,7 +1802,7 @@ test.group('Model | HasMany | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -1861,7 +1861,7 @@ test.group('Model | HasMany | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1920,7 +1920,7 @@ test.group('Model | HasMany | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -1977,7 +1977,7 @@ test.group('Model | HasMany | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Comment extends BaseModel { @column({ isPrimary: true }) @@ -2089,7 +2089,7 @@ test.group('Model | HasMany | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -2147,7 +2147,7 @@ test.group('Model | HasMany | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -2206,7 +2206,7 @@ test.group('Model | HasMany | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -2260,7 +2260,7 @@ test.group('Model | HasMany | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -2324,7 +2324,7 @@ test.group('Model | HasMany | has', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -2388,7 +2388,7 @@ test.group('Model | HasMany | has', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -2459,7 +2459,7 @@ test.group('Model | HasMany | has', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -2531,7 +2531,7 @@ test.group('Model | HasMany | has', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -2603,7 +2603,7 @@ test.group('Model | HasMany | has', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -2672,7 +2672,7 @@ test.group('Model | HasMany | has', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -2763,7 +2763,7 @@ test.group('Model | HasMany | whereHas', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -2837,7 +2837,7 @@ test.group('Model | HasMany | whereHas', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -2926,7 +2926,7 @@ test.group('Model | HasMany | whereHas', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -3012,7 +3012,7 @@ test.group('Model | HasMany | whereHas', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -3115,7 +3115,7 @@ test.group('Model | HasMany | whereHas', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -3223,7 +3223,7 @@ test.group('Model | HasMany | whereHas', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -3346,7 +3346,7 @@ if (process.env.DB !== 'mysql_legacy') { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -3465,7 +3465,7 @@ if (process.env.DB !== 'mysql_legacy') { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -3581,7 +3581,7 @@ if (process.env.DB !== 'mysql_legacy') { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -3688,7 +3688,7 @@ if (process.env.DB !== 'mysql_legacy') { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -3809,7 +3809,7 @@ if (process.env.DB !== 'mysql_legacy') { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -3890,7 +3890,7 @@ if (process.env.DB !== 'mysql_legacy') { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -3977,7 +3977,7 @@ if (process.env.DB !== 'mysql_legacy') { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Comment extends BaseModel { @column({ isPrimary: true }) @@ -4115,7 +4115,7 @@ if (process.env.DB !== 'mysql_legacy') { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Comment extends BaseModel { @column({ isPrimary: true }) @@ -4272,7 +4272,7 @@ test.group('Model | HasMany | save', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column({ isPrimary: true }) @@ -4334,7 +4334,7 @@ test.group('Model | HasMany | saveMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column({ isPrimary: true }) @@ -4388,7 +4388,7 @@ test.group('Model | HasMany | saveMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(6) @@ -4443,7 +4443,7 @@ test.group('Model | HasMany | saveMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column({ isPrimary: true }) @@ -4512,7 +4512,7 @@ test.group('Model | HasMany | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column({ isPrimary: true }) @@ -4571,7 +4571,7 @@ test.group('Model | HasMany | createMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column({ isPrimary: true }) @@ -4626,7 +4626,7 @@ test.group('Model | HasMany | createMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(4) @@ -4674,7 +4674,7 @@ test.group('Model | HasMany | createMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column({ isPrimary: true }) @@ -4735,7 +4735,7 @@ test.group('Model | HasMany | firstOrCreate', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column({ isPrimary: true }) @@ -4786,7 +4786,7 @@ test.group('Model | HasMany | firstOrCreate', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column({ isPrimary: true }) @@ -4851,7 +4851,7 @@ test.group('Model | HasMany | updateOrCreate', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column({ isPrimary: true }) @@ -4902,7 +4902,7 @@ test.group('Model | HasMany | updateOrCreate', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column({ isPrimary: true }) @@ -4968,7 +4968,7 @@ test.group('Model | HasMany | fetchOrCreateMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column({ isPrimary: true }) @@ -5019,7 +5019,7 @@ test.group('Model | HasMany | fetchOrCreateMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column({ isPrimary: true }) @@ -5103,7 +5103,7 @@ test.group('Model | HasMany | fetchOrCreateMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column({ isPrimary: true }) @@ -5154,7 +5154,7 @@ test.group('Model | HasMany | fetchOrCreateMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column({ isPrimary: true }) @@ -5250,7 +5250,7 @@ test.group('Model | HasMany | paginate', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -5307,7 +5307,7 @@ test.group('Model | HasMany | paginate', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(1) @@ -5357,7 +5357,7 @@ test.group('Model | HasMany | clone', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -5401,7 +5401,7 @@ test.group('Model | HasMany | scopes', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -5458,7 +5458,7 @@ test.group('Model | HasMany | scopes', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -5529,7 +5529,7 @@ test.group('Model | HasMany | onQuery', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -5576,7 +5576,7 @@ test.group('Model | HasMany | onQuery', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(3) @@ -5629,7 +5629,7 @@ test.group('Model | HasMany | onQuery', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -5677,7 +5677,7 @@ test.group('Model | HasMany | onQuery', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column() @@ -5757,7 +5757,7 @@ test.group('Model | HasMany | delete', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Post extends BaseModel { @column({ isPrimary: true }) diff --git a/test/orm/model_has_many_through.spec.ts b/test/orm/model_has_many_through.spec.ts index 751a544f..85a879aa 100644 --- a/test/orm/model_has_many_through.spec.ts +++ b/test/orm/model_has_many_through.spec.ts @@ -39,7 +39,7 @@ test.group('Model | Has Many Through | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) try { class User extends BaseModel {} @@ -70,7 +70,7 @@ test.group('Model | Has Many Through | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) try { class User extends BaseModel {} @@ -104,7 +104,7 @@ test.group('Model | Has Many Through | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) try { class User extends BaseModel { @@ -138,7 +138,7 @@ test.group('Model | Has Many Through | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) try { class User extends BaseModel { @@ -176,7 +176,7 @@ test.group('Model | Has Many Through | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -224,7 +224,7 @@ test.group('Model | Has Many Through | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -277,7 +277,7 @@ test.group('Model | Has Many Through | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -343,7 +343,7 @@ test.group('Model | Has Many Through | Set Relations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -383,7 +383,7 @@ test.group('Model | Has Many Through | Set Relations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -425,7 +425,7 @@ test.group('Model | Has Many Through | Set Relations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -508,7 +508,7 @@ test.group('Model | Has Many Through | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -557,7 +557,7 @@ test.group('Model | Has Many Through | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -609,7 +609,7 @@ test.group('Model | Has Many Through | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -667,7 +667,7 @@ test.group('Model | Has Many Through | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -731,7 +731,7 @@ test.group('Model | HasMany | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -777,7 +777,7 @@ test.group('Model | HasMany | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -828,7 +828,7 @@ test.group('Model | HasMany | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -879,7 +879,7 @@ test.group('Model | HasMany | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -930,7 +930,7 @@ test.group('Model | HasMany | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -979,7 +979,7 @@ test.group('Model | HasMany | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1045,7 +1045,7 @@ test.group('Model | Has Many Through | aggregates', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1102,7 +1102,7 @@ test.group('Model | Has Many Through | aggregates', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1183,7 +1183,7 @@ test.group('Model | Has Many Through | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1255,7 +1255,7 @@ test.group('Model | Has Many Through | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1329,7 +1329,7 @@ test.group('Model | Has Many Through | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1407,7 +1407,7 @@ test.group('Model | Has Many Through | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1484,7 +1484,7 @@ test.group('Model | Has Many Through | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1550,7 +1550,7 @@ test.group('Model | Has Many Through | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1607,7 +1607,7 @@ test.group('Model | Has Many Through | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1677,7 +1677,7 @@ test.group('Model | Has Many Through | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1751,7 +1751,7 @@ test.group('Model | Has Many Through | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1825,7 +1825,7 @@ test.group('Model | Has Many Through | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1898,7 +1898,7 @@ test.group('Model | Has Many Through | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1976,7 +1976,7 @@ test.group('Model | Has Many Through | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -2043,7 +2043,7 @@ test.group('Model | Has Many Through | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -2126,7 +2126,7 @@ test.group('Model | Has Many Through | has', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -2196,7 +2196,7 @@ test.group('Model | Has Many Through | has', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -2282,7 +2282,7 @@ test.group('Model | Has Many Through | whereHas', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -2358,7 +2358,7 @@ test.group('Model | Has Many Through | whereHas', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -2454,7 +2454,7 @@ if (process.env.DB !== 'mysql_legacy') { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -2549,7 +2549,7 @@ if (process.env.DB !== 'mysql_legacy') { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -2646,7 +2646,7 @@ if (process.env.DB !== 'mysql_legacy') { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -2750,7 +2750,7 @@ if (process.env.DB !== 'mysql_legacy') { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -2854,7 +2854,7 @@ if (process.env.DB !== 'mysql_legacy') { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -2933,7 +2933,7 @@ if (process.env.DB !== 'mysql_legacy') { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -3034,7 +3034,7 @@ test.group('Model | Has Many Through | pagination', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -3130,7 +3130,7 @@ test.group('Model | Has Many Through | pagination', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -3184,7 +3184,7 @@ test.group('Model | Has Many Through | clone', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -3269,7 +3269,7 @@ test.group('Model | Has Many Through | scopes', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -3356,7 +3356,7 @@ test.group('Model | Has Many Through | scopes', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -3455,7 +3455,7 @@ test.group('Model | Has Many Through | onQuery', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -3533,7 +3533,7 @@ test.group('Model | Has Many Through | onQuery', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -3616,7 +3616,7 @@ test.group('Model | Has Many Through | onQuery', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -3697,7 +3697,7 @@ test.group('Model | Has Many Through | onQuery', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) diff --git a/test/orm/model_has_one.spec.ts b/test/orm/model_has_one.spec.ts index a4636227..caef1414 100644 --- a/test/orm/model_has_one.spec.ts +++ b/test/orm/model_has_one.spec.ts @@ -38,7 +38,7 @@ test.group('Model | HasOne | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(1) @@ -62,7 +62,7 @@ test.group('Model | HasOne | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(1) @@ -93,7 +93,7 @@ test.group('Model | HasOne | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -120,7 +120,7 @@ test.group('Model | HasOne | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -150,7 +150,7 @@ test.group('Model | HasOne | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -177,7 +177,7 @@ test.group('Model | HasOne | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ columnName: 'user_id' }) @@ -204,7 +204,7 @@ test.group('Model | HasOne | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ columnName: 'user_id' }) @@ -244,7 +244,7 @@ test.group('Model | HasOne | Set Relations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -273,7 +273,7 @@ test.group('Model | HasOne | Set Relations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -302,7 +302,7 @@ test.group('Model | HasOne | Set Relations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column() @@ -360,7 +360,7 @@ test.group('Model | HasOne | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -406,7 +406,7 @@ test.group('Model | HasOne | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -454,7 +454,7 @@ test.group('Model | HasOne | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -506,7 +506,7 @@ test.group('Model | HasOne | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -566,7 +566,7 @@ test.group('Model | HasOne | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -610,7 +610,7 @@ test.group('Model | HasOne | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -659,7 +659,7 @@ test.group('Model | HasOne | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -708,7 +708,7 @@ test.group('Model | HasOne | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -749,7 +749,7 @@ test.group('Model | HasOne | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -797,7 +797,7 @@ test.group('Model | HasOne | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -863,7 +863,7 @@ test.group('Model | HasOne | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -921,7 +921,7 @@ test.group('Model | HasOne | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -961,7 +961,7 @@ test.group('Model | HasOne | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Identity extends BaseModel { @column({ isPrimary: true }) @@ -1044,7 +1044,7 @@ test.group('Model | HasOne | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -1102,7 +1102,7 @@ test.group('Model | HasOne | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -1159,7 +1159,7 @@ test.group('Model | HasOne | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -1216,7 +1216,7 @@ test.group('Model | HasOne | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -1273,7 +1273,7 @@ test.group('Model | HasOne | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -1330,7 +1330,7 @@ test.group('Model | HasOne | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -1386,7 +1386,7 @@ test.group('Model | HasOne | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(1) @@ -1441,7 +1441,7 @@ test.group('Model | HasOne | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Identity extends BaseModel { @column({ isPrimary: true }) @@ -1533,7 +1533,7 @@ test.group('Model | HasOne | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Identity extends BaseModel { @column({ isPrimary: true }) @@ -1620,7 +1620,7 @@ test.group('Model | HasOne | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -1669,7 +1669,7 @@ test.group('Model | HasOne | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -1724,7 +1724,7 @@ test.group('Model | HasOne | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -1782,7 +1782,7 @@ test.group('Model | HasOne | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -1836,7 +1836,7 @@ test.group('Model | HasOne | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -1881,7 +1881,7 @@ test.group('Model | HasOne | has', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -1948,7 +1948,7 @@ test.group('Model | HasOne | whereHas', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -2028,7 +2028,7 @@ test.group('Model | HasOne | save', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -2070,7 +2070,7 @@ test.group('Model | HasOne | save', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(3) @@ -2118,7 +2118,7 @@ test.group('Model | HasOne | save', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(4) @@ -2185,7 +2185,7 @@ test.group('Model | HasOne | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -2226,7 +2226,7 @@ test.group('Model | HasOne | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(3) @@ -2273,7 +2273,7 @@ test.group('Model | HasOne | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -2336,7 +2336,7 @@ test.group('Model | HasOne | firstOrCreate', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -2382,7 +2382,7 @@ test.group('Model | HasOne | firstOrCreate', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -2446,7 +2446,7 @@ test.group('Model | HasOne | updateOrCreate', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -2496,7 +2496,7 @@ test.group('Model | HasOne | updateOrCreate', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -2561,7 +2561,7 @@ test.group('Model | HasOne | pagination', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(1) @@ -2616,7 +2616,7 @@ test.group('Model | HasOne | clone', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(1) @@ -2668,7 +2668,7 @@ test.group('Model | HasOne | scopes', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -2722,7 +2722,7 @@ test.group('Model | HasOne | scopes', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -2792,7 +2792,7 @@ test.group('Model | HasOne | onQuery', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -2837,7 +2837,7 @@ test.group('Model | HasOne | onQuery', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(2) @@ -2889,7 +2889,7 @@ test.group('Model | HasOne | onQuery', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -2938,7 +2938,7 @@ test.group('Model | HasOne | onQuery', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) @@ -3018,7 +3018,7 @@ test.group('Model | HasOne | delete', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Profile extends BaseModel { @column({ isPrimary: true }) diff --git a/test/orm/model_many_to_many.spec.ts b/test/orm/model_many_to_many.spec.ts index 34b0bd1f..28695f3c 100644 --- a/test/orm/model_many_to_many.spec.ts +++ b/test/orm/model_many_to_many.spec.ts @@ -42,7 +42,7 @@ test.group('Model | ManyToMany | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(1) @@ -66,7 +66,7 @@ test.group('Model | ManyToMany | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -92,7 +92,7 @@ test.group('Model | ManyToMany | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -122,7 +122,7 @@ test.group('Model | ManyToMany | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(1) @@ -150,7 +150,7 @@ test.group('Model | ManyToMany | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -176,7 +176,7 @@ test.group('Model | ManyToMany | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -205,7 +205,7 @@ test.group('Model | ManyToMany | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -230,7 +230,7 @@ test.group('Model | ManyToMany | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -258,7 +258,7 @@ test.group('Model | ManyToMany | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -284,7 +284,7 @@ test.group('Model | ManyToMany | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -310,7 +310,7 @@ test.group('Model | ManyToMany | Options', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -348,7 +348,7 @@ test.group('Model | ManyToMany | Set Relations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -376,7 +376,7 @@ test.group('Model | ManyToMany | Set Relations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -407,7 +407,7 @@ test.group('Model | ManyToMany | Set Relations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -477,7 +477,7 @@ test.group('Model | ManyToMany | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -519,7 +519,7 @@ test.group('Model | ManyToMany | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -564,7 +564,7 @@ test.group('Model | ManyToMany | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -609,7 +609,7 @@ test.group('Model | ManyToMany | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -652,7 +652,7 @@ test.group('Model | ManyToMany | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -691,7 +691,7 @@ test.group('Model | ManyToMany | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -728,7 +728,7 @@ test.group('Model | ManyToMany | bulk operations', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -798,7 +798,7 @@ test.group('Model | ManyToMany | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -834,7 +834,7 @@ test.group('Model | ManyToMany | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -875,7 +875,7 @@ test.group('Model | ManyToMany | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -916,7 +916,7 @@ test.group('Model | ManyToMany | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -952,7 +952,7 @@ test.group('Model | ManyToMany | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -996,7 +996,7 @@ test.group('Model | ManyToMany | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -1037,7 +1037,7 @@ test.group('Model | ManyToMany | sub queries', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -1095,7 +1095,7 @@ test.group('Model | Many To Many | aggregates', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -1131,7 +1131,7 @@ test.group('Model | Many To Many | aggregates', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -1178,7 +1178,7 @@ test.group('Model | Many To Many | aggregates', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -1240,7 +1240,7 @@ test.group('Model | ManyToMany | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -1290,7 +1290,7 @@ test.group('Model | ManyToMany | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -1346,7 +1346,7 @@ test.group('Model | ManyToMany | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -1415,7 +1415,7 @@ test.group('Model | ManyToMany | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -1491,7 +1491,7 @@ test.group('Model | ManyToMany | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -1549,7 +1549,7 @@ test.group('Model | ManyToMany | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -1627,7 +1627,7 @@ test.group('Model | ManyToMany | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -1708,7 +1708,7 @@ test.group('Model | ManyToMany | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -1760,7 +1760,7 @@ test.group('Model | ManyToMany | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(1) @@ -1820,7 +1820,7 @@ test.group('Model | ManyToMany | preload', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -1865,7 +1865,7 @@ test.group('Model | ManyToMany | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -1924,7 +1924,7 @@ test.group('Model | ManyToMany | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -1987,7 +1987,7 @@ test.group('Model | ManyToMany | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -2050,7 +2050,7 @@ test.group('Model | ManyToMany | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -2112,7 +2112,7 @@ test.group('Model | ManyToMany | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -2170,7 +2170,7 @@ test.group('Model | ManyToMany | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -2237,7 +2237,7 @@ test.group('Model | ManyToMany | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -2352,7 +2352,7 @@ test.group('Model | ManyToMany | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -2406,7 +2406,7 @@ test.group('Model | ManyToMany | withCount', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -2476,7 +2476,7 @@ test.group('Model | ManyToMany | has', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -2532,7 +2532,7 @@ test.group('Model | ManyToMany | has', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -2606,7 +2606,7 @@ test.group('Model | ManyToMany | whereHas', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -2674,7 +2674,7 @@ test.group('Model | ManyToMany | whereHas', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -2761,7 +2761,7 @@ if (process.env.DB !== 'mysql_legacy') { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -2846,7 +2846,7 @@ if (process.env.DB !== 'mysql_legacy') { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -2975,7 +2975,7 @@ if (process.env.DB !== 'mysql_legacy') { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -3112,7 +3112,7 @@ if (process.env.DB !== 'mysql_legacy') { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -3250,7 +3250,7 @@ if (process.env.DB !== 'mysql_legacy') { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -3323,7 +3323,7 @@ if (process.env.DB !== 'mysql_legacy') { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -3414,7 +3414,7 @@ test.group('Model | ManyToMany | wherePivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -3453,7 +3453,7 @@ test.group('Model | ManyToMany | wherePivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -3494,7 +3494,7 @@ test.group('Model | ManyToMany | wherePivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -3533,7 +3533,7 @@ test.group('Model | ManyToMany | wherePivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -3578,7 +3578,7 @@ test.group('Model | ManyToMany | wherePivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -3618,7 +3618,7 @@ test.group('Model | ManyToMany | wherePivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -3675,7 +3675,7 @@ test.group('Model | ManyToMany | whereNotPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -3713,7 +3713,7 @@ test.group('Model | ManyToMany | whereNotPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -3752,7 +3752,7 @@ test.group('Model | ManyToMany | whereNotPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -3797,7 +3797,7 @@ test.group('Model | ManyToMany | whereNotPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -3847,7 +3847,7 @@ test.group('Model | ManyToMany | whereInPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -3886,7 +3886,7 @@ test.group('Model | ManyToMany | whereInPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -3931,7 +3931,7 @@ test.group('Model | ManyToMany | whereInPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -3975,7 +3975,7 @@ test.group('Model | ManyToMany | whereInPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) const ref = db.connection().getWriteClient().ref.bind(db.connection().getWriteClient()) @@ -4023,7 +4023,7 @@ test.group('Model | ManyToMany | whereInPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -4067,7 +4067,7 @@ test.group('Model | ManyToMany | whereInPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -4106,7 +4106,7 @@ test.group('Model | ManyToMany | whereInPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -4149,7 +4149,7 @@ test.group('Model | ManyToMany | whereInPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -4210,7 +4210,7 @@ test.group('Model | ManyToMany | whereNotInPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -4249,7 +4249,7 @@ test.group('Model | ManyToMany | whereNotInPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -4294,7 +4294,7 @@ test.group('Model | ManyToMany | whereNotInPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -4338,7 +4338,7 @@ test.group('Model | ManyToMany | whereNotInPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -4377,7 +4377,7 @@ test.group('Model | ManyToMany | whereNotInPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -4420,7 +4420,7 @@ test.group('Model | ManyToMany | whereNotInPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -4481,7 +4481,7 @@ test.group('Model | ManyToMany | whereNullPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -4520,7 +4520,7 @@ test.group('Model | ManyToMany | whereNullPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -4561,7 +4561,7 @@ test.group('Model | ManyToMany | whereNullPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -4604,7 +4604,7 @@ test.group('Model | ManyToMany | whereNullPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -4661,7 +4661,7 @@ test.group('Model | ManyToMany | whereNotNullPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -4700,7 +4700,7 @@ test.group('Model | ManyToMany | whereNotNullPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -4741,7 +4741,7 @@ test.group('Model | ManyToMany | whereNotNullPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -4784,7 +4784,7 @@ test.group('Model | ManyToMany | whereNotNullPivot', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -4845,7 +4845,7 @@ test.group('Model | ManyToMany | save', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -4897,7 +4897,7 @@ test.group('Model | ManyToMany | save', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -4952,7 +4952,7 @@ test.group('Model | ManyToMany | save', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -5006,7 +5006,7 @@ test.group('Model | ManyToMany | save', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -5068,7 +5068,7 @@ test.group('Model | ManyToMany | save', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -5128,7 +5128,7 @@ test.group('Model | ManyToMany | save', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -5194,7 +5194,7 @@ test.group('Model | ManyToMany | save', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -5255,7 +5255,7 @@ test.group('Model | ManyToMany | save', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -5311,7 +5311,7 @@ test.group('Model | ManyToMany | save', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -5373,7 +5373,7 @@ test.group('Model | ManyToMany | save', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -5432,7 +5432,7 @@ test.group('Model | ManyToMany | save', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -5491,7 +5491,7 @@ test.group('Model | ManyToMany | save', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -5559,7 +5559,7 @@ test.group('Model | ManyToMany | saveMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -5618,7 +5618,7 @@ test.group('Model | ManyToMany | saveMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -5687,7 +5687,7 @@ test.group('Model | ManyToMany | saveMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -5757,7 +5757,7 @@ test.group('Model | ManyToMany | saveMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -5817,7 +5817,7 @@ test.group('Model | ManyToMany | saveMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -5897,7 +5897,7 @@ test.group('Model | ManyToMany | saveMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -5965,7 +5965,7 @@ test.group('Model | ManyToMany | saveMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -6034,7 +6034,7 @@ test.group('Model | ManyToMany | saveMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -6109,7 +6109,7 @@ test.group('Model | ManyToMany | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -6158,7 +6158,7 @@ test.group('Model | ManyToMany | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -6213,7 +6213,7 @@ test.group('Model | ManyToMany | create', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -6281,7 +6281,7 @@ test.group('Model | ManyToMany | createMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -6338,7 +6338,7 @@ test.group('Model | ManyToMany | createMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -6400,7 +6400,7 @@ test.group('Model | ManyToMany | createMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -6462,7 +6462,7 @@ test.group('Model | ManyToMany | createMany', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -6528,7 +6528,7 @@ test.group('Model | ManyToMany | attach', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -6577,7 +6577,7 @@ test.group('Model | ManyToMany | attach', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -6649,7 +6649,7 @@ test.group('Model | ManyToMany | detach', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -6709,7 +6709,7 @@ test.group('Model | ManyToMany | detach', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -6786,7 +6786,7 @@ test.group('Model | ManyToMany | sync', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -6856,7 +6856,7 @@ test.group('Model | ManyToMany | sync', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -6926,7 +6926,7 @@ test.group('Model | ManyToMany | sync', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -7002,7 +7002,7 @@ test.group('Model | ManyToMany | sync', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -7074,7 +7074,7 @@ test.group('Model | ManyToMany | sync', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -7151,7 +7151,7 @@ test.group('Model | ManyToMany | sync', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -7228,7 +7228,7 @@ test.group('Model | ManyToMany | sync', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -7333,7 +7333,7 @@ test.group('Model | ManyToMany | pagination', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -7401,7 +7401,7 @@ test.group('Model | ManyToMany | pagination', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(1) @@ -7465,7 +7465,7 @@ test.group('Model | ManyToMany | clone', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -7523,7 +7523,7 @@ test.group('Model | ManyToMany | scopes', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -7582,7 +7582,7 @@ test.group('Model | ManyToMany | scopes', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -7654,7 +7654,7 @@ test.group('Model | ManyToMany | onQuery', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -7703,7 +7703,7 @@ test.group('Model | ManyToMany | onQuery', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(3) @@ -7762,7 +7762,7 @@ test.group('Model | ManyToMany | onQuery', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) @@ -7812,7 +7812,7 @@ test.group('Model | ManyToMany | onQuery', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) assert.plan(4) @@ -7883,7 +7883,7 @@ test.group('Model | ManyToMany | delete', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class Skill extends BaseModel { @column({ isPrimary: true }) diff --git a/test/orm/model_query_builder.spec.ts b/test/orm/model_query_builder.spec.ts index bc374a98..e90ac83f 100644 --- a/test/orm/model_query_builder.spec.ts +++ b/test/orm/model_query_builder.spec.ts @@ -40,7 +40,7 @@ test.group('Model query builder', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -59,7 +59,7 @@ test.group('Model query builder', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -78,7 +78,7 @@ test.group('Model query builder', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -105,7 +105,7 @@ test.group('Model query builder', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -133,7 +133,7 @@ test.group('Model query builder', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -164,7 +164,7 @@ test.group('Model query builder', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -193,7 +193,7 @@ test.group('Model query builder', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -222,7 +222,7 @@ test.group('Model query builder', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -251,7 +251,7 @@ test.group('Model query builder', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -280,7 +280,7 @@ test.group('Model query builder', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -302,7 +302,7 @@ test.group('Model query builder', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -324,7 +324,7 @@ test.group('Model query builder', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -350,7 +350,7 @@ test.group('Model query builder', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -387,7 +387,7 @@ test.group('Model query builder', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) @@ -424,7 +424,7 @@ test.group('Model query builder', (group) => { await app.init() const db = getDb() const adapter = ormAdapter(db) - const BaseModel = getBaseModel(adapter, app) + const BaseModel = getBaseModel(adapter) class User extends BaseModel { @column({ isPrimary: true }) From 1f6cf33feb828627fc8218cbdd20ab9de011b460 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Wed, 20 Sep 2023 08:57:28 +0530 Subject: [PATCH 22/70] feat: add method to create a model adapter from database service --- src/database/main.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/database/main.ts b/src/database/main.ts index bf7a5d38..a20318d5 100644 --- a/src/database/main.ts +++ b/src/database/main.ts @@ -22,8 +22,9 @@ import { } from '../types/database.js' import { LucidModel } from '../types/model.js' -import { QueryClient } from '../query_client/index.js' +import { Adapter } from '../orm/adapter/index.js' import { RawBuilder } from './static_builder/raw.js' +import { QueryClient } from '../query_client/index.js' import { prettyPrint } from '../helpers/pretty_print.js' import { ConnectionManager } from '../connection/manager.js' import { InsertQueryBuilder } from './query_builder/insert.js' @@ -185,6 +186,13 @@ export class Database extends Macroable { return this.connection(this.primaryConnectionName, options).modelQuery(model) } + /** + * Returns an adapter lucid models + */ + modelAdapter() { + return new Adapter(this) + } + /** * Returns an instance of raw query builder. Optionally one can * defined the `read/write` mode in which to execute the From 498572f38eae0ce34c2b72facc44d4c6244c975f Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Wed, 20 Sep 2023 09:00:01 +0530 Subject: [PATCH 23/70] feat: add BaseModel.useAdapter method to define an adapter for the model --- src/orm/base_model/index.ts | 8 ++++++++ src/types/model.ts | 6 ++++++ 2 files changed, 14 insertions(+) diff --git a/src/orm/base_model/index.ts b/src/orm/base_model/index.ts index 328f4b38..fcbf5915 100644 --- a/src/orm/base_model/index.ts +++ b/src/orm/base_model/index.ts @@ -87,6 +87,14 @@ class BaseModelImpl implements LucidRow { */ static $adapter: AdapterContract + /** + * Define an adapter to use for interacting with + * the database + */ + static useAdapter(adapter: AdapterContract) { + this.$adapter = adapter + } + /** * Naming strategy for model properties */ diff --git a/src/types/model.ts b/src/types/model.ts index 90dbc2f1..428d3a26 100644 --- a/src/types/model.ts +++ b/src/types/model.ts @@ -778,6 +778,12 @@ export interface LucidModel { */ $adapter: AdapterContract + /** + * Define an adapter to use for interacting with + * the database + */ + useAdapter(adapter: AdapterContract): void + /** * Reference to hooks */ From 2cc14600194fe6d48c9e5a70bf624fa41fb063fb Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Wed, 20 Sep 2023 09:00:43 +0530 Subject: [PATCH 24/70] test: fix breaking test --- test/configure.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/configure.spec.ts b/test/configure.spec.ts index 125ed701..12cfd99d 100644 --- a/test/configure.spec.ts +++ b/test/configure.spec.ts @@ -64,7 +64,7 @@ test.group('Configure', (group) => { await assert.fileContains('start/env.ts', `DB_HOST: Env.schema.string({ format: 'host' })`) await assert.fileContains('start/env.ts', 'DB_PORT: Env.schema.number()') await assert.fileContains('start/env.ts', 'DB_USER: Env.schema.string()') - await assert.fileContains('start/env.ts', 'DB_PASSWORD: Env.schema.string()') + await assert.fileContains('start/env.ts', 'DB_PASSWORD: Env.schema.string.optional()') await assert.fileContains('start/env.ts', 'DB_DATABASE: Env.schema.string()') }).timeout(6000) From 5edf520ca9cdd763fee476ded38d2cd44e1bd6fa Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Wed, 20 Sep 2023 09:07:38 +0530 Subject: [PATCH 25/70] chore(release): 19.0.0-1 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 74fd558d..f945e248 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@adonisjs/lucid", - "version": "19.0.0-0", + "version": "19.0.0-1", "description": "SQL ORM built on top of Active Record pattern", "engines": { "node": ">=18.16.0" From e06c08ebd550b32a647e35b450f3726904a89773 Mon Sep 17 00:00:00 2001 From: Romain Lanz <2793951+RomainLanz@users.noreply.github.com> Date: Thu, 21 Sep 2023 07:05:14 +0200 Subject: [PATCH 26/70] fix: correct path for exporting types (#955) --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index f945e248..303698e2 100644 --- a/package.json +++ b/package.json @@ -27,7 +27,7 @@ "./orm": "./build/src/orm/main.js", "./seeders": "./build/src/seeders/main.js", "./services/*": "./build/services/*.js", - "./types/*": "./build/types/*.js", + "./types/*": "./build/src/types/*.js", "./database_provider": "./build/providers/database_provider.js" }, "scripts": { From 9e89c0dbb7131d389448749e1d510724d18160ba Mon Sep 17 00:00:00 2001 From: Romain Lanz <2793951+RomainLanz@users.noreply.github.com> Date: Thu, 21 Sep 2023 07:05:53 +0200 Subject: [PATCH 27/70] fix(provider): properly define the adapter for the base model (#956) --- providers/database_provider.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/providers/database_provider.ts b/providers/database_provider.ts index 7f096e16..37d6d8fc 100644 --- a/providers/database_provider.ts +++ b/providers/database_provider.ts @@ -11,6 +11,8 @@ import type { ApplicationService } from '@adonisjs/core/types' import { Database } from '../src/database/main.js' import { QueryClient } from '../src/query_client/index.js' +import { BaseModel } from '../src/orm/base_model/index.js' +import { Adapter } from '../src/orm/adapter/index.js' import type { DatabaseConfig } from '../src/types/database.js' declare module '@adonisjs/core/types' { @@ -40,4 +42,9 @@ export default class DatabaseServiceProvider { this.app.container.alias('lucid.db', Database) } + + async boot() { + const db = await this.app.container.make('lucid.db') + BaseModel.$adapter = new Adapter(db) + } } From d0b37b29791591fd0fa8224c58c0dcaabca64258 Mon Sep 17 00:00:00 2001 From: Romain Lanz <2793951+RomainLanz@users.noreply.github.com> Date: Thu, 21 Sep 2023 15:20:22 +0200 Subject: [PATCH 28/70] fix(configure): add commands to the rc file (#954) * fix(configure): add commands to the rc file * test(configure): add assertion that commands have been added --- configure.ts | 1 + test/configure.spec.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/configure.ts b/configure.ts index 9073cb72..60e74cf1 100644 --- a/configure.ts +++ b/configure.ts @@ -102,6 +102,7 @@ export async function configure(command: Configure) { * Register provider */ await codemods.updateRcFile((rcFile) => { + rcFile.addCommand('@adonisjs/lucid/commands') rcFile.addProvider('@adonisjs/lucid/database_provider') }) diff --git a/test/configure.spec.ts b/test/configure.spec.ts index 12cfd99d..5db8595b 100644 --- a/test/configure.spec.ts +++ b/test/configure.spec.ts @@ -52,6 +52,7 @@ test.group('Configure', (group) => { await assert.fileExists('config/database.ts') await assert.fileExists('adonisrc.ts') + await assert.fileContains('adonisrc.ts', '@adonisjs/lucid/commands') await assert.fileContains('adonisrc.ts', '@adonisjs/lucid/database_provider') await assert.fileContains('config/database.ts', 'defineConfig({') From 8769fee05ec46ab71c0c38b68adc9380c35845af Mon Sep 17 00:00:00 2001 From: Romain Lanz Date: Thu, 21 Sep 2023 19:40:52 +0200 Subject: [PATCH 29/70] chore(release): 19.0.0-2 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 303698e2..94e8a3f5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@adonisjs/lucid", - "version": "19.0.0-1", + "version": "19.0.0-2", "description": "SQL ORM built on top of Active Record pattern", "engines": { "node": ">=18.16.0" From a014c2125a5496b65a1f537a58113e60a94cb5e5 Mon Sep 17 00:00:00 2001 From: Romain Lanz <2793951+RomainLanz@users.noreply.github.com> Date: Sat, 23 Sep 2023 22:44:14 +0200 Subject: [PATCH 30/70] fix(types): allow belongs to and has one to be null (#958) --- src/types/relations.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/types/relations.ts b/src/types/relations.ts index c05dc1dd..a48a8b36 100644 --- a/src/types/relations.ts +++ b/src/types/relations.ts @@ -114,7 +114,7 @@ export type ThroughRelationOptions< export type HasOneDecorator = ( model: () => RelatedModel, options?: RelationOptions> -) => TypedDecorator> +) => TypedDecorator | null> /** * Decorator signature to define has many relationship @@ -130,7 +130,7 @@ export type HasManyDecorator = ( export type BelongsToDecorator = ( model: () => RelatedModel, options?: RelationOptions> -) => TypedDecorator> +) => TypedDecorator | null> /** * Decorator signature to define many to many relationship From 62e5b5e792c2fdc1c46e4112e963a6677360b5aa Mon Sep 17 00:00:00 2001 From: Romain Lanz <2793951+RomainLanz@users.noreply.github.com> Date: Sat, 23 Sep 2023 22:50:03 +0200 Subject: [PATCH 31/70] fix(migrator): set primary key for schema_versions table (#957) --- src/migration/runner.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/migration/runner.ts b/src/migration/runner.ts index 56261c32..4c65b7aa 100644 --- a/src/migration/runner.ts +++ b/src/migration/runner.ts @@ -327,7 +327,7 @@ export class MigrationRunner extends EventEmitter { */ this.emit('create:schema_versions:table') await this.client.schema.createTable(this.schemaVersionsTableName, (table) => { - table.integer('version').notNullable() + table.integer('version').unsigned().primary() }) } From a66f9016d7ccf23ce5344be61dceb70c19964ead Mon Sep 17 00:00:00 2001 From: Romain Lanz <2793951+RomainLanz@users.noreply.github.com> Date: Fri, 29 Sep 2023 10:05:19 +0200 Subject: [PATCH 32/70] fix(datetime): check equalities properly (#959) --- src/orm/base_model/index.ts | 5 ++++- test/orm/base_model.spec.ts | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/orm/base_model/index.ts b/src/orm/base_model/index.ts index fcbf5915..ec525bc0 100644 --- a/src/orm/base_model/index.ts +++ b/src/orm/base_model/index.ts @@ -1288,7 +1288,10 @@ class BaseModelImpl implements LucidRow { let isEqual = true if (DateTime.isDateTime(value) || DateTime.isDateTime(originalValue)) { - isEqual = value === originalValue + isEqual = + DateTime.isDateTime(value) && DateTime.isDateTime(originalValue) + ? value.equals(originalValue) + : value === originalValue } else if (isObject(value) && 'isDirty' in value) { isEqual = !value.isDirty } else { diff --git a/test/orm/base_model.spec.ts b/test/orm/base_model.spec.ts index bc5f0026..2debdafa 100644 --- a/test/orm/base_model.spec.ts +++ b/test/orm/base_model.spec.ts @@ -1016,6 +1016,37 @@ test.group('Base Model | persist', (group) => { assert.deepEqual(user.$original, { username: 'virk', updatedAt: '2019-11-20' }) }) + test('the dirty should not contain DateTime field if DateTime value is same', async ({ + fs, + assert, + }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + const adapter = new FakeAdapter() + await app.init() + + const BaseModel = getBaseModel(adapter) + const currentTime = DateTime.now().toISO()! + class User extends BaseModel { + @column() + declare username: string + + @column.dateTime({ columnName: 'updated_at' }) + declare updatedAt: DateTime + } + + const user = new User() + user.username = 'virk' + user.updatedAt = DateTime.fromISO(currentTime) + await user.save() + + assert.isTrue(user.$isPersisted) + + user.merge({ updatedAt: DateTime.fromISO(currentTime) }) + + assert.isFalse(user.$isDirty) + assert.deepEqual(user.$dirty, {}) + }) + test('do not issue update when model is not dirty', async ({ fs, assert }) => { const app = new AppFactory().create(fs.baseUrl, () => {}) const adapter = new FakeAdapter() @@ -6525,6 +6556,9 @@ test.group('Base Model | datetime', (group) => { user.username = 'virk' await user.save() + // waiting for 2 ms, so that the updated at timestamp is different + await new Promise((resolve) => setTimeout(resolve, 200)) + user.username = 'nikk' await user.save() }) From 492f4765007400ae851b4031922469f57e185c78 Mon Sep 17 00:00:00 2001 From: Romain Lanz <2793951+RomainLanz@users.noreply.github.com> Date: Wed, 4 Oct 2023 04:29:33 +0200 Subject: [PATCH 33/70] fix(configure): add missing luxon install (#964) --- configure.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/configure.ts b/configure.ts index 60e74cf1..f95776b2 100644 --- a/configure.ts +++ b/configure.ts @@ -132,7 +132,11 @@ export async function configure(command: Configure) { * Install package or show steps to install package */ if (installNpmDriver) { - await command.installPackages([{ name: pkg, isDevDependency: false }]) + await command.installPackages([ + { name: pkg, isDevDependency: false }, + { name: 'luxon', isDevDependency: false }, + { name: '@types/luxon', isDevDependency: true }, + ]) } else { command.listPackagesToInstall([{ name: pkg, isDevDependency: false }]) } From 123b275b473842286a93c24c345ef02f9c02a45f Mon Sep 17 00:00:00 2001 From: Romain Lanz <2793951+RomainLanz@users.noreply.github.com> Date: Wed, 11 Oct 2023 13:18:28 +0200 Subject: [PATCH 34/70] feat(errors): use new way to define exceptions (#966) --- index.ts | 1 + src/connection/index.ts | 12 ++--- src/connection/manager.ts | 7 +-- src/database/query_builder/database.ts | 9 ++-- src/errors.ts | 74 ++++++++++++++++++++++++++ src/migration/runner.ts | 27 +++++----- src/orm/adapter/index.ts | 2 +- src/orm/base_model/index.ts | 44 ++++++++------- src/orm/decorators/date.ts | 35 +++++------- src/orm/decorators/date_time.ts | 35 +++++------- src/orm/preloader/index.ts | 17 ++---- src/orm/query_builder/index.ts | 33 +++++------- src/orm/relations/keys_extractor.ts | 10 +--- src/utils/index.ts | 10 ++-- test/migrations/migrator.spec.ts | 6 ++- test/orm/base_model.spec.ts | 21 +++++--- 16 files changed, 190 insertions(+), 153 deletions(-) create mode 100644 src/errors.ts diff --git a/index.ts b/index.ts index c0d9fb6e..4d39b223 100644 --- a/index.ts +++ b/index.ts @@ -7,6 +7,7 @@ * file that was distributed with this source code. */ +export * as errors from './src/errors.js' export { configure } from './configure.js' export { stubsRoot } from './stubs/main.js' export { defineConfig } from './src/define_config.js' diff --git a/src/connection/index.ts b/src/connection/index.ts index 6ccce980..de5bec94 100644 --- a/src/connection/index.ts +++ b/src/connection/index.ts @@ -10,7 +10,6 @@ import { Pool } from 'tarn' import knex, { Knex } from 'knex' import { EventEmitter } from 'node:events' -import { Exception } from '@poppinss/utils' import { patchKnex } from 'knex-dynamic-connection' import type { Logger } from '@adonisjs/core/logger' // @ts-expect-error @@ -18,6 +17,7 @@ import { resolveClientNameWithAliases } from 'knex/lib/util/helpers.js' import { ConnectionConfig, ConnectionContract, ReportNode } from '../types/database.js' import { Logger as ConnectionLogger } from './logger.js' +import * as errors from '../errors.js' /** * Connection class manages a given database connection. Internally it uses @@ -81,17 +81,11 @@ export class Connection extends EventEmitter implements ConnectionContract { private validateConfig(): void { if (this.config.replicas) { if (!this.config.replicas.read || !this.config.replicas.write) { - throw new Exception('Make sure to define read/write replicas or use connection property', { - code: 'E_INCOMPLETE_REPLICAS_CONFIG', - status: 500, - }) + throw new errors.E_INCOMPLETE_REPLICAS_CONFIG() } if (!this.config.replicas.read.connection || !this.config.replicas.read.connection) { - throw new Exception('Make sure to define connection property inside read/write replicas', { - status: 500, - code: 'E_INVALID_REPLICAS_CONFIG', - }) + throw new errors.E_INVALID_REPLICAS_CONFIG() } } } diff --git a/src/connection/manager.ts b/src/connection/manager.ts index 42a68238..1d501b2b 100644 --- a/src/connection/manager.ts +++ b/src/connection/manager.ts @@ -7,7 +7,6 @@ * file that was distributed with this source code. */ -import { Exception } from '@poppinss/utils' import type { Emitter } from '@adonisjs/core/events' import type { Logger } from '@adonisjs/core/logger' @@ -20,6 +19,7 @@ import { } from '../types/database.js' import { Connection } from './index.js' +import * as errors from '../errors.js' /** * Connection manager job is to manage multiple named connections. You can add any number @@ -126,10 +126,7 @@ export class ConnectionManager implements ConnectionManagerContract { connect(connectionName: string): void { const connection = this.connections.get(connectionName) if (!connection) { - throw new Exception(`Cannot connect to unregistered connection ${connectionName}`, { - code: 'E_UNMANAGED_DB_CONNECTION', - status: 500, - }) + throw new errors.E_UNMANAGED_DB_CONNECTION([connectionName]) } /** diff --git a/src/database/query_builder/database.ts b/src/database/query_builder/database.ts index 1dc477d5..8daaae16 100644 --- a/src/database/query_builder/database.ts +++ b/src/database/query_builder/database.ts @@ -19,6 +19,7 @@ import { DBQueryCallback, DatabaseQueryBuilderContract } from '../../types/query import { Chainable } from './chainable.js' import { QueryRunner } from '../../query_runner/index.js' import { SimplePaginator } from '../paginator/simple_paginator.js' +import * as errors from '../../errors.js' /** * Wrapping the user function for a query callback and give them @@ -29,7 +30,7 @@ const queryCallback: DBQueryCallback = (userFn, keysResolver) => { return (builder: Knex.QueryBuilder) => { /** * Sub queries don't need the client, since client is used to execute the query - * and subqueries are not executed seperately. That's why we just pass + * and sub-queries are not executed separately. That's why we just pass * an empty object. * * Other option is to have this method for each instance of the class, but this @@ -198,7 +199,7 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil async firstOrFail(): Promise { const row = await this.first() if (!row) { - throw new Exception('Row not found', { status: 404, code: 'E_ROW_NOT_FOUND' }) + throw new errors.E_ROW_NOT_FOUND() } return row @@ -330,8 +331,8 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil /** * Implementation of `finally` for the promise API */ - finally(fullfilled: any) { - return this.exec().finally(fullfilled) + finally(fulfilled: any) { + return this.exec().finally(fulfilled) } /** diff --git a/src/errors.ts b/src/errors.ts new file mode 100644 index 00000000..ba217231 --- /dev/null +++ b/src/errors.ts @@ -0,0 +1,74 @@ +/* + * @adonisjs/lucid + * + * (c) AdonisJS + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import { createError } from '@poppinss/utils' + +export const E_INVALID_DATE_COLUMN_VALUE = createError<[string, string | null]>( + 'Invalid value for "%s". %s', + 'E_INVALID_DATE_COLUMN_VALUE', + 500 +) + +export const E_UNMANAGED_DB_CONNECTION = createError<[string]>( + 'Cannot connect to unregistered connection %s', + 'E_UNMANAGED_DB_CONNECTION', + 500 +) + +export const E_MISSING_MODEL_ATTRIBUTE = createError<[string, string, string]>( + '"%s" expects "%s" to exist on "%s" model, but is missing', + 'E_MISSING_MODEL_ATTRIBUTE', + 500 +) + +export const E_INCOMPLETE_REPLICAS_CONFIG = createError( + 'Make sure to define read/write replicas or use connection property', + 'E_INCOMPLETE_REPLICAS_CONFIG', + 500 +) + +export const E_INVALID_REPLICAS_CONFIG = createError( + 'Make sure to define connection property inside read/write replicas', + 'E_INVALID_REPLICAS_CONFIG', + 500 +) + +export const E_MODEL_DELETED = createError( + 'Cannot mutate delete model instance', + 'E_MODEL_DELETED', + 500 +) + +export const E_ROW_NOT_FOUND = createError('Row not found', 'E_ROW_NOT_FOUND', 404) + +export const E_UNABLE_ACQUIRE_LOCK = createError( + 'Unable to acquire lock. Concurrent migrations are not allowed', + 'E_UNABLE_ACQUIRE_LOCK', + 500 +) + +export const E_UNABLE_RELEASE_LOCK = createError( + 'Migration completed, but unable to release database lock', + 'E_UNABLE_RELEASE_LOCK', + 500 +) + +export const E_MISSING_SCHEMA_FILES = createError( + 'Cannot perform rollback. Schema file "%s" is missing', + 'E_MISSING_SCHEMA_FILES', + 500 +) + +export const E_UNDEFINED_RELATIONSHIP = createError( + '"%s" is not defined as a relationship on "%s" model', + 'E_UNDEFINED_RELATIONSHIP', + 500 +) + +export const E_RUNTIME_EXCEPTION = createError('%s', 'E_RUNTIME_EXCEPTION', 500) diff --git a/src/migration/runner.ts b/src/migration/runner.ts index 4c65b7aa..fe902cf6 100644 --- a/src/migration/runner.ts +++ b/src/migration/runner.ts @@ -9,7 +9,6 @@ import slash from 'slash' import { EventEmitter } from 'node:events' -import { Exception } from '@poppinss/utils' import { MigratorOptions, MigratedFileNode, MigrationListNode } from '../types/migrator.js' import { @@ -24,6 +23,7 @@ import { MigrationSource } from './source.js' import { Database } from '../database/main.js' import { Application } from '@adonisjs/core/app' import { BaseSchema } from '../schema/main.js' +import * as errors from '../errors.js' /** * Migrator exposes the API to execute migrations using the schema files @@ -45,7 +45,7 @@ export class MigrationRunner extends EventEmitter { private schemaVersionsTableName: string /** - * Whether or not the migrator has been booted + * Whether the migrator has been booted */ private booted: boolean = false @@ -254,7 +254,7 @@ export class MigrationRunner extends EventEmitter { /** * Acquires a lock to disallow concurrent transactions. Only works with - * `Mysql`, `PostgreSQL` and `MariaDb` for now. + * `Mysql`, `PostgresSQL` and `MariaDb` for now. * * Make sure we are acquiring lock outside the transactions, since we want * to block other processes from acquiring the same lock. @@ -269,14 +269,14 @@ export class MigrationRunner extends EventEmitter { const acquired = await this.client.dialect.getAdvisoryLock(1) if (!acquired) { - throw new Exception('Unable to acquire lock. Concurrent migrations are not allowed') + throw new errors.E_UNABLE_ACQUIRE_LOCK() } this.emit('acquire:lock') } /** * Release a lock once complete the migration process. Only works with - * `Mysql`, `PostgreSQL` and `MariaDb` for now. + * `Mysql`, `PostgresSQL` and `MariaDb` for now. */ private async releaseLock() { if (!this.client.dialect.supportsAdvisoryLocks || this.disableLocks) { @@ -285,7 +285,7 @@ export class MigrationRunner extends EventEmitter { const released = await this.client.dialect.releaseAdvisoryLock(1) if (!released) { - throw new Exception('Migration completed, but unable to release database lock') + throw new errors.E_UNABLE_RELEASE_LOCK() } this.emit('release:lock') } @@ -293,7 +293,7 @@ export class MigrationRunner extends EventEmitter { /** * Makes the migrations table (if missing). Also created in dry run, since * we always reads from the schema table to find which migrations files to - * execute and that cannot done without missing table. + * execute and that cannot be done without missing table. */ private async makeMigrationsTable() { const hasTable = await this.client.schema.hasTable(this.schemaTableName) @@ -332,7 +332,7 @@ export class MigrationRunner extends EventEmitter { } /** - * Returns the latest migrations version. If no rows exists + * Returns the latest migrations version. If no rows exist * it inserts a new row for version 1 */ private async getLatestVersion() { @@ -349,7 +349,7 @@ export class MigrationRunner extends EventEmitter { /** * Upgrade migrations name from version 1 to version 2 */ - private async upgradeFromOnetoTwo() { + private async upgradeFromOneToTwo() { const migrations = await this.getMigratedFilesTillBatch(0) const client = await this.getClient(false) @@ -368,7 +368,7 @@ export class MigrationRunner extends EventEmitter { await client.from(this.schemaVersionsTableName).where('version', 1).update({ version: 2 }) await this.commit(client) } catch (error) { - this.rollback(client) + await this.rollback(client) throw error } } @@ -379,7 +379,7 @@ export class MigrationRunner extends EventEmitter { private async upgradeVersion(latestVersion: number): Promise { if (latestVersion === 1) { this.emit('upgrade:version', { from: 1, to: 2 }) - await this.upgradeFromOnetoTwo() + await this.upgradeFromOneToTwo() } } @@ -488,10 +488,7 @@ export class MigrationRunner extends EventEmitter { existing.forEach((file) => { const migration = collected.find(({ name }) => name === file.name) if (!migration) { - throw new Exception(`Cannot perform rollback. Schema file {${file.name}} is missing`, { - status: 500, - code: 'E_MISSING_SCHEMA_FILES', - }) + throw new errors.E_MISSING_SCHEMA_FILES([file.name]) } this.migratedFiles[migration.name] = { diff --git a/src/orm/adapter/index.ts b/src/orm/adapter/index.ts index 4751cce4..675d56fb 100644 --- a/src/orm/adapter/index.ts +++ b/src/orm/adapter/index.ts @@ -44,7 +44,7 @@ export class Adapter implements AdapterContract { } /** - * Returns query client for a model instance by inspecting it's options + * Returns query client for a model instance by inspecting its options */ modelClient(instance: LucidRow): any { const modelConstructor = instance.constructor as unknown as LucidModel diff --git a/src/orm/base_model/index.ts b/src/orm/base_model/index.ts index ec525bc0..8b3d6e8e 100644 --- a/src/orm/base_model/index.ts +++ b/src/orm/base_model/index.ts @@ -63,6 +63,7 @@ import { } from '../../utils/index.js' import { SnakeCaseNamingStrategy } from '../naming_strategies/snake_case.js' import { LazyLoadAggregates } from '../relations/aggregates_loader/lazy_load.js' +import * as errors from '../../errors.js' const MANY_RELATIONS = ['hasMany', 'manyToMany', 'hasManyThrough'] const DATE_TIME_TYPES = { @@ -106,7 +107,7 @@ class BaseModelImpl implements LucidRow { static primaryKey: string /** - * Whether or not the model has been booted. Booting the model initializes it's + * Whether the model has been booted. Booting the model initializes its * static properties. Base models must not be initialized. */ static booted: boolean @@ -307,7 +308,7 @@ class BaseModelImpl implements LucidRow { } /** - * Set column as the primary column, when `primary` is to true + * Set column as the primary column, when `primary` is true */ if (column.isPrimary) { this.primaryKey = name @@ -401,7 +402,7 @@ class BaseModelImpl implements LucidRow { } /** - * Register many to many relationship + * Register many-to-many relationship */ protected static $addManyToMany( name: string, @@ -412,7 +413,7 @@ class BaseModelImpl implements LucidRow { } /** - * Register many to many relationship + * Register has many through relationship */ protected static $addHasManyThrough( name: string, @@ -533,7 +534,7 @@ class BaseModelImpl implements LucidRow { this.$defineProperty('selfAssignPrimaryKey', false, 'inherit') /** - * Define the keys property. This allows looking up variations + * Define the keys' property. This allows looking up variations * for model keys */ this.$defineProperty( @@ -927,7 +928,7 @@ class BaseModelImpl implements LucidRow { ) /** - * Perist inside db inside a transaction + * Persist inside db inside a transaction */ await managedTransaction(query.client, async (trx) => { for (let row of rows) { @@ -1033,7 +1034,7 @@ class BaseModelImpl implements LucidRow { /** * The transaction listener listens for the `commit` and `rollback` events and - * cleansup the `$trx` reference + * cleanup the `$trx` reference */ private transactionListener = function listener(this: BaseModelImpl) { this.modelTrx = undefined @@ -1061,10 +1062,7 @@ class BaseModelImpl implements LucidRow { */ private ensureIsntDeleted() { if (this.$isDeleted) { - throw new Exception('Cannot mutate delete model instance', { - status: 500, - code: 'E_MODEL_DELETED', - }) + throw new errors.E_MODEL_DELETED() } } @@ -1203,7 +1201,7 @@ class BaseModelImpl implements LucidRow { /** * Extras are dynamic properties set on the model instance, which - * are not serialized and neither casted for adapter calls. + * are not serialized and neither cast for adapter calls. * * This is helpful when adapter wants to load some extra data conditionally * and that data must not be persisted back the adapter. @@ -1211,18 +1209,18 @@ class BaseModelImpl implements LucidRow { $extras: ModelObject = {} /** - * Sideloaded are dynamic properties set on the model instance, which - * are not serialized and neither casted for adapter calls. + * Side-loaded are dynamic properties set on the model instance, which + * are not serialized and neither cast for adapter calls. * - * This is helpful when you want to add dynamic meta data to the model + * This is helpful when you want to add dynamic metadata to the model * and it's children as well. * * The difference between [[extras]] and [[sideloaded]] is: * * - Extras can be different for each model instance * - Extras are not shared down the hierarchy (example relationships) - * - Sideloaded are shared across multiple model instances created via `$createMultipleFromAdapterResult`. - * - Sideloaded are passed to the relationships as well. + * - Side-loaded are shared across multiple model instances created via `$createMultipleFromAdapterResult`. + * - Side-loaded are passed to the relationships as well. */ $sideloaded: ModelObject = {} @@ -1535,7 +1533,7 @@ class BaseModelImpl implements LucidRow { } /** - * Dis-allow setting multiple model instances for a one to one relationship + * Dis-allow setting multiple model instances for a one-to-one relationship */ if (Array.isArray(models)) { throw new Error( @@ -1666,7 +1664,7 @@ class BaseModelImpl implements LucidRow { /** * Resolve the attribute name from the column names. Since people - * usaully define the column names directly as well by + * usually define the column names directly as well by * accepting them directly from the API. */ const attributeName = Model.$keys.columnsToAttributes.get(key) @@ -1791,7 +1789,7 @@ class BaseModelImpl implements LucidRow { const Model = this.constructor as typeof BaseModel /** - * Persit the model when it's not persisted already + * Persist the model when it's not persisted already */ if (!this.$isPersisted) { await Model.$hooks.runner('before:create').run(this) @@ -1809,7 +1807,7 @@ class BaseModelImpl implements LucidRow { } /** - * Call hooks before hand, so that they have the chance + * Call hooks beforehand, so that they have the chance * to make mutations that produces one or more `$dirty` * fields. */ @@ -1896,7 +1894,7 @@ class BaseModelImpl implements LucidRow { /** * Serializes relationships to a plain object. When `raw=true`, it will - * recurisvely serialize the relationships as well. + * recursively serialize the relationships as well. */ serializeRelations( cherryPick?: CherryPick['relations'], @@ -1925,7 +1923,7 @@ class BaseModelImpl implements LucidRow { } /** - * Always make sure we passing a valid object or undefined + * Always make sure we are passing a valid object or undefined * to the relationships */ const relationOptions = cherryPick ? cherryPick[relation.serializeAs] : undefined diff --git a/src/orm/decorators/date.ts b/src/orm/decorators/date.ts index b498730f..43c172e9 100644 --- a/src/orm/decorators/date.ts +++ b/src/orm/decorators/date.ts @@ -8,7 +8,7 @@ */ import { DateTime } from 'luxon' -import { Exception } from '@poppinss/utils' +import * as errors from '../../errors.js' import { LucidRow, LucidModel, DateColumnDecorator } from '../../types/model.js' /** @@ -31,13 +31,10 @@ function prepareDateColumn(value: any, attributeName: string, modelInstance: Luc */ if (DateTime.isDateTime(value)) { if (!value.isValid) { - throw new Exception( - `Invalid value for "${modelName}.${attributeName}". ${value.invalidReason}`, - { - status: 500, - code: 'E_INVALID_DATE_COLUMN_VALUE', - } - ) + throw new errors.E_INVALID_DATE_COLUMN_VALUE([ + `${modelName}.${attributeName}`, + value.invalidReason, + ]) } return value.toISODate() @@ -46,13 +43,10 @@ function prepareDateColumn(value: any, attributeName: string, modelInstance: Luc /** * Anything else if not an acceptable value for date column */ - throw new Exception( - `The value for "${modelName}.${attributeName}" must be an instance of "luxon.DateTime"`, - { - status: 500, - code: 'E_INVALID_DATE_COLUMN_VALUE', - } - ) + throw new errors.E_INVALID_DATE_COLUMN_VALUE([ + `${modelName}.${attributeName}`, + 'The value must be an instance of "luxon.DateTime"', + ]) } /** @@ -84,13 +78,10 @@ function consumeDateColumn(value: any, attributeName: string, modelInstance: Luc * Any another value cannot be formatted */ const modelName = modelInstance.constructor.name - throw new Exception( - `Cannot format "${modelName}.${attributeName}" ${typeof value} value to an instance of "luxon.DateTime"`, - { - status: 500, - code: 'E_INVALID_DATE_COLUMN_VALUE', - } - ) + throw new errors.E_INVALID_DATE_COLUMN_VALUE([ + `${modelName}.${attributeName}`, + `${typeof value} cannot be formatted`, + ]) } /** diff --git a/src/orm/decorators/date_time.ts b/src/orm/decorators/date_time.ts index 8181cdc8..e32bc98a 100644 --- a/src/orm/decorators/date_time.ts +++ b/src/orm/decorators/date_time.ts @@ -8,8 +8,8 @@ */ import { DateTime } from 'luxon' -import { Exception } from '@poppinss/utils' import { LucidRow, LucidModel, DateTimeColumnDecorator } from '../../types/model.js' +import * as errors from '../../errors.js' /** * The method to prepare the datetime column before persisting it's @@ -32,13 +32,10 @@ function prepareDateTimeColumn(value: any, attributeName: string, modelInstance: */ if (DateTime.isDateTime(value)) { if (!value.isValid) { - throw new Exception( - `Invalid value for "${modelName}.${attributeName}". ${value.invalidReason}`, - { - status: 500, - code: 'E_INVALID_DATETIME_COLUMN_VALUE', - } - ) + throw new errors.E_INVALID_DATE_COLUMN_VALUE([ + `${modelName}.${attributeName}`, + value.invalidReason, + ]) } const dateTimeFormat = model.query(modelInstance.$options).client.dialect.dateTimeFormat @@ -48,13 +45,10 @@ function prepareDateTimeColumn(value: any, attributeName: string, modelInstance: /** * Anything else if not an acceptable value for date column */ - throw new Exception( - `The value for "${modelName}.${attributeName}" must be an instance of "luxon.DateTime"`, - { - status: 500, - code: 'E_INVALID_DATETIME_COLUMN_VALUE', - } - ) + throw new errors.E_INVALID_DATE_COLUMN_VALUE([ + `${modelName}.${attributeName}`, + 'It must be an instance of "luxon.DateTime"', + ]) } /** @@ -86,13 +80,10 @@ function consumeDateTimeColumn(value: any, attributeName: string, modelInstance: * Any another value cannot be formatted */ const modelName = modelInstance.constructor.name - throw new Exception( - `Cannot format "${modelName}.${attributeName}" ${typeof value} value to an instance of "luxon.DateTime"`, - { - status: 500, - code: 'E_INVALID_DATETIME_COLUMN_VALUE', - } - ) + throw new errors.E_INVALID_DATE_COLUMN_VALUE([ + `${modelName}.${attributeName}`, + `${typeof value} cannot be formatted`, + ]) } /** diff --git a/src/orm/preloader/index.ts b/src/orm/preloader/index.ts index 2b8b9391..650d3aa7 100644 --- a/src/orm/preloader/index.ts +++ b/src/orm/preloader/index.ts @@ -7,8 +7,6 @@ * file that was distributed with this source code. */ -import { Exception } from '@poppinss/utils' - import { LucidRow, LucidModel, ModelObject } from '../../types/model.js' import { @@ -18,6 +16,7 @@ import { } from '../../types/relations.js' import { QueryClientContract } from '../../types/database.js' +import * as errors from '../../errors.js' /** * Exposes the API to define and preload relationships in reference to @@ -32,7 +31,7 @@ export class Preloader implements PreloaderContract { } = {} /** - * When invoked via query builder. The preloader will get the sideloaded + * When invoked via query builder. The preloader will get the side-loaded * object, that should be transferred to relationship model instances. */ private sideloaded: ModelObject = {} @@ -76,7 +75,7 @@ export class Preloader implements PreloaderContract { /** * Process a given relationship for many parent instances. This happens - * during eagerloading + * during eager-loading */ private async processRelationForMany( name: string, @@ -110,13 +109,7 @@ export class Preloader implements PreloaderContract { load(name: any, callback?: any): this { const relation = this.model.$getRelation(name) as RelationshipsContract if (!relation) { - throw new Exception( - `"${name}" is not defined as a relationship on "${this.model.name}" model`, - { - status: 500, - code: 'E_UNDEFINED_RELATIONSHIP', - } - ) + throw new errors.E_UNDEFINED_RELATIONSHIP([name, this.model.name]) } relation.boot() @@ -145,7 +138,7 @@ export class Preloader implements PreloaderContract { /** * Define attributes to be passed to all the model instance as - * sideloaded attributes + * side-loaded attributes */ sideload(values: ModelObject): this { this.sideloaded = values diff --git a/src/orm/query_builder/index.ts b/src/orm/query_builder/index.ts index a8dd50b0..a4a3fe50 100644 --- a/src/orm/query_builder/index.ts +++ b/src/orm/query_builder/index.ts @@ -38,6 +38,7 @@ import { ModelPaginator } from '../paginator/index.js' import { QueryRunner } from '../../query_runner/index.js' import { Chainable } from '../../database/query_builder/chainable.js' import { SimplePaginator } from '../../database/paginator/simple_paginator.js' +import * as errors from '../../errors.js' /** * A wrapper to invoke scope methods on the query builder @@ -73,7 +74,7 @@ export class ModelQueryBuilder implements ModelQueryBuilderContract { /** - * Sideloaded attributes that will be passed to the model instances + * Side-loaded attributes that will be passed to the model instances */ protected sideloaded: ModelObject = {} @@ -100,7 +101,7 @@ export class ModelQueryBuilder private scopesWrapper: ModelScopes | undefined = undefined /** - * Control whether or not to wrap adapter result to model + * Control whether to wrap adapter result to model * instances or not */ protected wrapResultsToModelInstances: boolean = true @@ -129,7 +130,7 @@ export class ModelQueryBuilder clientOptions: ModelAdapterOptions /** - * Whether or not query is a subquery for `.where` callback + * Whether query is a sub-query for `.where` callback */ isChildQuery = false @@ -231,7 +232,7 @@ export class ModelQueryBuilder } /** - * Defines sub query for checking the existance of a relationship + * Defines sub query for checking the existence of a relationship */ private addWhereHas( relationName: any, @@ -325,13 +326,7 @@ export class ModelQueryBuilder * Ensure relationship exists */ if (!relation) { - throw new Exception( - `"${name}" is not defined as a relationship on "${this.model.name}" model`, - { - status: 500, - code: 'E_UNDEFINED_RELATIONSHIP', - } - ) + throw new errors.E_UNDEFINED_RELATIONSHIP([name, this.model.name]) } relation.boot() @@ -450,7 +445,7 @@ export class ModelQueryBuilder } /** - * Set sideloaded properties to be passed to the model instance + * Set side-loaded properties to be passed to the model instance */ sideload(value: ModelObject) { this.sideloaded = value @@ -485,14 +480,14 @@ export class ModelQueryBuilder async firstOrFail(): Promise { const row = await this.first() if (!row) { - throw new Exception('Row not found', { status: 404, code: 'E_ROW_NOT_FOUND' }) + throw new errors.E_ROW_NOT_FOUND() } return row } /** - * Load aggregate value as a subquery for a relationship + * Load aggregate value as a sub-query for a relationship */ withAggregate(relationName: any, userCallback: any): this { const subQuery = this.getRelationship(relationName).subQuery(this.client) @@ -525,7 +520,7 @@ export class ModelQueryBuilder } /** - * Count subquery selection + * Count sub-query selection */ this.select(subQuery.prepare()) @@ -538,7 +533,7 @@ export class ModelQueryBuilder } /** - * Get count of a relationship along side the main query results + * Get count of a relationship alongside the main query results */ withCount(relationName: any, userCallback?: any): this { this.withAggregate(relationName, (subQuery: RelationQueryBuilderContract) => { @@ -554,7 +549,7 @@ export class ModelQueryBuilder } /** - * Define alias for the subquery + * Define alias for the sub-query */ if (!subQuery.subQueryAlias) { subQuery.as(`${relationName}_count`) @@ -860,8 +855,8 @@ export class ModelQueryBuilder /** * Implementation of `finally` for the promise API */ - finally(fullfilled: any) { - return this.exec().finally(fullfilled) + finally(fulfilled: any) { + return this.exec().finally(fulfilled) } /** diff --git a/src/orm/relations/keys_extractor.ts b/src/orm/relations/keys_extractor.ts index dd7c8203..ebbae1ab 100644 --- a/src/orm/relations/keys_extractor.ts +++ b/src/orm/relations/keys_extractor.ts @@ -7,8 +7,8 @@ * file that was distributed with this source code. */ -import { Exception } from '@poppinss/utils' import { LucidModel } from '../../types/model.js' +import * as errors from '../../errors.js' /** * Utility to consistently extract relationship keys from the model @@ -33,13 +33,7 @@ export class KeysExtractor { group.each.setup(async () => { @@ -834,7 +835,7 @@ test.group('Migrator', (group) => { const db = getDb() cleanup(() => db.manager.closeAll()) - assert.plan(4) + assert.plan(5) await fs.create( 'database/migrations/users_v11.ts', @@ -892,9 +893,10 @@ test.group('Migrator', (group) => { assert.lengthOf(migrated, 2) assert.isTrue(hasUsersTable) assert.isTrue(hasAccountsTable) + assert.instanceOf(migrator1.error, errors.E_MISSING_SCHEMA_FILES) assert.equal( migrator1.error!.message, - 'Cannot perform rollback. Schema file {database/migrations/accounts_v11} is missing' + 'Cannot perform rollback. Schema file "database/migrations/accounts_v11" is missing' ) }) diff --git a/test/orm/base_model.spec.ts b/test/orm/base_model.spec.ts index 2debdafa..634917d7 100644 --- a/test/orm/base_model.spec.ts +++ b/test/orm/base_model.spec.ts @@ -53,6 +53,7 @@ import { LucidRow } from '../../src/types/model.js' import { ModelPaginator } from '../../src/orm/paginator/index.js' import { SimplePaginator } from '../../src/database/paginator/simple_paginator.js' import { SnakeCaseNamingStrategy } from '../../src/orm/naming_strategies/snake_case.js' +import * as errors from '../../src/errors.js' test.group('Base model | boot', (group) => { group.setup(async () => { @@ -6018,7 +6019,7 @@ test.group('Base Model | date', (group) => { }) test('raise error when date column value is unprocessable', async ({ fs, assert }) => { - assert.plan(1) + assert.plan(2) const app = new AppFactory().create(fs.baseUrl, () => {}) await app.init() @@ -6044,8 +6045,12 @@ test.group('Base Model | date', (group) => { user.dob = 10 as any try { await user.save() - } catch ({ message }) { - assert.equal(message, 'The value for "User.dob" must be an instance of "luxon.DateTime"') + } catch (error) { + assert.instanceOf(error, errors.E_INVALID_DATE_COLUMN_VALUE) + assert.equal( + error.message, + 'Invalid value for "User.dob". The value must be an instance of "luxon.DateTime"' + ) } }) @@ -6414,7 +6419,7 @@ test.group('Base Model | datetime', (group) => { }) test('raise error when datetime column value is unprocessable', async ({ fs, assert }) => { - assert.plan(1) + assert.plan(2) const app = new AppFactory().create(fs.baseUrl, () => {}) await app.init() @@ -6440,8 +6445,12 @@ test.group('Base Model | datetime', (group) => { user.dob = 10 as any try { await user.save() - } catch ({ message }) { - assert.equal(message, 'The value for "User.dob" must be an instance of "luxon.DateTime"') + } catch (error) { + assert.instanceOf(error, errors.E_INVALID_DATE_COLUMN_VALUE) + assert.equal( + error.message, + 'Invalid value for "User.dob". It must be an instance of "luxon.DateTime"' + ) } }) From a6f290d3a6f79460c475d5116d5ef585d800cd1e Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Fri, 20 Oct 2023 11:43:14 +0530 Subject: [PATCH 35/70] chore: update dependencies --- package.json | 46 ++++++++++++++++---------------- stubs/config.stub | 6 ++--- stubs/factories/index.txt | 1 - stubs/make/factory/main.stub | 8 +++--- stubs/make/migration/alter.stub | 8 +++--- stubs/make/migration/create.stub | 8 +++--- stubs/make/model/main.stub | 8 +++--- stubs/make/seeder/main.stub | 8 +++--- 8 files changed, 51 insertions(+), 42 deletions(-) delete mode 100644 stubs/factories/index.txt diff --git a/package.json b/package.json index 94e8a3f5..2b06d45c 100644 --- a/package.json +++ b/package.json @@ -55,57 +55,57 @@ "index:commands": "adonis-kit index build/commands" }, "dependencies": { - "@faker-js/faker": "^8.0.1", - "@poppinss/hooks": "^7.1.1-4", - "@poppinss/macroable": "^1.0.0-0", - "@poppinss/utils": "^6.5.0-6", + "@faker-js/faker": "^8.2.0", + "@poppinss/hooks": "^7.2.0", + "@poppinss/macroable": "^1.0.0", + "@poppinss/utils": "^6.5.0", "fast-deep-equal": "^3.1.3", "igniculus": "^1.5.0", "kleur": "^4.1.5", - "knex": "^2.4.2", - "knex-dynamic-connection": "^3.1.0", + "knex": "^3.0.1", + "knex-dynamic-connection": "^3.1.1", "pretty-hrtime": "^1.0.3", "qs": "^6.11.2", "slash": "^5.1.0", "tarn": "^3.0.2" }, "devDependencies": { - "@adonisjs/assembler": "^6.1.3-22", - "@adonisjs/core": "^6.1.5-26", + "@adonisjs/assembler": "^6.1.3-25", + "@adonisjs/core": "^6.1.5-29", "@adonisjs/eslint-config": "^1.1.8", "@adonisjs/prettier-config": "^1.1.8", "@adonisjs/tsconfig": "^1.1.8", - "@commitlint/cli": "^17.7.1", - "@commitlint/config-conventional": "^17.7.0", - "@japa/assert": "^2.0.0-1", - "@japa/file-system": "^2.0.0-1", - "@japa/runner": "^3.0.0-7", + "@commitlint/cli": "^17.8.0", + "@commitlint/config-conventional": "^17.8.0", + "@japa/assert": "^2.0.0", + "@japa/file-system": "^2.0.0", + "@japa/runner": "^3.0.4", "@swc/core": "1.3.82", - "@types/chance": "^1.1.4", - "@types/luxon": "^3.3.0", - "@types/node": "^20.6.2", - "@types/pluralize": "^0.0.30", - "@types/pretty-hrtime": "^1.0.1", - "@types/qs": "^6.9.7", - "better-sqlite3": "^8.4.0", + "@types/chance": "^1.1.5", + "@types/luxon": "^3.3.3", + "@types/node": "^20.8.7", + "@types/pluralize": "^0.0.32", + "@types/pretty-hrtime": "^1.0.2", + "@types/qs": "^6.9.9", + "better-sqlite3": "^9.0.0", "c8": "^8.0.1", "chance": "^1.1.11", "copyfiles": "^2.4.1", "cross-env": "^7.0.3", "del-cli": "^5.0.0", "dotenv": "^16.0.3", - "eslint": "^8.41.0", + "eslint": "^8.51.0", "fs-extra": "^11.1.1", "github-label-sync": "^2.3.1", "husky": "^8.0.3", "luxon": "^3.4.3", - "mysql2": "^3.3.1", + "mysql2": "^3.6.2", "np": "^8.0.4", "pg": "^8.11.0", "prettier": "^3.0.3", "reflect-metadata": "^0.1.13", "sqlite3": "^5.1.6", - "tedious": "^16.1.0", + "tedious": "^16.5.0", "ts-node": "^10.9.1", "typescript": "^5.2.2" }, diff --git a/stubs/config.stub b/stubs/config.stub index 076ab773..8461600d 100644 --- a/stubs/config.stub +++ b/stubs/config.stub @@ -1,6 +1,6 @@ ---- -to: {{ app.configPath('database.ts') }} ---- +{{{ + exports({ to: app.configPath('database.ts') }) +}}} import env from '#start/env' {{#if dialect === 'sqlite'}} import app from '@adonisjs/core/services/app' diff --git a/stubs/factories/index.txt b/stubs/factories/index.txt deleted file mode 100644 index 25f391a2..00000000 --- a/stubs/factories/index.txt +++ /dev/null @@ -1 +0,0 @@ -import factory from '@adonisjs/lucid/factories' diff --git a/stubs/make/factory/main.stub b/stubs/make/factory/main.stub index 8a9e426b..43d4f166 100644 --- a/stubs/make/factory/main.stub +++ b/stubs/make/factory/main.stub @@ -3,9 +3,11 @@ {{#var modelName = generators.modelName(model.name)}} {{#var modelFileName = generators.modelFileName(model.name)}} {{#var modelImportPath = generators.importPath('#models', model.path, modelFileName.replace(/\.ts$/, ''))}} ---- -to: {{ app.factoriesPath(entity.path, factoryFileName) }} ---- +{{{ + exports({ + to: app.factoriesPath(entity.path, factoryFileName) + }) +}}} import factory from '@adonisjs/lucid/factories' import {{ modelName }} from '{{ modelImportPath }}' diff --git a/stubs/make/migration/alter.stub b/stubs/make/migration/alter.stub index 5b20b1bd..b71a5d19 100644 --- a/stubs/make/migration/alter.stub +++ b/stubs/make/migration/alter.stub @@ -1,6 +1,8 @@ ---- -to: {{ app.makePath(migration.folder, entity.path, migration.fileName) }} ---- +{{{ + exports({ + to: app.makePath(migration.folder, entity.path, migration.fileName) + }) +}}} import { BaseSchema } from '@adonisjs/lucid/schema' export default class extends BaseSchema { diff --git a/stubs/make/migration/create.stub b/stubs/make/migration/create.stub index 12c582d1..111e76c5 100644 --- a/stubs/make/migration/create.stub +++ b/stubs/make/migration/create.stub @@ -1,6 +1,8 @@ ---- -to: {{ app.makePath(migration.folder, entity.path, migration.fileName) }} ---- +{{{ + exports({ + to: app.makePath(migration.folder, entity.path, migration.fileName) + }) +}}} import { BaseSchema } from '@adonisjs/lucid/schema' export default class extends BaseSchema { diff --git a/stubs/make/model/main.stub b/stubs/make/model/main.stub index b994560d..97e15a07 100644 --- a/stubs/make/model/main.stub +++ b/stubs/make/model/main.stub @@ -1,8 +1,10 @@ {{#var modelName = generators.modelName(entity.name)}} {{#var modelFileName = generators.modelFileName(entity.name)}} ---- -to: {{ app.modelsPath(entity.path, modelFileName) }} ---- +{{{ + exports({ + to: app.modelsPath(entity.path, modelFileName) + }) +}}} import { DateTime } from 'luxon' import { BaseModel, column } from '@adonisjs/lucid/orm' diff --git a/stubs/make/seeder/main.stub b/stubs/make/seeder/main.stub index e520f649..76a5799d 100644 --- a/stubs/make/seeder/main.stub +++ b/stubs/make/seeder/main.stub @@ -1,7 +1,9 @@ {{#var seederFileName = generators.seederFileName(entity.name)}} ---- -to: {{ app.seedersPath(entity.path, seederFileName) }} ---- +{{{ + exports({ + to: app.seedersPath(entity.path, seederFileName) + }) +}}} import { BaseSeeder } from '@adonisjs/lucid/seeders' export default class extends BaseSeeder { From 0793ce04d67d781ea0936b95ea78548c99fdb490 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Fri, 20 Oct 2023 12:23:04 +0530 Subject: [PATCH 36/70] chore(release): 19.0.0-3 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 2b06d45c..259c563b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@adonisjs/lucid", - "version": "19.0.0-2", + "version": "19.0.0-3", "description": "SQL ORM built on top of Active Record pattern", "engines": { "node": ">=18.16.0" From 3717436c0f4c4239c32e039518333d6430d1ccde Mon Sep 17 00:00:00 2001 From: Mae <55837878+maevdb@users.noreply.github.com> Date: Fri, 3 Nov 2023 19:16:09 +0100 Subject: [PATCH 37/70] feat: fix a typo in the readme (#969) The readme mentioned Redis instead of Lucid --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e77d7e81..86bb5797 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ npm run test In order to ensure that the AdonisJS community is welcoming to all, please review and abide by the [Code of Conduct](https://github.com/adonisjs/.github/blob/main/docs/CODE_OF_CONDUCT.md). ## License -AdonisJS Redis is open-sourced software licensed under the [MIT license](LICENSE.md). +AdonisJS Lucid is open-sourced software licensed under the [MIT license](LICENSE.md). [gh-workflow-image]: https://img.shields.io/github/actions/workflow/status/adonisjs/lucid/test.yml?style=for-the-badge [gh-workflow-url]: https://github.com/adonisjs/lucid/actions/workflows/test.yml "Github action" From 98023de775c187261546160d8734f362afda5995 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Mon, 27 Nov 2023 16:23:26 +0530 Subject: [PATCH 38/70] chore: update dependencies --- package.json | 54 ++++++++++++++++++++++++++-------------------------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/package.json b/package.json index 259c563b..39e7fc43 100644 --- a/package.json +++ b/package.json @@ -55,10 +55,10 @@ "index:commands": "adonis-kit index build/commands" }, "dependencies": { - "@faker-js/faker": "^8.2.0", - "@poppinss/hooks": "^7.2.0", + "@faker-js/faker": "^8.3.1", + "@poppinss/hooks": "^7.2.1", "@poppinss/macroable": "^1.0.0", - "@poppinss/utils": "^6.5.0", + "@poppinss/utils": "^6.5.1", "fast-deep-equal": "^3.1.3", "igniculus": "^1.5.0", "kleur": "^4.1.5", @@ -70,44 +70,44 @@ "tarn": "^3.0.2" }, "devDependencies": { - "@adonisjs/assembler": "^6.1.3-25", - "@adonisjs/core": "^6.1.5-29", - "@adonisjs/eslint-config": "^1.1.8", - "@adonisjs/prettier-config": "^1.1.8", - "@adonisjs/tsconfig": "^1.1.8", - "@commitlint/cli": "^17.8.0", - "@commitlint/config-conventional": "^17.8.0", - "@japa/assert": "^2.0.0", - "@japa/file-system": "^2.0.0", - "@japa/runner": "^3.0.4", - "@swc/core": "1.3.82", - "@types/chance": "^1.1.5", - "@types/luxon": "^3.3.3", - "@types/node": "^20.8.7", - "@types/pluralize": "^0.0.32", - "@types/pretty-hrtime": "^1.0.2", - "@types/qs": "^6.9.9", - "better-sqlite3": "^9.0.0", + "@adonisjs/assembler": "^6.1.3-28", + "@adonisjs/core": "^6.1.5-32", + "@adonisjs/eslint-config": "^1.1.9", + "@adonisjs/prettier-config": "^1.1.9", + "@adonisjs/tsconfig": "^1.1.9", + "@commitlint/cli": "^18.4.3", + "@commitlint/config-conventional": "^18.4.3", + "@japa/assert": "^2.0.1", + "@japa/file-system": "^2.0.1", + "@japa/runner": "^3.1.0", + "@swc/core": "^1.3.99", + "@types/chance": "^1.1.6", + "@types/luxon": "^3.3.5", + "@types/node": "^20.10.0", + "@types/pluralize": "^0.0.33", + "@types/pretty-hrtime": "^1.0.3", + "@types/qs": "^6.9.10", + "better-sqlite3": "^9.1.1", "c8": "^8.0.1", "chance": "^1.1.11", "copyfiles": "^2.4.1", "cross-env": "^7.0.3", "del-cli": "^5.0.0", "dotenv": "^16.0.3", - "eslint": "^8.51.0", + "eslint": "^8.54.0", "fs-extra": "^11.1.1", "github-label-sync": "^2.3.1", "husky": "^8.0.3", - "luxon": "^3.4.3", - "mysql2": "^3.6.2", + "luxon": "^3.4.4", + "mysql2": "^3.6.5", "np": "^8.0.4", "pg": "^8.11.0", - "prettier": "^3.0.3", + "prettier": "^3.1.0", "reflect-metadata": "^0.1.13", "sqlite3": "^5.1.6", - "tedious": "^16.5.0", + "tedious": "^16.6.0", "ts-node": "^10.9.1", - "typescript": "^5.2.2" + "typescript": "5.2.2" }, "peerDependencies": { "@adonisjs/assembler": "^6.1.3-22", From e774c86a5c626770166a82e432656a23d98c8df0 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Mon, 27 Nov 2023 16:25:21 +0530 Subject: [PATCH 39/70] style: format source code --- commands/migration/_base.ts | 8 ++++---- src/connection/index.ts | 4 ++-- src/migration/runner.ts | 8 ++++---- src/orm/base_model/index.ts | 4 ++-- src/types/model.ts | 4 ++-- test/database/query_client.spec.ts | 8 ++++---- 6 files changed, 18 insertions(+), 18 deletions(-) diff --git a/commands/migration/_base.ts b/commands/migration/_base.ts index 89deb26e..c139e521 100644 --- a/commands/migration/_base.ts +++ b/commands/migration/_base.ts @@ -57,10 +57,10 @@ export default abstract class MigrationsBase extends BaseCommand { ? 'migrating' : 'reverting' : file.status === 'completed' - ? direction === 'up' - ? 'migrated' - : 'reverted' - : 'error' + ? direction === 'up' + ? 'migrated' + : 'reverted' + : 'error' this.logger.logUpdate(`${arrow} ${this.colors[color](message)} ${file.file.name}`) } diff --git a/src/connection/index.ts b/src/connection/index.ts index de5bec94..1e4688aa 100644 --- a/src/connection/index.ts +++ b/src/connection/index.ts @@ -405,8 +405,8 @@ export class Connection extends EventEmitter implements ConnectionContract { message: readError ? 'Unable to reach one of the read hosts' : error - ? 'Unable to reach the database server' - : 'Connection is healthy', + ? 'Unable to reach the database server' + : 'Connection is healthy', error: error || readError || null, } } diff --git a/src/migration/runner.ts b/src/migration/runner.ts index fe902cf6..4531b645 100644 --- a/src/migration/runner.ts +++ b/src/migration/runner.ts @@ -95,10 +95,10 @@ export class MigrationRunner extends EventEmitter { return !this.booted ? 'pending' : this.error - ? 'error' - : Object.keys(this.migratedFiles).length - ? 'completed' - : 'skipped' + ? 'error' + : Object.keys(this.migratedFiles).length + ? 'completed' + : 'skipped' } /** diff --git a/src/orm/base_model/index.ts b/src/orm/base_model/index.ts index 8b3d6e8e..117cd201 100644 --- a/src/orm/base_model/index.ts +++ b/src/orm/base_model/index.ts @@ -1930,8 +1930,8 @@ class BaseModelImpl implements LucidRow { result[relation.serializeAs] = Array.isArray(value) ? value.map((one) => one.serialize(relationOptions)) : value === null - ? null - : value.serialize(relationOptions) + ? null + : value.serialize(relationOptions) return result }, {}) diff --git a/src/types/model.ts b/src/types/model.ts index 428d3a26..a0bdc286 100644 --- a/src/types/model.ts +++ b/src/types/model.ts @@ -95,8 +95,8 @@ export type ModelAttributes = Model['$columns'] extends [P in keyof Model]: P extends keyof LucidRow | 'serializeExtras' ? never : Model[P] extends Function | ModelRelationTypes - ? never - : P + ? never + : P }[keyof Model]]: Model[Filtered] } : Model['$columns'] diff --git a/test/database/query_client.spec.ts b/test/database/query_client.spec.ts index dd7b5e79..75ae17cd 100644 --- a/test/database/query_client.spec.ts +++ b/test/database/query_client.spec.ts @@ -210,8 +210,8 @@ test.group('Query client | dual mode', (group) => { process.env.DB === 'sqlite' || process.env.DB === 'better_sqlite' ? 'DELETE FROM users;' : process.env.DB === 'mssql' - ? 'TRUNCATE table users;' - : 'TRUNCATE users;' + ? 'TRUNCATE table users;' + : 'TRUNCATE users;' await client.insertQuery().table('users').insert({ username: 'virk' }) await client.rawQuery(command).exec() @@ -357,8 +357,8 @@ test.group('Query client | write mode', (group) => { process.env.DB === 'sqlite' || process.env.DB === 'better_sqlite' ? 'DELETE FROM users;' : process.env.DB === 'mssql' - ? 'TRUNCATE table users;' - : 'TRUNCATE users;' + ? 'TRUNCATE table users;' + : 'TRUNCATE users;' await client.insertQuery().table('users').insert({ username: 'virk' }) await client.rawQuery(command).exec() From 35bad84df6a1c21348f8513d0bb6716c1277ae42 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Mon, 27 Nov 2023 16:26:06 +0530 Subject: [PATCH 40/70] ci: update nodejs versions --- .github/workflows/test.yml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index caadecf0..885732a1 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -10,7 +10,7 @@ jobs: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: - node-version: 20 + node-version: 21 - run: npm install - run: npm run lint @@ -20,7 +20,7 @@ jobs: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: - node-version: 20 + node-version: 21 - run: npm install - run: npm run typecheck @@ -29,7 +29,7 @@ jobs: strategy: fail-fast: false matrix: - node-version: [18, 20] + node-version: [20, 21] postgres-version: [11, 14] services: postgres: @@ -56,7 +56,7 @@ jobs: fail-fast: false matrix: mysql: [{ version: '5.7', command: 'mysql_legacy' }, { version: '8.0', command: 'mysql' }] - node-version: [18, 20] + node-version: [20, 21] services: mysql: image: mysql:${{ matrix.mysql.version }} @@ -85,7 +85,7 @@ jobs: fail-fast: false matrix: lib: ['sqlite', 'better_sqlite'] - node-version: [18, 20] + node-version: [20, 21] steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 @@ -101,7 +101,7 @@ jobs: strategy: fail-fast: false matrix: - node-version: [18, 20] + node-version: [20, 21] services: mssql: image: mcr.microsoft.com/mssql/server:2019-latest From dfd03910cfbb954d8464e9136b3588cbe9cdf824 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Mon, 27 Nov 2023 16:26:37 +0530 Subject: [PATCH 41/70] ci: rename test.yml to checks.yml --- .github/workflows/{test.yml => checks.yml} | 0 README.md | 4 ++-- 2 files changed, 2 insertions(+), 2 deletions(-) rename .github/workflows/{test.yml => checks.yml} (100%) diff --git a/.github/workflows/test.yml b/.github/workflows/checks.yml similarity index 100% rename from .github/workflows/test.yml rename to .github/workflows/checks.yml diff --git a/README.md b/README.md index 86bb5797..2b763d27 100644 --- a/README.md +++ b/README.md @@ -29,8 +29,8 @@ In order to ensure that the AdonisJS community is welcoming to all, please revie ## License AdonisJS Lucid is open-sourced software licensed under the [MIT license](LICENSE.md). -[gh-workflow-image]: https://img.shields.io/github/actions/workflow/status/adonisjs/lucid/test.yml?style=for-the-badge -[gh-workflow-url]: https://github.com/adonisjs/lucid/actions/workflows/test.yml "Github action" +[gh-workflow-image]: https://img.shields.io/github/actions/workflow/status/adonisjs/lucid/checks.yml?style=for-the-badge +[gh-workflow-url]: https://github.com/adonisjs/lucid/actions/workflows/checks.yml "Github action" [npm-image]: https://img.shields.io/npm/v/@adonisjs/lucid/latest.svg?style=for-the-badge&logo=npm [npm-url]: https://www.npmjs.com/package/@adonisjs/lucid/v/latest "npm" From 57cdc390267671728a122e6ce98e1ae10341e6c9 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Mon, 27 Nov 2023 16:32:05 +0530 Subject: [PATCH 42/70] chore(release): 19.0.0-4 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 39e7fc43..76693291 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@adonisjs/lucid", - "version": "19.0.0-3", + "version": "19.0.0-4", "description": "SQL ORM built on top of Active Record pattern", "engines": { "node": ">=18.16.0" From 797957d69e3404666cdf44ba612bbb03090aea52 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Mon, 27 Nov 2023 19:18:03 +0530 Subject: [PATCH 43/70] refactor: do not import env when using sqlite driver --- stubs/config.stub | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/stubs/config.stub b/stubs/config.stub index 8461600d..591383bd 100644 --- a/stubs/config.stub +++ b/stubs/config.stub @@ -1,9 +1,10 @@ {{{ exports({ to: app.configPath('database.ts') }) }}} -import env from '#start/env' {{#if dialect === 'sqlite'}} import app from '@adonisjs/core/services/app' +{{#else}} +import env from '#start/env' {{/if}} import { defineConfig } from '@adonisjs/lucid' From 1e5bab36db764f74921f64e98dcd51f5a5942bc5 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Mon, 27 Nov 2023 19:20:03 +0530 Subject: [PATCH 44/70] feat: add type info for db:query event --- providers/database_provider.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/providers/database_provider.ts b/providers/database_provider.ts index 37d6d8fc..37b2c0a6 100644 --- a/providers/database_provider.ts +++ b/providers/database_provider.ts @@ -10,15 +10,18 @@ import type { ApplicationService } from '@adonisjs/core/types' import { Database } from '../src/database/main.js' +import { Adapter } from '../src/orm/adapter/index.js' import { QueryClient } from '../src/query_client/index.js' import { BaseModel } from '../src/orm/base_model/index.js' -import { Adapter } from '../src/orm/adapter/index.js' -import type { DatabaseConfig } from '../src/types/database.js' +import type { DatabaseConfig, DbQueryEventNode } from '../src/types/database.js' declare module '@adonisjs/core/types' { export interface ContainerBindings { 'lucid.db': Database } + export interface EventsList { + 'db:query': DbQueryEventNode + } } /** From 811e059ef9fcd37ad1f2bbe510b155ba3f5c72e1 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Mon, 27 Nov 2023 19:20:46 +0530 Subject: [PATCH 45/70] fix: invalid migration alter stub --- stubs/make/migration/alter.stub | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/stubs/make/migration/alter.stub b/stubs/make/migration/alter.stub index b71a5d19..5bab480e 100644 --- a/stubs/make/migration/alter.stub +++ b/stubs/make/migration/alter.stub @@ -14,6 +14,7 @@ export default class extends BaseSchema { } async down() { - this.schema.alterTable(this.tableName) + this.schema.alterTable(this.tableName, (table) => { + }) } } From 0ebd2ee708c86f777dae8eeec578a55631625d7c Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Mon, 27 Nov 2023 19:21:12 +0530 Subject: [PATCH 46/70] refactor: remove useTz flag from timestamps --- stubs/make/migration/create.stub | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/stubs/make/migration/create.stub b/stubs/make/migration/create.stub index 111e76c5..a41a48b1 100644 --- a/stubs/make/migration/create.stub +++ b/stubs/make/migration/create.stub @@ -12,11 +12,8 @@ export default class extends BaseSchema { this.schema.createTable(this.tableName, (table) => { table.increments('id') - /** - * Uses timestamptz for PostgreSQL and DATETIME2 for MSSQL - */ - table.timestamp('created_at', { useTz: true }) - table.timestamp('updated_at', { useTz: true }) + table.timestamp('created_at') + table.timestamp('updated_at') }) } From ef6fbc3a6a34dfa537afca7bbc6f97f7ba276c0b Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Tue, 28 Nov 2023 09:57:22 +0530 Subject: [PATCH 47/70] feat: add unique and exists validation rules --- package.json | 1 + providers/database_provider.ts | 31 ++++++++++++++ src/bindings/vinejs.ts | 78 ++++++++++++++++++++++++++++++++++ 3 files changed, 110 insertions(+) create mode 100644 src/bindings/vinejs.ts diff --git a/package.json b/package.json index 76693291..2633371e 100644 --- a/package.json +++ b/package.json @@ -87,6 +87,7 @@ "@types/pluralize": "^0.0.33", "@types/pretty-hrtime": "^1.0.3", "@types/qs": "^6.9.10", + "@vinejs/vine": "^1.7.0", "better-sqlite3": "^9.1.1", "c8": "^8.0.1", "chance": "^1.1.11", diff --git a/providers/database_provider.ts b/providers/database_provider.ts index 37b2c0a6..2e67fde8 100644 --- a/providers/database_provider.ts +++ b/providers/database_provider.ts @@ -30,6 +30,30 @@ declare module '@adonisjs/core/types' { export default class DatabaseServiceProvider { constructor(protected app: ApplicationService) {} + /** + * Registers repl bindings when running the application + * in the REPL environment + */ + protected async registerReplBindings() { + if (this.app.getEnvironment() === 'repl') { + const { defineReplBindings } = await import('../src/bindings/repl.js') + defineReplBindings(this.app, await this.app.container.make('repl')) + } + } + + /** + * Registers validation rules for VineJS + */ + protected async registerVineJSRules(db: Database) { + if (this.app.usingVineJS) { + const { defineValidationRules } = await import('../src/bindings/vinejs.js') + defineValidationRules(db) + } + } + + /** + * Invoked by AdonisJS to register container bindings + */ register() { this.app.container.singleton(Database, async (resolver) => { const config = this.app.config.get('database') @@ -46,8 +70,15 @@ export default class DatabaseServiceProvider { this.app.container.alias('lucid.db', Database) } + /** + * Invoked by AdonisJS to extend the framework or pre-configure + * objects + */ async boot() { const db = await this.app.container.make('lucid.db') BaseModel.$adapter = new Adapter(db) + + await this.registerReplBindings() + await this.registerVineJSRules(db) } } diff --git a/src/bindings/vinejs.ts b/src/bindings/vinejs.ts new file mode 100644 index 00000000..2dbd0e83 --- /dev/null +++ b/src/bindings/vinejs.ts @@ -0,0 +1,78 @@ +/* + * @adonisjs/lucid + * + * (c) AdonisJS + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import vine, { VineString } from '@vinejs/vine' +import type { FieldContext } from '@vinejs/vine/types' +import type { Database } from '../database/main.js' + +/** + * The callback function to check a row inside the database + */ +type DatabaseRowChecker = (db: Database, value: string, field: FieldContext) => Promise + +declare module '@vinejs/vine' { + export interface VineString { + /** + * Ensure the value is unique inside the database by self + * executing a query. + * + * - The callback must return "true", if the value is unique (does not exist). + * - The callback must return "false", if the value is not unique (already exists). + */ + unique(callback: DatabaseRowChecker): this + + /** + * Ensure the value is exists inside the database by self + * executing a query. + * + * - The callback must return "true", if the value exists. + * - The callback must return "false", if the value does not exist. + */ + exists(callback: DatabaseRowChecker): this + } +} + +/** + * Defines the "unique" and "exists" validation rules with + * VineJS. + */ +export function defineValidationRules(db: Database) { + const uniqueRule = vine.createRule( + async (value, optionsOrCallback, field) => { + if (!field.isValid) { + return + } + + const isUnqiue = await optionsOrCallback(db, value as string, field) + if (!isUnqiue) { + field.report('The {{ field }} has already been taken', 'database.unique', field) + } + } + ) + + const existsRule = vine.createRule( + async (value, optionsOrCallback, field) => { + if (!field.isValid) { + return + } + + const exists = await optionsOrCallback(db, value as string, field) + if (!exists) { + field.report('The selected {{ field }} is invalid', 'database.exists', field) + } + } + ) + + VineString.macro('unique', function (this: VineString, optionsOrCallback) { + return this.use(uniqueRule(optionsOrCallback)) + }) + VineString.macro('exists', function (this: VineString, optionsOrCallback) { + return this.use(existsRule(optionsOrCallback)) + }) +} From c9522196e3e872d83ca7f82fd8ae5e2fcf25d7b4 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Tue, 28 Nov 2023 10:02:07 +0530 Subject: [PATCH 48/70] refactor: create tmp directory during configure for sqlite dialect --- configure.ts | 11 ++++++++ test/configure.spec.ts | 63 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) diff --git a/configure.ts b/configure.ts index f95776b2..0c42b54b 100644 --- a/configure.ts +++ b/configure.ts @@ -7,6 +7,7 @@ * file that was distributed with this source code. */ +import { mkdir } from 'node:fs/promises' import type Configure from '@adonisjs/core/commands/configure' /** @@ -98,6 +99,16 @@ export async function configure(command: Configure) { `Do you want to install npm package "${pkg}"?` ) + /** + * Make "tmp" directory when the selected dialect is + * sqlite + */ + if (dialect === 'sqlite') { + try { + await mkdir(command.app.tmpPath()) + } catch {} + } + /** * Register provider */ diff --git a/test/configure.spec.ts b/test/configure.spec.ts index 5db8595b..65e6880a 100644 --- a/test/configure.spec.ts +++ b/test/configure.spec.ts @@ -105,4 +105,67 @@ test.group('Configure', (group) => { await assert.fileNotExists('.env') await assert.fileNotExists('start/env.ts') }).timeout(6000) + + test('create tmp directory for sqlite dialect', async ({ fs, assert }) => { + const ignitor = new IgnitorFactory() + .withCoreProviders() + .withCoreConfig() + .create(BASE_URL, { + importer: (filePath) => { + if (filePath.startsWith('./') || filePath.startsWith('../')) { + return import(new URL(filePath, BASE_URL).href) + } + + return import(filePath) + }, + }) + + const app = ignitor.createApp('web') + await app.init() + await app.boot() + + await fs.createJson('tsconfig.json', {}) + await fs.create('adonisrc.ts', `export default defineConfig({})`) + + const ace = await app.container.make('ace') + ace.prompt.trap('Select the database you want to use').chooseOption(0) + ace.prompt.trap('Do you want to install npm package "sqlite3"?').reject() + + const command = await ace.create(Configure, ['../../index.js']) + await command.exec() + + await assert.dirExists('tmp') + }).timeout(6000) + + test('do not recreate tmp directory if it already exists', async ({ fs, assert }) => { + const ignitor = new IgnitorFactory() + .withCoreProviders() + .withCoreConfig() + .create(BASE_URL, { + importer: (filePath) => { + if (filePath.startsWith('./') || filePath.startsWith('../')) { + return import(new URL(filePath, BASE_URL).href) + } + + return import(filePath) + }, + }) + + const app = ignitor.createApp('web') + await app.init() + await app.boot() + + await fs.createJson('tsconfig.json', {}) + await fs.create('adonisrc.ts', `export default defineConfig({})`) + await fs.create('tmp/db.sqlite', '') + + const ace = await app.container.make('ace') + ace.prompt.trap('Select the database you want to use').chooseOption(0) + ace.prompt.trap('Do you want to install npm package "sqlite3"?').reject() + + const command = await ace.create(Configure, ['../../index.js']) + await command.exec() + + await assert.fileExists('tmp/db.sqlite') + }).timeout(6000) }) From 58244dbdf9c534f0c883bf9cfff31881837312da Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Tue, 28 Nov 2023 10:42:10 +0530 Subject: [PATCH 49/70] refactor: do not promopt for db selection when --db flag is used --- configure.ts | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/configure.ts b/configure.ts index 0c42b54b..3df011fd 100644 --- a/configure.ts +++ b/configure.ts @@ -85,14 +85,27 @@ const DIALECTS_INFO: { */ export async function configure(command: Configure) { const codemods = await command.createCodemods() + let dialect: keyof typeof DIALECTS_INFO = command.parsedFlags.db /** * Prompt to select the dialect to use */ - const dialect = - (await command.prompt.choice('Select the database you want to use', DIALECTS, { + if (!dialect) { + dialect = await command.prompt.choice('Select the database you want to use', DIALECTS, { hint: 'You can always change it later', - })) || 'postgres' + }) + } + + /** + * Show error when selected dialect is not supported + */ + if (!DIALECTS_INFO[dialect]) { + command.error( + `The selected database "${dialect}" is invalid. Select from one of the following + ${Object.keys(DIALECTS_INFO).join(', ')}` + ) + return + } const { pkg, envVars, envValidations } = DIALECTS_INFO[dialect] const installNpmDriver = await command.prompt.confirm( From ceec58115e2e1ebd522676fa5ada0c6476ccd700 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Tue, 28 Nov 2023 10:54:52 +0530 Subject: [PATCH 50/70] refactor: define vine types within the provider --- providers/database_provider.ts | 29 ++++++++++++++++++++ src/bindings/vinejs.ts | 48 +++++++--------------------------- 2 files changed, 39 insertions(+), 38 deletions(-) diff --git a/providers/database_provider.ts b/providers/database_provider.ts index 2e67fde8..0e38c6d8 100644 --- a/providers/database_provider.ts +++ b/providers/database_provider.ts @@ -7,6 +7,7 @@ * file that was distributed with this source code. */ +import type { FieldContext } from '@vinejs/vine/types' import type { ApplicationService } from '@adonisjs/core/types' import { Database } from '../src/database/main.js' @@ -15,6 +16,9 @@ import { QueryClient } from '../src/query_client/index.js' import { BaseModel } from '../src/orm/base_model/index.js' import type { DatabaseConfig, DbQueryEventNode } from '../src/types/database.js' +/** + * Extending AdonisJS types + */ declare module '@adonisjs/core/types' { export interface ContainerBindings { 'lucid.db': Database @@ -24,6 +28,31 @@ declare module '@adonisjs/core/types' { } } +/** + * Extending VineJS schema types + */ +declare module '@vinejs/vine' { + export interface VineString { + /** + * Ensure the value is unique inside the database by self + * executing a query. + * + * - The callback must return "true", if the value is unique (does not exist). + * - The callback must return "false", if the value is not unique (already exists). + */ + unique(callback: (db: Database, value: string, field: FieldContext) => Promise): this + + /** + * Ensure the value is exists inside the database by self + * executing a query. + * + * - The callback must return "true", if the value exists. + * - The callback must return "false", if the value does not exist. + */ + exists(callback: (db: Database, value: string, field: FieldContext) => Promise): this + } +} + /** * Database service provider */ diff --git a/src/bindings/vinejs.ts b/src/bindings/vinejs.ts index 2dbd0e83..1e2d0612 100644 --- a/src/bindings/vinejs.ts +++ b/src/bindings/vinejs.ts @@ -8,71 +8,43 @@ */ import vine, { VineString } from '@vinejs/vine' -import type { FieldContext } from '@vinejs/vine/types' import type { Database } from '../database/main.js' -/** - * The callback function to check a row inside the database - */ -type DatabaseRowChecker = (db: Database, value: string, field: FieldContext) => Promise - -declare module '@vinejs/vine' { - export interface VineString { - /** - * Ensure the value is unique inside the database by self - * executing a query. - * - * - The callback must return "true", if the value is unique (does not exist). - * - The callback must return "false", if the value is not unique (already exists). - */ - unique(callback: DatabaseRowChecker): this - - /** - * Ensure the value is exists inside the database by self - * executing a query. - * - * - The callback must return "true", if the value exists. - * - The callback must return "false", if the value does not exist. - */ - exists(callback: DatabaseRowChecker): this - } -} - /** * Defines the "unique" and "exists" validation rules with * VineJS. */ export function defineValidationRules(db: Database) { - const uniqueRule = vine.createRule( - async (value, optionsOrCallback, field) => { + const uniqueRule = vine.createRule[0]>( + async (value, checker, field) => { if (!field.isValid) { return } - const isUnqiue = await optionsOrCallback(db, value as string, field) + const isUnqiue = await checker(db, value as string, field) if (!isUnqiue) { field.report('The {{ field }} has already been taken', 'database.unique', field) } } ) - const existsRule = vine.createRule( - async (value, optionsOrCallback, field) => { + const existsRule = vine.createRule[0]>( + async (value, checker, field) => { if (!field.isValid) { return } - const exists = await optionsOrCallback(db, value as string, field) + const exists = await checker(db, value as string, field) if (!exists) { field.report('The selected {{ field }} is invalid', 'database.exists', field) } } ) - VineString.macro('unique', function (this: VineString, optionsOrCallback) { - return this.use(uniqueRule(optionsOrCallback)) + VineString.macro('unique', function (this: VineString, checker) { + return this.use(uniqueRule(checker)) }) - VineString.macro('exists', function (this: VineString, optionsOrCallback) { - return this.use(existsRule(optionsOrCallback)) + VineString.macro('exists', function (this: VineString, checker) { + return this.use(existsRule(checker)) }) } From 2dbff86686d5471cd5b0fbf44d1588cf23c68c0f Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Tue, 28 Nov 2023 10:55:27 +0530 Subject: [PATCH 51/70] chore(release): 19.0.0-5 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 2633371e..59f0612c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@adonisjs/lucid", - "version": "19.0.0-4", + "version": "19.0.0-5", "description": "SQL ORM built on top of Active Record pattern", "engines": { "node": ">=18.16.0" From 8b839d329e0a5bd954b164c6bb1d78021362c21b Mon Sep 17 00:00:00 2001 From: Julien Ripouteau Date: Sun, 10 Dec 2023 04:53:01 +0100 Subject: [PATCH 52/70] fix: release connection in provider shutdown (#977) --- providers/database_provider.ts | 8 ++++ test/database_provider.spec.ts | 84 ++++++++++++++++++++++++++++++++++ 2 files changed, 92 insertions(+) create mode 100644 test/database_provider.spec.ts diff --git a/providers/database_provider.ts b/providers/database_provider.ts index 0e38c6d8..5f4c40e4 100644 --- a/providers/database_provider.ts +++ b/providers/database_provider.ts @@ -110,4 +110,12 @@ export default class DatabaseServiceProvider { await this.registerReplBindings() await this.registerVineJSRules(db) } + + /** + * Gracefully close connections during shutdown + */ + async shutdown() { + const db = await this.app.container.make('lucid.db') + await db.manager.closeAll() + } } diff --git a/test/database_provider.spec.ts b/test/database_provider.spec.ts new file mode 100644 index 00000000..85300dee --- /dev/null +++ b/test/database_provider.spec.ts @@ -0,0 +1,84 @@ +import { test } from '@japa/runner' +import { IgnitorFactory } from '@adonisjs/core/factories' + +import { defineConfig } from '../src/define_config.js' +import { Database } from '../src/database/main.js' + +const BASE_URL = new URL('./tmp/', import.meta.url) +const IMPORTER = (filePath: string) => { + if (filePath.startsWith('./') || filePath.startsWith('../')) { + return import(new URL(filePath, BASE_URL).href) + } + return import(filePath) +} + +test.group('Database Provider', () => { + test('register database provider', async ({ assert }) => { + const ignitor = new IgnitorFactory() + .merge({ + rcFileContents: { + providers: [() => import('../providers/database_provider.js')], + }, + }) + .withCoreConfig() + .withCoreProviders() + .merge({ + config: { + database: defineConfig({ + connection: 'sqlite', + connections: { + sqlite: { + client: 'sqlite', + connection: { filename: new URL('./tmp/database.sqlite', import.meta.url).href }, + migrations: { naturalSort: true, paths: ['database/migrations'] }, + }, + }, + }), + }, + }) + .create(BASE_URL, { importer: IMPORTER }) + + const app = ignitor.createApp('web') + await app.init() + await app.boot() + + assert.instanceOf(await app.container.make('lucid.db'), Database) + }) + + test('release connection when app is terminating', async ({ assert }) => { + const ignitor = new IgnitorFactory() + .merge({ + rcFileContents: { + providers: [() => import('../providers/database_provider.js')], + }, + }) + .withCoreConfig() + .withCoreProviders() + .merge({ + config: { + database: defineConfig({ + connection: 'sqlite', + connections: { + sqlite: { + client: 'sqlite', + connection: { filename: new URL('./tmp/database.sqlite', import.meta.url).href }, + migrations: { naturalSort: true, paths: ['database/migrations'] }, + }, + }, + }), + }, + }) + .create(BASE_URL, { importer: IMPORTER }) + + const app = ignitor.createApp('web') + await app.init() + await app.boot() + + const db = await app.container.make('lucid.db') + + await db.from('users').catch(() => {}) + await app.terminate() + + assert.isFalse(db.manager.isConnected('sqlite')) + }) +}) From 638b1502111b3f0bdec9393950d0bee893f7c320 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Thu, 14 Dec 2023 14:06:50 +0530 Subject: [PATCH 53/70] chore: package update dependencies --- package.json | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/package.json b/package.json index 59f0612c..18062adc 100644 --- a/package.json +++ b/package.json @@ -58,11 +58,11 @@ "@faker-js/faker": "^8.3.1", "@poppinss/hooks": "^7.2.1", "@poppinss/macroable": "^1.0.0", - "@poppinss/utils": "^6.5.1", + "@poppinss/utils": "^6.6.0", "fast-deep-equal": "^3.1.3", "igniculus": "^1.5.0", "kleur": "^4.1.5", - "knex": "^3.0.1", + "knex": "^3.1.0", "knex-dynamic-connection": "^3.1.1", "pretty-hrtime": "^1.0.3", "qs": "^6.11.2", @@ -72,42 +72,42 @@ "devDependencies": { "@adonisjs/assembler": "^6.1.3-28", "@adonisjs/core": "^6.1.5-32", - "@adonisjs/eslint-config": "^1.1.9", - "@adonisjs/prettier-config": "^1.1.9", - "@adonisjs/tsconfig": "^1.1.9", + "@adonisjs/eslint-config": "^1.2.0", + "@adonisjs/prettier-config": "^1.2.0", + "@adonisjs/tsconfig": "^1.2.0", "@commitlint/cli": "^18.4.3", "@commitlint/config-conventional": "^18.4.3", "@japa/assert": "^2.0.1", "@japa/file-system": "^2.0.1", "@japa/runner": "^3.1.0", - "@swc/core": "^1.3.99", + "@swc/core": "^1.3.100", "@types/chance": "^1.1.6", - "@types/luxon": "^3.3.5", - "@types/node": "^20.10.0", + "@types/luxon": "^3.3.7", + "@types/node": "^20.10.4", "@types/pluralize": "^0.0.33", "@types/pretty-hrtime": "^1.0.3", "@types/qs": "^6.9.10", "@vinejs/vine": "^1.7.0", - "better-sqlite3": "^9.1.1", + "better-sqlite3": "^9.2.2", "c8": "^8.0.1", "chance": "^1.1.11", "copyfiles": "^2.4.1", "cross-env": "^7.0.3", "del-cli": "^5.0.0", "dotenv": "^16.0.3", - "eslint": "^8.54.0", - "fs-extra": "^11.1.1", + "eslint": "^8.55.0", + "fs-extra": "^11.2.0", "github-label-sync": "^2.3.1", "husky": "^8.0.3", "luxon": "^3.4.4", "mysql2": "^3.6.5", - "np": "^8.0.4", + "np": "^9.2.0", "pg": "^8.11.0", - "prettier": "^3.1.0", - "reflect-metadata": "^0.1.13", + "prettier": "^3.1.1", + "reflect-metadata": "^0.2.0", "sqlite3": "^5.1.6", - "tedious": "^16.6.0", - "ts-node": "^10.9.1", + "tedious": "^16.6.1", + "ts-node": "^10.9.2", "typescript": "5.2.2" }, "peerDependencies": { From 45cad2ec2477938fccb89a4c5a9a7c0f0e8a3c87 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Thu, 14 Dec 2023 14:50:21 +0530 Subject: [PATCH 54/70] fix: logic for wrapping existing where clauses when applying relationship constraints Closes: #949 --- src/database/query_builder/chainable.ts | 23 ++++------- test/database/query_builder.spec.ts | 55 ++++++++++++++++++------- 2 files changed, 49 insertions(+), 29 deletions(-) diff --git a/src/database/query_builder/chainable.ts b/src/database/query_builder/chainable.ts index 1743e623..0ff78051 100644 --- a/src/database/query_builder/chainable.ts +++ b/src/database/query_builder/chainable.ts @@ -17,8 +17,6 @@ import { RawQueryBuilder } from './raw.js' import { RawBuilder } from '../static_builder/raw.js' import { ReferenceBuilder } from '../static_builder/reference.js' -const WRAPPING_METHODS = ['where', 'orWhere', 'whereNot', 'orWhereNot'] - /** * The chainable query builder to consturct SQL queries for selecting, updating and * deleting records. @@ -48,13 +46,6 @@ export abstract class Chainable extends Macroable implements ChainableContract { * Returns the wrapping method for a given where method */ private getWrappingMethod(method: string) { - if (WRAPPING_METHODS.includes(method)) { - return { - method: 'where', - wrappingMethod: method, - } - } - if (method.startsWith('or')) { return { method: method, @@ -82,12 +73,14 @@ export abstract class Chainable extends Macroable implements ChainableContract { } this.whereStack.forEach((collection) => { - const firstItem = collection.shift() - const wrapper = this.getWrappingMethod(firstItem.method) - ;(this.knexQuery as any)[wrapper.wrappingMethod]((subquery: any) => { - subquery[wrapper.method](...firstItem.args) - collection.forEach(({ method, args }) => subquery[method](...args)) - }) + if (collection.length) { + const firstItem = collection.shift() + const wrapper = this.getWrappingMethod(firstItem.method) + ;(this.knexQuery as any)[wrapper.wrappingMethod]((subquery: any) => { + subquery[wrapper.method](...firstItem.args) + collection.forEach(({ method, args }) => subquery[method](...args)) + }) + } }) } diff --git a/test/database/query_builder.spec.ts b/test/database/query_builder.spec.ts index 1940044d..c0352c37 100644 --- a/test/database/query_builder.spec.ts +++ b/test/database/query_builder.spec.ts @@ -1121,8 +1121,8 @@ test.group('Query Builder | whereNot', (group) => { const { sql: knexSql, bindings: knexBindings } = connection .client!.from('users') - .whereNot((query) => query.where('username', 'virk')) - .whereNot((query) => query.where('email', 'virk')) + .where((query) => query.whereNot('username', 'virk')) + .where((query) => query.whereNot('email', 'virk')) .toSQL() assert.equal(sql, knexSql) @@ -1140,8 +1140,8 @@ test.group('Query Builder | whereNot', (group) => { const { sql: knexResolverSql, bindings: knexResolverBindings } = connection .client!.from('users') - .whereNot((query) => query.where('my_username', 'virk')) - .whereNot((query) => query.where('my_email', 'virk')) + .where((query) => query.whereNot('my_username', 'virk')) + .where((query) => query.whereNot('my_email', 'virk')) .toSQL() assert.equal(resolverSql, knexResolverSql) @@ -1234,7 +1234,7 @@ test.group('Query Builder | whereNot', (group) => { const { sql: knexSql, bindings: knexBindings } = connection .client!.from('users') - .whereNot((builder) => builder.where((s) => s.where('username', 'virk'))) + .where((builder) => builder.whereNot((s) => s.where('username', 'virk'))) .where((builder) => builder.whereNotNull('deleted_at')) .toSQL() @@ -1253,7 +1253,7 @@ test.group('Query Builder | whereNot', (group) => { const { sql: knexResolverSql, bindings: knexResolverBindings } = connection .client!.from('users') - .whereNot((builder) => builder.where((s) => s.where('my_username', 'virk'))) + .where((builder) => builder.whereNot((s) => s.where('my_username', 'virk'))) .where((builder) => builder.whereNotNull('my_deleted_at')) .toSQL() @@ -1311,8 +1311,8 @@ test.group('Query Builder | whereNot', (group) => { const { sql: knexSql, bindings: knexBindings } = connection .client!.from('users') - .whereNot((q) => q.where('age', '>', 22)) - .whereNot((q) => q.where('age', '<', 18)) + .where((q) => q.whereNot('age', '>', 22)) + .where((q) => q.whereNot('age', '<', 18)) .toSQL() assert.equal(sql, knexSql) @@ -1330,8 +1330,8 @@ test.group('Query Builder | whereNot', (group) => { const { sql: knexResolverSql, bindings: knexResolverBindings } = connection .client!.from('users') - .whereNot((q) => q.where('my_age', '>', 22)) - .whereNot((q) => q.where('my_age', '<', 18)) + .where((q) => q.whereNot('my_age', '>', 22)) + .where((q) => q.whereNot('my_age', '<', 18)) .toSQL() assert.equal(resolverSql, knexResolverSql) @@ -1477,8 +1477,8 @@ test.group('Query Builder | whereNot', (group) => { const { sql: knexSql, bindings: knexBindings } = connection .client!.from('users') - .whereNot((q) => q.where('age', '>', 22)) - .orWhereNot((q) => q.where('age', 18)) + .where((q) => q.whereNot('age', '>', 22)) + .orWhere((q) => q.whereNot('age', 18)) .toSQL() assert.equal(sql, knexSql) @@ -1496,8 +1496,8 @@ test.group('Query Builder | whereNot', (group) => { const { sql: knexResolverSql, bindings: knexResolverBindings } = connection .client!.from('users') - .whereNot((q) => q.where('my_age', '>', 22)) - .orWhereNot((q) => q.where('my_age', 18)) + .where((q) => q.whereNot('my_age', '>', 22)) + .orWhere((q) => q.whereNot('my_age', 18)) .toSQL() assert.equal(resolverSql, knexResolverSql) @@ -1556,6 +1556,33 @@ test.group('Query Builder | whereNot', (group) => { await connection.disconnect() }) + + test('wrap where and whereNot clause', async ({ assert }) => { + const connection = new Connection('primary', getConfig(), logger) + connection.connect() + + let db = getQueryBuilder(getQueryClient(connection)) + const { sql, bindings } = db + .from('users') + .whereNot('points', '<', 50) + .where('age', 18) + .wrapExisting() + .toSQL() + + const { sql: knexSql, bindings: knexBindings } = connection + .client!.from('users') + .where((query) => { + query.whereNot('points', '<', 50).where('age', 18) + }) + .toSQL() + + console.log(sql, knexSql) + + assert.equal(sql, knexSql) + assert.deepEqual(bindings, knexBindings) + + await connection.disconnect() + }) }) test.group('Query Builder | whereIn', (group) => { From b44d15ee658d6e673cc7a8c97d1b7e617ad3b504 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Thu, 14 Dec 2023 15:26:48 +0530 Subject: [PATCH 55/70] fix: passing connection debug flag to relationships loaded via model instance Fixes: #950, #963 --- src/orm/base_model/index.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/orm/base_model/index.ts b/src/orm/base_model/index.ts index 117cd201..69c3f221 100644 --- a/src/orm/base_model/index.ts +++ b/src/orm/base_model/index.ts @@ -1734,9 +1734,12 @@ class BaseModelImpl implements LucidRow { preloader.load(relationName, callback) } + const queryClient = Model.$adapter.modelClient(this) + await preloader .sideload(this.$sideloaded) - .processAllForOne(this, Model.$adapter.modelClient(this)) + .debug(queryClient.debug) + .processAllForOne(this, queryClient) } /** From 223db3907b247a996b663f6c75961eecc6a9eb18 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Thu, 14 Dec 2023 15:52:27 +0530 Subject: [PATCH 56/70] refactor: deprecate useTransaction method usage on query builder --- src/database/query_builder/database.ts | 8 +++++++- src/database/query_builder/insert.ts | 8 +++++++- src/database/query_builder/raw.ts | 8 +++++++- src/orm/query_builder/index.ts | 7 ++++++- src/types/querybuilder.ts | 9 +++++++++ 5 files changed, 36 insertions(+), 4 deletions(-) diff --git a/src/database/query_builder/database.ts b/src/database/query_builder/database.ts index 8daaae16..926712b5 100644 --- a/src/database/query_builder/database.ts +++ b/src/database/query_builder/database.ts @@ -268,7 +268,13 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil } /** - * Run query inside the given transaction + * @deprecated + * Do not use this method. Instead create a query using the + * transaction client directly. + * + * ```ts + * trx.query() + * ``` */ useTransaction(transaction: TransactionClientContract): this { this.knexQuery.transacting(transaction.knexClient) diff --git a/src/database/query_builder/insert.ts b/src/database/query_builder/insert.ts index 2aa7bd5a..78da8821 100644 --- a/src/database/query_builder/insert.ts +++ b/src/database/query_builder/insert.ts @@ -180,7 +180,13 @@ export class InsertQueryBuilder extends Macroable implements InsertQueryBuilderC } /** - * Run query inside the given transaction + * @deprecated + * Do not use this method. Instead create a query using the + * transaction client directly. + * + * ```ts + * trx.insertQuery() + * ``` */ useTransaction(transaction: TransactionClientContract) { this.knexQuery.transacting(transaction.knexClient) diff --git a/src/database/query_builder/raw.ts b/src/database/query_builder/raw.ts index 813b07e6..11f32226 100644 --- a/src/database/query_builder/raw.ts +++ b/src/database/query_builder/raw.ts @@ -88,7 +88,13 @@ export class RawQueryBuilder implements RawQueryBuilderContract { } /** - * Run query inside the given transaction + * @deprecated + * Do not use this method. Instead create a query using the + * transaction client directly. + * + * ```ts + * trx.rawQuery() + * ``` */ useTransaction(transaction: TransactionClientContract) { this.knexQuery.transacting(transaction.knexClient) diff --git a/src/orm/query_builder/index.ts b/src/orm/query_builder/index.ts index a4a3fe50..5be3cca1 100644 --- a/src/orm/query_builder/index.ts +++ b/src/orm/query_builder/index.ts @@ -742,7 +742,12 @@ export class ModelQueryBuilder } /** - * Run query inside the given transaction + * @deprecated + * Do not use this method. Instead create a query with options.client + * + * ```ts + * Model.query({ client: trx }) + * ``` */ useTransaction(transaction: TransactionClientContract) { this.knexQuery.transacting(transaction.knexClient) diff --git a/src/types/querybuilder.ts b/src/types/querybuilder.ts index 6c2a2566..66ffe911 100644 --- a/src/types/querybuilder.ts +++ b/src/types/querybuilder.ts @@ -895,6 +895,15 @@ export interface InsertQueryBuilderContract export interface ExcutableQueryBuilderContract extends Promise { debug(debug: boolean): this timeout(time: number, options?: { cancel: boolean }): this + /** + * @deprecated + * Do not use this method. Instead create a query with options.client + * + * ```ts + * Model.query({ client: trx }) + * Database.query({ client: trx }) + * ``` + */ useTransaction(trx: TransactionClientContract): this reporterData(data: any): this toQuery(): string From 8a6f894b4a7cba6e1cf3680229fea7b0346e4653 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Fri, 15 Dec 2023 07:44:36 +0530 Subject: [PATCH 57/70] fix: make models inherit relationships Fixes: #921 --- src/orm/base_model/index.ts | 1 - test/orm/model_belongs_to.spec.ts | 2 +- test/orm/model_has_many.spec.ts | 2 +- test/orm/model_has_many_through.spec.ts | 2 +- test/orm/model_has_one.spec.ts | 2 +- test/orm/model_many_to_many.spec.ts | 2 +- 6 files changed, 5 insertions(+), 6 deletions(-) diff --git a/src/orm/base_model/index.ts b/src/orm/base_model/index.ts index 69c3f221..9721c0c6 100644 --- a/src/orm/base_model/index.ts +++ b/src/orm/base_model/index.ts @@ -580,7 +580,6 @@ class BaseModelImpl implements LucidRow { const relations = new Map() value.forEach((relation, key) => { const relationClone = relation.clone(this) - relationClone.boot() relations.set(key, relationClone) }) return relations diff --git a/test/orm/model_belongs_to.spec.ts b/test/orm/model_belongs_to.spec.ts index f9bcad53..8da6ccd0 100644 --- a/test/orm/model_belongs_to.spec.ts +++ b/test/orm/model_belongs_to.spec.ts @@ -192,7 +192,7 @@ test.group('Model | BelongsTo | Options', (group) => { assert.equal(Profile.$getRelation('user')!['foreignKey'], 'userUid') }) - test('clone relationship instance with options', async ({ fs, assert }) => { + test('clone relationship instance with options during inheritance', async ({ fs, assert }) => { const app = new AppFactory().create(fs.baseUrl, () => {}) await app.init() const db = getDb() diff --git a/test/orm/model_has_many.spec.ts b/test/orm/model_has_many.spec.ts index bf5632e0..39eb8606 100644 --- a/test/orm/model_has_many.spec.ts +++ b/test/orm/model_has_many.spec.ts @@ -196,7 +196,7 @@ test.group('Model | HasMany | Options', (group) => { assert.equal(User.$getRelation('posts')!['foreignKey'], 'userUid') }) - test('clone relationship instance with options', async ({ fs, assert }) => { + test('clone relationship instance with options during inheritance', async ({ fs, assert }) => { const app = new AppFactory().create(fs.baseUrl, () => {}) await app.init() const db = getDb() diff --git a/test/orm/model_has_many_through.spec.ts b/test/orm/model_has_many_through.spec.ts index 85a879aa..bbf8f979 100644 --- a/test/orm/model_has_many_through.spec.ts +++ b/test/orm/model_has_many_through.spec.ts @@ -272,7 +272,7 @@ test.group('Model | Has Many Through | Options', (group) => { assert.equal(relation['throughForeignKeyColumnName'], 'user_uid') }) - test('clone relationship instance with options', async ({ fs, assert }) => { + test('clone relationship instance with options during inheritance', async ({ fs, assert }) => { const app = new AppFactory().create(fs.baseUrl, () => {}) await app.init() const db = getDb() diff --git a/test/orm/model_has_one.spec.ts b/test/orm/model_has_one.spec.ts index caef1414..5f2120c1 100644 --- a/test/orm/model_has_one.spec.ts +++ b/test/orm/model_has_one.spec.ts @@ -199,7 +199,7 @@ test.group('Model | HasOne | Options', (group) => { assert.equal(User.$getRelation('profile')!['foreignKey'], 'userUid') }) - test('clone relationship instance with options', async ({ fs, assert }) => { + test('clone relationship instance with options during inheritance', async ({ fs, assert }) => { const app = new AppFactory().create(fs.baseUrl, () => {}) await app.init() const db = getDb() diff --git a/test/orm/model_many_to_many.spec.ts b/test/orm/model_many_to_many.spec.ts index 28695f3c..00f27565 100644 --- a/test/orm/model_many_to_many.spec.ts +++ b/test/orm/model_many_to_many.spec.ts @@ -305,7 +305,7 @@ test.group('Model | ManyToMany | Options', (group) => { assert.equal(User.$getRelation('skills')!['pivotRelatedForeignKey'], 'skill_uid') }) - test('clone relationship instance with options', async ({ fs, assert }) => { + test('clone relationship instance with options during inheritance', async ({ fs, assert }) => { const app = new AppFactory().create(fs.baseUrl, () => {}) await app.init() const db = getDb() From 5e99253f2af6f9638e15ab7c5bc1a3333ca1ee25 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Fri, 15 Dec 2023 08:55:19 +0530 Subject: [PATCH 58/70] fix: mention search paths from config during db:wipe and db:truncate commands Fixes: #926 --- commands/db_truncate.ts | 14 ++++++++++---- commands/db_wipe.ts | 26 ++++++++++++++++---------- test-helpers/index.ts | 1 + 3 files changed, 27 insertions(+), 14 deletions(-) diff --git a/commands/db_truncate.ts b/commands/db_truncate.ts index e4102555..520aa331 100644 --- a/commands/db_truncate.ts +++ b/commands/db_truncate.ts @@ -55,8 +55,8 @@ export default class DbTruncate extends BaseCommand { /** * Truncate all tables except adonis migrations table */ - private async performTruncate(client: QueryClientContract) { - let tables = await client.getAllTables(['public']) + private async performTruncate(client: QueryClientContract, schemas: string[]) { + let tables = await client.getAllTables(schemas) tables = tables.filter((table) => !['adonis_schema', 'adonis_schema_versions'].includes(table)) await Promise.all(tables.map((table) => client.truncate(table, true))) @@ -91,13 +91,19 @@ export default class DbTruncate extends BaseCommand { /** * Invalid database connection */ - if (!db.manager.has(this.connection)) { + const managerConnection = db.manager.get(this.connection) + if (!managerConnection) { this.printNotAValidConnection(this.connection) this.exitCode = 1 return } - await this.performTruncate(connection) + let schemas: string[] = ['public'] + if ('searchPath' in managerConnection.config && managerConnection.config.searchPath) { + schemas = managerConnection.config.searchPath + } + + await this.performTruncate(connection, schemas) } /** diff --git a/commands/db_wipe.ts b/commands/db_wipe.ts index 1e6bf516..43c59268 100644 --- a/commands/db_wipe.ts +++ b/commands/db_wipe.ts @@ -67,7 +67,7 @@ export default class DbWipe extends BaseCommand { /** * Drop all views (if asked for and supported) */ - private async performDropViews(client: QueryClientContract) { + private async performDropViews(client: QueryClientContract, schemas: string[]) { if (!this.dropViews) { return } @@ -76,22 +76,22 @@ export default class DbWipe extends BaseCommand { this.logger.warning(`Dropping views is not supported by "${client.dialect.name}"`) } - await client.dropAllViews() + await client.dropAllViews(schemas) this.logger.success('Dropped views successfully') } /** * Drop all tables */ - private async performDropTables(client: QueryClientContract) { - await client.dropAllTables() + private async performDropTables(client: QueryClientContract, schemas: string[]) { + await client.dropAllTables(schemas) this.logger.success('Dropped tables successfully') } /** * Drop all types (if asked for and supported) */ - private async performDropTypes(client: QueryClientContract) { + private async performDropTypes(client: QueryClientContract, schemas: string[]) { if (!this.dropTypes) { return } @@ -100,7 +100,7 @@ export default class DbWipe extends BaseCommand { this.logger.warning(`Dropping types is not supported by "${client.dialect.name}"`) } - await client.dropAllTypes() + await client.dropAllTypes(schemas) this.logger.success('Dropped types successfully') } @@ -132,15 +132,21 @@ export default class DbWipe extends BaseCommand { /** * Invalid database connection */ - if (!db.manager.has(this.connection)) { + const managerConnection = db.manager.get(this.connection) + if (!managerConnection) { this.printNotAValidConnection(this.connection) this.exitCode = 1 return } - await this.performDropViews(connection) - await this.performDropTables(connection) - await this.performDropTypes(connection) + let schemas: string[] = ['public'] + if ('searchPath' in managerConnection.config && managerConnection.config.searchPath) { + schemas = managerConnection.config.searchPath + } + + await this.performDropViews(connection, schemas) + await this.performDropTables(connection, schemas) + await this.performDropTypes(connection, schemas) } /** diff --git a/test-helpers/index.ts b/test-helpers/index.ts index 0ad47835..bec36aa1 100644 --- a/test-helpers/index.ts +++ b/test-helpers/index.ts @@ -117,6 +117,7 @@ export function getConfig(): ConnectionConfig { user: process.env.PG_USER as string, password: process.env.PG_PASSWORD as string, }, + searchPath: ['custom', 'public'], debug: !!process.env.DEBUG, useNullAsDefault: true, } From 073fee4f33e22d7bd7a83f4172cc3b53ce853fda Mon Sep 17 00:00:00 2001 From: Romain Lanz <2793951+RomainLanz@users.noreply.github.com> Date: Fri, 15 Dec 2023 04:50:51 +0100 Subject: [PATCH 59/70] fix(orm): use naming strategy for computed field (#970) --- src/orm/base_model/index.ts | 5 ++++- test/orm/base_model.spec.ts | 12 ++++++------ 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/orm/base_model/index.ts b/src/orm/base_model/index.ts index 9721c0c6..f9574551 100644 --- a/src/orm/base_model/index.ts +++ b/src/orm/base_model/index.ts @@ -347,7 +347,10 @@ class BaseModelImpl implements LucidRow { */ static $addComputed(name: string, options: Partial) { const computed: ComputedOptions = { - serializeAs: options.serializeAs || name, + serializeAs: + options.serializeAs !== undefined + ? options.serializeAs + : this.namingStrategy.serializedName(this, name), meta: options.meta, } this.$computedDefinitions.set(name, computed) diff --git a/test/orm/base_model.spec.ts b/test/orm/base_model.spec.ts index 634917d7..dc07d465 100644 --- a/test/orm/base_model.spec.ts +++ b/test/orm/base_model.spec.ts @@ -2506,7 +2506,7 @@ test.group('Base Model | toJSON', (group) => { const user = new User() user.username = 'virk' - assert.deepEqual(user.toJSON(), { username: 'virk', fullName: 'VIRK' }) + assert.deepEqual(user.toJSON(), { username: 'virk', full_name: 'VIRK' }) }) test('do not add computed property when it returns undefined', async ({ fs, assert }) => { @@ -2585,7 +2585,7 @@ test.group('Base Model | toJSON', (group) => { assert.deepEqual(user.toJSON(), { username: 'virk', - fullName: 'VIRK', + full_name: 'VIRK', meta: { postsCount: 10, }, @@ -2623,7 +2623,7 @@ test.group('Base Model | toJSON', (group) => { assert.deepEqual(user.toJSON(), { username: 'virk', - fullName: 'VIRK', + full_name: 'VIRK', posts: { count: 10, }, @@ -7612,7 +7612,7 @@ test.group('Base model | inheritance', (group) => { 'fullName', { meta: undefined, - serializeAs: 'fullName', + serializeAs: 'full_name', }, ], [ @@ -7638,7 +7638,7 @@ test.group('Base model | inheritance', (group) => { 'fullName', { meta: undefined, - serializeAs: 'fullName', + serializeAs: 'full_name', }, ], ]) @@ -7733,7 +7733,7 @@ test.group('Base model | inheritance', (group) => { 'fullName', { meta: undefined, - serializeAs: 'fullName', + serializeAs: 'full_name', }, ], ]) From 2ae295b3df52b806e87d5415b45c59ff97586ccb Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Fri, 15 Dec 2023 09:23:15 +0530 Subject: [PATCH 60/70] refactor: add connectionString config option in postgresql config --- src/types/database.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/types/database.ts b/src/types/database.ts index b3fe9ad3..1b57ef7f 100644 --- a/src/types/database.ts +++ b/src/types/database.ts @@ -416,6 +416,7 @@ export type MysqlConfig = SharedConfigNode & { */ type PostgresConnectionNode = { ssl?: boolean | ConnectionOptions + connectionString?: string } export type PostgreConfig = SharedConfigNode & { client: 'pg' | 'postgres' | 'postgresql' From 4b10565909ce8d244847ddee9c1691bece9b00b5 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Fri, 15 Dec 2023 11:59:11 +0530 Subject: [PATCH 61/70] test: remove searchPath from postgreSQL config --- test-helpers/index.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/test-helpers/index.ts b/test-helpers/index.ts index bec36aa1..0ad47835 100644 --- a/test-helpers/index.ts +++ b/test-helpers/index.ts @@ -117,7 +117,6 @@ export function getConfig(): ConnectionConfig { user: process.env.PG_USER as string, password: process.env.PG_PASSWORD as string, }, - searchPath: ['custom', 'public'], debug: !!process.env.DEBUG, useNullAsDefault: true, } From db19e1d9ad61c10f9d14ceef5cc80cc523af1468 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Fri, 15 Dec 2023 14:52:38 +0530 Subject: [PATCH 62/70] chore(release): 19.0.0-6 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 18062adc..59efa14c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@adonisjs/lucid", - "version": "19.0.0-5", + "version": "19.0.0-6", "description": "SQL ORM built on top of Active Record pattern", "engines": { "node": ">=18.16.0" From 0556cb5bb8d358acdc887d644da981e46968933b Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Tue, 26 Dec 2023 11:21:45 +0530 Subject: [PATCH 63/70] refactor: update stubs to use latest APIs --- configure.ts | 164 +++++++++------------------------------------- package.json | 27 ++++---- stubs/config.stub | 75 --------------------- 3 files changed, 45 insertions(+), 221 deletions(-) delete mode 100644 stubs/config.stub diff --git a/configure.ts b/configure.ts index 3df011fd..807664ec 100644 --- a/configure.ts +++ b/configure.ts @@ -7,161 +7,59 @@ * file that was distributed with this source code. */ -import { mkdir } from 'node:fs/promises' +import string from '@poppinss/utils/string' +import { presetLucid, DIALECTS } from '@adonisjs/presets/lucid' import type Configure from '@adonisjs/core/commands/configure' -/** - * We only allow configuring the one's thoroughly tested - * inside the Lucid codebase. Knex supports more and one - * can reference knex docs to configure additional - * dialects. - */ -const DIALECTS = ['sqlite', 'mysql', 'postgres', 'mssql'] as const -const DIALECTS_INFO: { - [K in (typeof DIALECTS)[number]]: { - envVars?: Record - envValidations?: Record - pkg: string - } -} = { - sqlite: { - pkg: 'sqlite3', - }, - mysql: { - pkg: 'mysql2', - envVars: { - DB_HOST: '127.0.0.1', - DB_PORT: 3306, - DB_USER: 'root', - DB_PASSWORD: '', - DB_DATABASE: '', - }, - envValidations: { - DB_HOST: `Env.schema.string({ format: 'host' })`, - DB_PORT: `Env.schema.number()`, - DB_USER: 'Env.schema.string()', - DB_PASSWORD: 'Env.schema.string.optional()', - DB_DATABASE: 'Env.schema.string()', - }, - }, - postgres: { - envVars: { - DB_HOST: '127.0.0.1', - DB_PORT: 5432, - DB_USER: 'postgres', - DB_PASSWORD: '', - DB_DATABASE: '', - }, - envValidations: { - DB_HOST: `Env.schema.string({ format: 'host' })`, - DB_PORT: `Env.schema.number()`, - DB_USER: 'Env.schema.string()', - DB_PASSWORD: 'Env.schema.string.optional()', - DB_DATABASE: 'Env.schema.string()', - }, - pkg: 'pg', - }, - mssql: { - envVars: { - DB_HOST: '127.0.0.1', - DB_PORT: 1433, - DB_USER: 'sa', - DB_PASSWORD: '', - DB_DATABASE: '', - }, - envValidations: { - DB_HOST: `Env.schema.string({ format: 'host' })`, - DB_PORT: `Env.schema.number()`, - DB_USER: 'Env.schema.string()', - DB_PASSWORD: 'Env.schema.string.optional()', - DB_DATABASE: 'Env.schema.string()', - }, - pkg: 'tedious', - }, -} - /** * Configures the package */ export async function configure(command: Configure) { - const codemods = await command.createCodemods() - let dialect: keyof typeof DIALECTS_INFO = command.parsedFlags.db + let dialect: string | undefined = command.parsedFlags.db + let shouldInstallPackages: boolean | undefined = command.parsedFlags.install /** - * Prompt to select the dialect to use + * Prompt to select the dialect when --db flag + * is not used. */ - if (!dialect) { - dialect = await command.prompt.choice('Select the database you want to use', DIALECTS, { - hint: 'You can always change it later', - }) + if (dialect === undefined) { + dialect = await command.prompt.choice( + 'Select the database you want to use', + Object.keys(DIALECTS), + { + validate(value) { + return !!value + }, + } + ) } /** * Show error when selected dialect is not supported */ - if (!DIALECTS_INFO[dialect]) { + if (dialect! in DIALECTS === false) { command.error( - `The selected database "${dialect}" is invalid. Select from one of the following - ${Object.keys(DIALECTS_INFO).join(', ')}` + `The selected database "${dialect}" is invalid. Select one from: ${string.sentence( + Object.keys(DIALECTS) + )}` ) + command.exitCode = 1 return } - const { pkg, envVars, envValidations } = DIALECTS_INFO[dialect] - const installNpmDriver = await command.prompt.confirm( - `Do you want to install npm package "${pkg}"?` - ) - /** - * Make "tmp" directory when the selected dialect is - * sqlite + * Prompt when `install` or `--no-install` flags are + * not used */ - if (dialect === 'sqlite') { - try { - await mkdir(command.app.tmpPath()) - } catch {} + if (shouldInstallPackages === undefined) { + shouldInstallPackages = await command.prompt.confirm( + 'Do you want to install additional packages required by "@adonisjs/lucid"?' + ) } - /** - * Register provider - */ - await codemods.updateRcFile((rcFile) => { - rcFile.addCommand('@adonisjs/lucid/commands') - rcFile.addProvider('@adonisjs/lucid/database_provider') + const codemods = await command.createCodemods() + await presetLucid(codemods, command.app, { + dialect: dialect as keyof typeof DIALECTS, + installPackages: !!shouldInstallPackages, }) - - /** - * Define environment variables - */ - if (envVars) { - codemods.defineEnvVariables(envVars) - } - - /** - * Define environment validations - */ - if (envValidations) { - codemods.defineEnvValidations({ - variables: envValidations, - leadingComment: 'Variables for configuring database connection', - }) - } - - /** - * Publish config - */ - await command.publishStub('config.stub', { dialect: dialect }) - - /** - * Install package or show steps to install package - */ - if (installNpmDriver) { - await command.installPackages([ - { name: pkg, isDevDependency: false }, - { name: 'luxon', isDevDependency: false }, - { name: '@types/luxon', isDevDependency: true }, - ]) - } else { - command.listPackagesToInstall([{ name: pkg, isDevDependency: false }]) - } } diff --git a/package.json b/package.json index 59efa14c..165cd50e 100644 --- a/package.json +++ b/package.json @@ -55,10 +55,11 @@ "index:commands": "adonis-kit index build/commands" }, "dependencies": { + "@adonisjs/presets": "^1.0.0", "@faker-js/faker": "^8.3.1", - "@poppinss/hooks": "^7.2.1", - "@poppinss/macroable": "^1.0.0", - "@poppinss/utils": "^6.6.0", + "@poppinss/hooks": "^7.2.2", + "@poppinss/macroable": "^1.0.1", + "@poppinss/utils": "^6.7.0", "fast-deep-equal": "^3.1.3", "igniculus": "^1.5.0", "kleur": "^4.1.5", @@ -70,23 +71,23 @@ "tarn": "^3.0.2" }, "devDependencies": { - "@adonisjs/assembler": "^6.1.3-28", - "@adonisjs/core": "^6.1.5-32", + "@adonisjs/assembler": "^7.0.0-1", + "@adonisjs/core": "^6.1.5-36", "@adonisjs/eslint-config": "^1.2.0", "@adonisjs/prettier-config": "^1.2.0", "@adonisjs/tsconfig": "^1.2.0", "@commitlint/cli": "^18.4.3", "@commitlint/config-conventional": "^18.4.3", - "@japa/assert": "^2.0.1", - "@japa/file-system": "^2.0.1", - "@japa/runner": "^3.1.0", - "@swc/core": "^1.3.100", + "@japa/assert": "^2.1.0", + "@japa/file-system": "^2.1.1", + "@japa/runner": "^3.1.1", + "@swc/core": "^1.3.101", "@types/chance": "^1.1.6", "@types/luxon": "^3.3.7", - "@types/node": "^20.10.4", + "@types/node": "^20.10.5", "@types/pluralize": "^0.0.33", "@types/pretty-hrtime": "^1.0.3", - "@types/qs": "^6.9.10", + "@types/qs": "^6.9.11", "@vinejs/vine": "^1.7.0", "better-sqlite3": "^9.2.2", "c8": "^8.0.1", @@ -95,7 +96,7 @@ "cross-env": "^7.0.3", "del-cli": "^5.0.0", "dotenv": "^16.0.3", - "eslint": "^8.55.0", + "eslint": "^8.56.0", "fs-extra": "^11.2.0", "github-label-sync": "^2.3.1", "husky": "^8.0.3", @@ -108,7 +109,7 @@ "sqlite3": "^5.1.6", "tedious": "^16.6.1", "ts-node": "^10.9.2", - "typescript": "5.2.2" + "typescript": "^5.3.3" }, "peerDependencies": { "@adonisjs/assembler": "^6.1.3-22", diff --git a/stubs/config.stub b/stubs/config.stub deleted file mode 100644 index 591383bd..00000000 --- a/stubs/config.stub +++ /dev/null @@ -1,75 +0,0 @@ -{{{ - exports({ to: app.configPath('database.ts') }) -}}} -{{#if dialect === 'sqlite'}} -import app from '@adonisjs/core/services/app' -{{#else}} -import env from '#start/env' -{{/if}} -import { defineConfig } from '@adonisjs/lucid' - -const dbConfig = defineConfig({ - connection: '{{ dialect }}', - connections: { - {{#if dialect === 'sqlite'}} - sqlite: { - client: 'sqlite', - connection: { - filename: app.tmpPath('db.sqlite3') - }, - useNullAsDefault: true, - migrations: { - naturalSort: true, - paths: ['database/migrations'], - }, - }, - {{#elif dialect === 'postgres'}} - postgres: { - client: 'pg', - connection: { - host: env.get('DB_HOST'), - port: env.get('DB_PORT'), - user: env.get('DB_USER'), - password: env.get('DB_PASSWORD'), - database: env.get('DB_DATABASE'), - }, - migrations: { - naturalSort: true, - paths: ['database/migrations'], - }, - }, - {{#elif dialect === 'mysql'}} - mysql: { - client: 'mysql2', - connection: { - host: env.get('DB_HOST'), - port: env.get('DB_PORT'), - user: env.get('DB_USER'), - password: env.get('DB_PASSWORD'), - database: env.get('DB_DATABASE'), - }, - migrations: { - naturalSort: true, - paths: ['database/migrations'], - }, - }, - {{#elif dialect === 'mssql'}} - mssql: { - client: 'tedious', - connection: { - server: env.get('DB_HOST'), - port: env.get('DB_PORT'), - user: env.get('DB_USER'), - password: env.get('DB_PASSWORD'), - database: env.get('DB_DATABASE'), - }, - migrations: { - naturalSort: true, - paths: ['database/migrations'], - }, - }, - {{/if}} - }, -}) - -export default dbConfig From ae35d24eafdaaefaa66307cf21360184631454a8 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Tue, 26 Dec 2023 11:46:05 +0530 Subject: [PATCH 64/70] test: fix breaking tests --- index.ts | 1 - package.json | 2 +- test/configure.spec.ts | 20 ++++++++++++-------- 3 files changed, 13 insertions(+), 10 deletions(-) diff --git a/index.ts b/index.ts index 4d39b223..861b08d3 100644 --- a/index.ts +++ b/index.ts @@ -9,5 +9,4 @@ export * as errors from './src/errors.js' export { configure } from './configure.js' -export { stubsRoot } from './stubs/main.js' export { defineConfig } from './src/define_config.js' diff --git a/package.json b/package.json index 165cd50e..b94dfa17 100644 --- a/package.json +++ b/package.json @@ -55,7 +55,7 @@ "index:commands": "adonis-kit index build/commands" }, "dependencies": { - "@adonisjs/presets": "^1.0.0", + "@adonisjs/presets": "^1.0.2", "@faker-js/faker": "^8.3.1", "@poppinss/hooks": "^7.2.2", "@poppinss/macroable": "^1.0.1", diff --git a/test/configure.spec.ts b/test/configure.spec.ts index 65e6880a..6e87e914 100644 --- a/test/configure.spec.ts +++ b/test/configure.spec.ts @@ -20,6 +20,8 @@ test.group('Configure', (group) => { context.fs.basePath = fileURLToPath(BASE_URL) }) + group.each.disableTimeout() + test('create config file and register provider', async ({ fs, assert }) => { const ignitor = new IgnitorFactory() .withCoreProviders() @@ -45,7 +47,9 @@ test.group('Configure', (group) => { const ace = await app.container.make('ace') ace.prompt.trap('Select the database you want to use').chooseOption(2) - ace.prompt.trap('Do you want to install npm package "pg"?').reject() + ace.prompt + .trap('Do you want to install additional packages required by "@adonisjs/lucid"?') + .reject() const command = await ace.create(Configure, ['../../index.js']) await command.exec() @@ -67,7 +71,7 @@ test.group('Configure', (group) => { await assert.fileContains('start/env.ts', 'DB_USER: Env.schema.string()') await assert.fileContains('start/env.ts', 'DB_PASSWORD: Env.schema.string.optional()') await assert.fileContains('start/env.ts', 'DB_DATABASE: Env.schema.string()') - }).timeout(6000) + }) test('do not define env vars for sqlite dialect', async ({ fs, assert }) => { const ignitor = new IgnitorFactory() @@ -92,7 +96,7 @@ test.group('Configure', (group) => { const ace = await app.container.make('ace') ace.prompt.trap('Select the database you want to use').chooseOption(0) - ace.prompt.trap('Do you want to install npm package "sqlite3"?').reject() + ace.prompt.trap('Do you want to install additional packages required by "@adonisjs/lucid"?') const command = await ace.create(Configure, ['../../index.js']) await command.exec() @@ -104,7 +108,7 @@ test.group('Configure', (group) => { await assert.fileNotExists('.env') await assert.fileNotExists('start/env.ts') - }).timeout(6000) + }) test('create tmp directory for sqlite dialect', async ({ fs, assert }) => { const ignitor = new IgnitorFactory() @@ -129,13 +133,13 @@ test.group('Configure', (group) => { const ace = await app.container.make('ace') ace.prompt.trap('Select the database you want to use').chooseOption(0) - ace.prompt.trap('Do you want to install npm package "sqlite3"?').reject() + ace.prompt.trap('Do you want to install additional packages required by "@adonisjs/lucid"?') const command = await ace.create(Configure, ['../../index.js']) await command.exec() await assert.dirExists('tmp') - }).timeout(6000) + }) test('do not recreate tmp directory if it already exists', async ({ fs, assert }) => { const ignitor = new IgnitorFactory() @@ -161,11 +165,11 @@ test.group('Configure', (group) => { const ace = await app.container.make('ace') ace.prompt.trap('Select the database you want to use').chooseOption(0) - ace.prompt.trap('Do you want to install npm package "sqlite3"?').reject() + ace.prompt.trap('Do you want to install additional packages required by "@adonisjs/lucid"?') const command = await ace.create(Configure, ['../../index.js']) await command.exec() await assert.fileExists('tmp/db.sqlite') - }).timeout(6000) + }) }) From 9457f682e1039423aad77602dc4160ca5b04709b Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Tue, 26 Dec 2023 11:52:13 +0530 Subject: [PATCH 65/70] chore(release): 19.0.0-7 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index b94dfa17..c228e9f9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@adonisjs/lucid", - "version": "19.0.0-6", + "version": "19.0.0-7", "description": "SQL ORM built on top of Active Record pattern", "engines": { "node": ">=18.16.0" From 12a8a90befb6e134d919f112ac1939db3351671a Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Tue, 26 Dec 2023 11:57:42 +0530 Subject: [PATCH 66/70] chore: update peer dependencies --- package.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index c228e9f9..363d7f54 100644 --- a/package.json +++ b/package.json @@ -112,9 +112,9 @@ "typescript": "^5.3.3" }, "peerDependencies": { - "@adonisjs/assembler": "^6.1.3-22", - "@adonisjs/core": "^6.1.5-26", - "luxon": "^3.4.3" + "@adonisjs/assembler": "^7.0.0-1", + "@adonisjs/core": "^6.1.5-36", + "luxon": "^3.4.4" }, "peerDependenciesMeta": { "@adonisjs/assembler": { From 0fb73d415a68d4037543feea59f88f33588b40d6 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Tue, 26 Dec 2023 11:58:15 +0530 Subject: [PATCH 67/70] chore(release): 19.0.0-8 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 363d7f54..b61ee4f9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@adonisjs/lucid", - "version": "19.0.0-7", + "version": "19.0.0-8", "description": "SQL ORM built on top of Active Record pattern", "engines": { "node": ">=18.16.0" From 06422e1cc201d5205ab80f90d9bb4f40f7eb1e49 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Thu, 11 Jan 2024 07:28:08 +0530 Subject: [PATCH 68/70] chore(package): update dependencies --- package.json | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/package.json b/package.json index b61ee4f9..32e1a0c1 100644 --- a/package.json +++ b/package.json @@ -55,7 +55,7 @@ "index:commands": "adonis-kit index build/commands" }, "dependencies": { - "@adonisjs/presets": "^1.0.2", + "@adonisjs/presets": "^2.1.1", "@faker-js/faker": "^8.3.1", "@poppinss/hooks": "^7.2.2", "@poppinss/macroable": "^1.0.1", @@ -71,26 +71,26 @@ "tarn": "^3.0.2" }, "devDependencies": { - "@adonisjs/assembler": "^7.0.0-1", - "@adonisjs/core": "^6.1.5-36", - "@adonisjs/eslint-config": "^1.2.0", - "@adonisjs/prettier-config": "^1.2.0", - "@adonisjs/tsconfig": "^1.2.0", - "@commitlint/cli": "^18.4.3", - "@commitlint/config-conventional": "^18.4.3", + "@adonisjs/assembler": "^7.0.0", + "@adonisjs/core": "^6.2.0", + "@adonisjs/eslint-config": "^1.2.1", + "@adonisjs/prettier-config": "^1.2.1", + "@adonisjs/tsconfig": "^1.2.1", + "@commitlint/cli": "^18.4.4", + "@commitlint/config-conventional": "^18.4.4", "@japa/assert": "^2.1.0", "@japa/file-system": "^2.1.1", "@japa/runner": "^3.1.1", - "@swc/core": "^1.3.101", + "@swc/core": "^1.3.102", "@types/chance": "^1.1.6", - "@types/luxon": "^3.3.7", - "@types/node": "^20.10.5", + "@types/luxon": "^3.4.0", + "@types/node": "^20.10.8", "@types/pluralize": "^0.0.33", "@types/pretty-hrtime": "^1.0.3", "@types/qs": "^6.9.11", "@vinejs/vine": "^1.7.0", "better-sqlite3": "^9.2.2", - "c8": "^8.0.1", + "c8": "^9.0.0", "chance": "^1.1.11", "copyfiles": "^2.4.1", "cross-env": "^7.0.3", @@ -101,19 +101,19 @@ "github-label-sync": "^2.3.1", "husky": "^8.0.3", "luxon": "^3.4.4", - "mysql2": "^3.6.5", + "mysql2": "^3.7.0", "np": "^9.2.0", "pg": "^8.11.0", "prettier": "^3.1.1", "reflect-metadata": "^0.2.0", - "sqlite3": "^5.1.6", + "sqlite3": "^5.1.7", "tedious": "^16.6.1", "ts-node": "^10.9.2", "typescript": "^5.3.3" }, "peerDependencies": { - "@adonisjs/assembler": "^7.0.0-1", - "@adonisjs/core": "^6.1.5-36", + "@adonisjs/assembler": "^7.0.0", + "@adonisjs/core": "^6.2.0", "luxon": "^3.4.4" }, "peerDependenciesMeta": { From ae090bd093ff7ce41d05054284e5b3edd197f54d Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Thu, 11 Jan 2024 07:31:51 +0530 Subject: [PATCH 69/70] refactor: export stubsRoot --- index.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/index.ts b/index.ts index 861b08d3..4d39b223 100644 --- a/index.ts +++ b/index.ts @@ -9,4 +9,5 @@ export * as errors from './src/errors.js' export { configure } from './configure.js' +export { stubsRoot } from './stubs/main.js' export { defineConfig } from './src/define_config.js' From 57d9ca740faf43200da0f5db8258a169f1191eb1 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Thu, 11 Jan 2024 07:46:50 +0530 Subject: [PATCH 70/70] refactor: fix mess created by the merge --- test/database/query_builder.spec.ts | 43 +++-------------------------- test/orm/model_has_many.spec.ts | 2 +- 2 files changed, 5 insertions(+), 40 deletions(-) diff --git a/test/database/query_builder.spec.ts b/test/database/query_builder.spec.ts index dce8f3bd..c0352c37 100644 --- a/test/database/query_builder.spec.ts +++ b/test/database/query_builder.spec.ts @@ -451,41 +451,6 @@ test.group('Query Builder | where', (group) => { await connection.disconnect() }) - test('add where clause with a null comparison', async ({ assert }) => { - const connection = new Connection('primary', getConfig(), app.logger) - connection.connect() - - let db = getQueryBuilder(getQueryClient(connection, app)) - const { sql, bindings } = db.from('users').where('username', null).toSQL() - - const { sql: knexSql, bindings: knexBindings } = connection - .client!.from('users') - .where('username', null) - .toSQL() - - assert.equal(sql, knexSql) - assert.deepEqual(bindings, knexBindings) - - /** - * Using keys resolver - */ - db = getQueryBuilder(getQueryClient(connection, app)) - db.keysResolver = (key) => `my_${key}` - const { sql: resolverSql, bindings: resolverBindings } = db - .from('users') - .where('username', null) - .toSQL() - - const { sql: knexResolverSql, bindings: knexResolverBindings } = connection - .client!.from('users') - .where('my_username', null) - .toSQL() - - assert.equal(resolverSql, knexResolverSql) - assert.deepEqual(resolverBindings, knexResolverBindings) - await connection.disconnect() - }) - test('wrap where clause to its own group', async ({ assert }) => { const connection = new Connection('primary', getConfig(), logger) connection.connect() @@ -7020,7 +6985,7 @@ test.group('Query Builder | havingNull', (group) => { const { sql: knexSql, bindings: knexBindings } = (connection.client as any) .from('users') ['havingNull']('deleted_at') - ['orHavingNull']('updated_at') + .orHavingNull('updated_at') .toSQL() assert.equal(sql, knexSql) @@ -7038,7 +7003,7 @@ test.group('Query Builder | havingNull', (group) => { const { sql: knexResolverSql, bindings: knexResolverBindings } = (connection.client as any) .from('users') ['havingNull']('my_deleted_at') - ['orHavingNull']('my_updated_at') + .orHavingNull('my_updated_at') .toSQL() assert.equal(resolverSql, knexResolverSql) @@ -7110,7 +7075,7 @@ test.group('Query Builder | havingNotNull', (group) => { .from('users') .from('users') ['havingNotNull']('deleted_at') - ['orHavingNotNull']('updated_at') + .orHavingNotNull('updated_at') .toSQL() assert.equal(sql, knexSql) @@ -7128,7 +7093,7 @@ test.group('Query Builder | havingNotNull', (group) => { const { sql: knexResolverSql, bindings: knexResolverBindings } = (connection.client as any) .from('users') ['havingNotNull']('my_deleted_at') - ['orHavingNotNull']('my_updated_at') + .orHavingNotNull('my_updated_at') .toSQL() assert.equal(resolverSql, knexResolverSql) diff --git a/test/orm/model_has_many.spec.ts b/test/orm/model_has_many.spec.ts index 1b8562ee..39eb8606 100644 --- a/test/orm/model_has_many.spec.ts +++ b/test/orm/model_has_many.spec.ts @@ -3787,7 +3787,7 @@ if (process.env.DB !== 'mysql_legacy') { User.boot() const users = await User.query().preload('posts', (query) => { - query.groupLimit(2).groupOrderBy('created_at', 'asc') + query.groupLimit(2).groupOrderBy('created_at', 'desc') }) assert.lengthOf(users, 2)